链接共享库的依赖项

Linking In Dependencies of a Shared Library

我创建了一个我希望其他人使用的库。

编译我的库:

 /usr/bin/g++ -fPIC -shared -Wl,-soname,libMYLIB.so [inputs] -lboost_system -lboost_thread

编译二进制文件:

/usr/bin/g++ myTest.cpp -lMYLIB -lboost_system

我希望那一行只是:

/usr/bin/g++ myTest.cpp -lMYLIB

如何避免以后必须指定我的库依赖项?我在寻找链接器或编译器中的什么标志?

有一个链接器选项(我的意思是ld链接器http://linux.die.net/man/1/ld)--unresolved-symbols=ignore-all or -unresolved-symbols=ignore-in-object-files:

Determine how to handle unresolved symbols. There are four possible values for method: 

* ignore-all 
    Do not report any unresolved symbols. 
* report-all 
    Report all unresolved symbols. This is the default. 
* ignore-in-object-files 
    Report unresolved symbols that are contained in shared libraries, but ignore them if they come from regular object files. 
* ignore-in-shared-libs 
    Report unresolved symbols that come from regular object files, but ignore them if they come from shared libraries. This can be useful

when creating a dynamic binary and it is known that all the shared libraries that it should be referencing are included on the linker's command line.

这是一个例子。我有一个库 libmylib.so 和一个应用程序 main:

所以我首先构建库:

$ g++ -fpic  -shared mylib.cpp -o libmylib.so

当我构建应用程序时,我没有在命令行上添加 -lmylib。通常它会导致错误 Unresolved external symbols 但由于我将 -Wl,--unresolved-symbols=ignore-in-object-files 添加到命令行,所以我没有收到任何错误:

$ g++ -fpic -g main.cpp -Wl,--unresolved-symbols=ignore-in-object-files  -Wl,-rpath,.

然后我运行我的程序:

$ ./a.out 
./a.out: symbol lookup error: ./a.out: undefined symbol: _Z7my_funcd

它没有按预期工作,但后来我使用 LD_PRELOAD:

$ LD_PRELOAD=./libmylib.so ./a.out                                                   
2

因此 LD_PRELOAD 有效