天天看点

【原创】Linux下共享库嵌套依赖问题

问题场景: 

动态库 librabbitmq_r.so 内部依赖动态库 libevent_core.so 和 libevent_pthreads.so ;

可执行程序 sa 依赖动态库 librabbitmq_r.so ;

在链接生成 sa 的时候希望只指定 librabbitmq_r.so 而不指定 libevent_core.so 和 libevent_pthreads.so 。

错误信息: 

      由错误信息可以看出,未找到的符号均属于 libevent_core.so 和 libevent_pthreads.so 内部。但这两个库确实存在于 -l../../../../10-common/lib/release/linux 路径下,但为什么链接器仍旧无法找到对应的库和符号呢? 

下面的文章讨论了这个问题(下面给出部分摘录)

... 

you system, through ld.so.conf, ld.so.conf.d, and the system environment, ld_library_path, etc.., provides the system-wide library search paths which are supplemented by installed libraries through pkg-config information and the like when you build against standard libraries.  

there is no standard run-time library search path for custom shared libraries you create yourself. you specify the search path to your libraries through the -l/path/to/lib designation during compile and link. for libraries in non-standard locations, the library search path can be optionally placed in the header of your executable (elf header) at compile-time so that your executable can find the needed libraries. 

rpath provides a way of embedding your custom run-time library search path in the elf header so that your custom libraries can be found as well without having to specify the search path each time it is used. this applies to libraries that depend on libraries as well. as you have found, not only is the order you specify the libraries on the command line important, you also must provide the run-time library search path, or rpath, information for each dependent library you are linking against as well so that the header contains the location of all libraries needed to run. 

back to the semantics of ld. in order to produce a "good link", ld must be able to locate all dependent libraries. ld cannot insure a good link otherwise. the runtime linker must find and load, not just to find the shared libraries needed by a program. ld cannot guarantee that will happen unless ld itself can locate all needed shared libraries at the time the progam is linked. 

结论就是,像这种 a.so 依赖 b.so ,而 c 依赖 a.so 的情况,在链接过程中需要通过 -rpath-link 指定所需 .so 的位置,而不能仅仅使用 -l 指定。 

示例如下: 

【say_hello.c】 

【say_hello.h】 

【time_print.c】 

【time_print.h】 

【main.c 】 

生成两个 .so 库 

若不指定 -rpath-link 选项,则链接失败 

若指定 -rpath-link 选项,则可以成功链接 

查看一下共享库依赖关系 

执行程序 

继续阅读