IT笔记 · 2014年2月21日

linux动态库的链接

参考:

编译链接时动态库搜索顺序(man ld):

The linker uses the following search paths to locate required shared libraries:

  1. Any directories specified by -rpath-link options.
  2. 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.
  3. On an ELF system, for native linkers, if the -rpath and -rpath-link options were not used, search the contents of the environment variable LD_RUN_PATH.
  4. On SunOS, if the -rpath option was not used, search any directories specified using -Loptions.
  5. For a native linker, the search the contents of the environment variable LD_LIBRARY_PATH.
  6. For a native ELF linker, the directories in DT_RUNPATH or DT_RPATH of a shared library are searched for shared libraries needed by it. The DT_RPATH entries are ignored if DT_RUNPATH entries exist.
  7. The default directories, normally /lib and /usr/lib.
  8. 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 -dobjdump查看
  • 指定库新路径,推荐使用优先级最低的/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,待确认