Skip to content
Advertisement

Duplicate static variable initialization in C++

I build a shared library “libMyLibrary.so” with a class “MyClass” that contains a static variable of type “MyClass”. Then I build an executable “MyLibraryTest” that I link against “libMyLibrary.so”. The main program uses “dlopen” to load dynamically a “.so” given as an argument.

While building, the library and executable are generated in a directory, say, “buildDir/bin”. Then I install the library into “installDir/lib” and the executable into “installDir/bin” (removing the runtime path from the executable).

When I run “buildDir/MyLibraryTest buildDir/MyLibrary.so” with LD_LIBRARY_PATH=buildDir, everything is fine.

But when I run “buildDir/MyLibraryTest installDir/lib/MyLibrary.so” with LD_LIBRARY_PATH=installDir/lib, a very strange thing occurs : – The static variable’s constructor is called twice (once before dlopen, once during dlopen) – At the end of the execution, the destructor is called twice, and this results into a crash.

Here is my code :

MyClass.h

JavaScript

MyClass.cpp

JavaScript

MyLibraryTest.cpp

JavaScript

Here are the compilation and link commands :

JavaScript

And at last here is what happens in the second case (duplicate initialization of the static variable) :

JavaScript

Any help would be greatly appreciated !!!

Advertisement

Answer

Thank you all for your answers. As Todd said, I forgot to include the link command for MyLibraryTest. Here it is :

JavaScript

The problem was related to the RPATH. If I do not use the -Wl,-rpath option any more, the test works fine !

I use CMake to build my projects, and found this : https://cmake.org/Wiki/CMake_RPATH_handling. Now I use the following command in my CMakeLists.txt, which removes the -Wl,-rpath link option.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement