Inline
Inline

Reputation: 2843

libstdc++ static linking in dynamic library

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

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

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

Benjamin T
Benjamin T

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:

  • Use dynamic linkage for the STL
  • Ensure that incompatibilities do not cross the border of a binary (library, exe). The hard way to do this is to make your library expose only a C API (no C++).

Upvotes: -1

Related Questions