依赖于同一个静态链接库的可执行文件和共享库

问题描述:

假设您正在开发一个共享库 libshared.so.

Suppose you're developing a shared library libshared.so.

并且您有一个静态库 libstatic.a,其中包含您需要的一些内部类和功能.您想像这样将它链接到您的 .so:

And you have a static library libstatic.a with some internal classes and functionality you need. You'd like to link it to your .so like this:

g++ -o libshared.so -shared myObj.o -lstatic

您还有一个 executable.sh 它将使用您的 .so 并在运行时动态打开它

Also you have an executable.sh which will use your .so and dynamically open it in the runtime

dlopen(libshared.so", RTLD_NOW)

您知道此可执行文件也与 libstatic.a 静态链接(但您不确定该库的版本是否与您的完全相同).

You know this executable was as well statically linked against libstatic.a (but you're not sure the version of the library is exactly the same as yours).

当您知道 executable.shlibshared.solibstatic.a 静态链接是否安全和正确?/代码>?

Is it safe and correct to statically link your libshared.so against libstatic.a when you know the same library is already used in executable.sh?

您应该避免将静态库链接到共享库中.

You should avoid linking a static library into a shared one.

因为共享库应该有位置无关代码(否则,动态链接器有做太多重定位,失去共享库的好处),但静态库通常没有PIC.

Because a shared library should have position independent code (otherwise, the dynamic linker has to do too much relocation, and you lose the benefits of shared libraries), but a static library usually does not have PIC.

阅读Drepper 的论文:如何编写共享库

您使用

  g++ -Wall -O -fPIC mySrc.cc -c -o myObj.pic.o
  g++ -o libshared.so -shared myObj.pic.o -lotherlib