Reputation: 2843
To understand question I should tell you more about program that loads dynamic library. It's Half-Life Dedicated server. It uses old libstdc++ which is located next to executable. To avoid issues, when using features from new standard library I usually link my project staticaly to libstdc++.
My friend told me that libstdc++ static linking can create problems, if 2 compiled with different compilers libraries are loaded or when I call function from server (which is internally implemented in terms of old libstdc++).
Is it true? How can I resolve this issue?
Upvotes: 5
Views: 4759
Reputation: 136198
The API your shared library exposes must use the same ABI that the host application expects, i.e. the types involved must be of the same layout, size and alignment.
If there are std::
types exposed in the API or it throws C++ exceptions, then that means the shared library must be compiled using the same standard library headers and macros defined. In this case you can link dynamically to that libstdc++
that comes with the host application.
If there are no std::
types exposed in the API and no exceptions are thrown from the shared library, you can link statically to libstdc++
. However, all external symbols are still going to be exposed from the shared library, so that when it is loaded with a call to dlopen
without RTLD_DEEPBIND
flag, it will use the symbols with the same name from the host application if they are available instead of the ones you hoped to link in statically, which may cause that undefined behavior your friend probably refers to. To avoid this, a linker version script is required to make all symbols in your shared library local and only expose the API symbols as global. Something like:
MYHALFLIFEPLUGIN_0.0 {
global: half_life_foo,half_life_bar; # Explicitly list symbols to be exported.
local: *; # Hide everything else.
};
And direct the linker to use this script with -Wl,--version-script=<filename>
compiler linker option (LDFLAGS
). In addition to -static-libstdc++
option, you will need -static-libgcc
linker option.
Also, have a read through
for more details.
Upvotes: 8
Reputation: 8311
Yes it is true. The easiest example is if you create an object with new
in a library and delete
it in another library that does not use the same STL.
You have 2 solutions:
Upvotes: -1