参考:
编译链接时动态库搜索顺序(man ld):
The linker uses the following search paths to locate required shared libraries:
- Any directories specified by
-rpath-link
options. - Any directories specified by
-rpath
options. The difference between-rpath
and-rpath-link
is that directories specified by-rpath
options are included in the executable and used at runtime, whereas the-rpath-link
option is only effective at link time. Searching-rpath
in this way is only supported by native linkers and cross linkers which have been configured with the--with-sysroot
option. - On an ELF system, for native linkers, if the
-rpath
and-rpath-link
options were not used, search the contents of the environment variableLD_RUN_PATH
. - On SunOS, if the
-rpath
option was not used, search any directories specified using-L
options. - For a native linker, the search the contents of the environment variable
LD_LIBRARY_PATH
. - For a native ELF linker, the directories in
DT_RUNPATH
orDT_RPATH
of a shared library are searched for shared libraries needed by it. TheDT_RPATH
entries are ignored ifDT_RUNPATH
entries exist. - The default directories, normally
/lib
and/usr/lib
. - For a native linker on an ELF system, if the file
/etc/ld.so.conf
exists, the list of directories found in that file.
NOTE
- If the linker is being invoked indirectly, via a compiler driver(e.g. gcc) then all the linker command line options should be prefixed by
-Wl
, (or whatever is appropriate for the particular compiler driver)like this:gcc -Wl,--start-group foo.o bar.o -Wl,--end-group
- linux可执行文件的elf信息,可用命令
readelf -d
或objdump
查看 - 指定库新路径,推荐使用优先级最低的
/etc/ld.so.conf
来指定,不推荐使用LD_LIBRARY_PATH
- 如果同名库冲突,可在编译时指定
-Wl,-rpath=新库路径
来避免运行时库冲突 - gcc编译时
-lsoname
之类的参数对应库名libsoname.so
,注意lib*.so
不带细版本号只针对编译链接时,如果该库有具体的 soname信息,比如lib*.so.0.10
,那么运行时会去寻找lib*.so.0.10
而不是lib*.so
ldconfig
会自动在/lib或/usr/lib或/etc/ld.so.conf指定的文件夹里生成soname link;或者用ldconfig -n path
来对指定路径进行soname软连接。- 如果把
rpath
路径设置为相对路径,似乎并不是以程序所在目录为参照,很可能是以当前所在目录pwd
,待确认