rpath添加依赖库搜索路径

windows 下一个程序的dll搜索路径首先是程序目录,然后是一些系统目录。linux 下的可以通过设置 LD_LIBRARY_PATH 等方法添加搜索路径,但是这些路径是定死的,如果要实现程序目录,就要使用链接时的rpath选项。rpath 适用于 elf 文件,不适用 pe。

Linux 上动态库搜索顺序:

Unless loading object has RUNPATH:
RPATH of the loading object,
then the RPATH of its loader (unless it has a RUNPATH),...,
until the end of the chain,which is either the executable
or an object loaded by dlopen(loader 为可执行程序或被 dlopen 打开的对象)
Unless executable has RUNPATH:
RPATH of the executable
LD_LIBRARY_PATH
RUNPATH of the loading object
ld.so.cache
default dirs


rpath 用法

ld:
[plain] view plain copy
  1. -rpathdiror--rpath=dir
为了兼容其他 ELF 链接器,如果 -R 选项的值是个目录而不是文件,那么此时相当与 -rpath
注:-R filename 与 --just-symbols=filename 等价
如果链接时没使用 '-rpath' ,那么如果定义了 LD_RUN_PATH 就会使用该值作为 rpath
ld 如果不是直接被调用的,而是是通过一个驱动程序如 gcc 调用,那么的所有的链接选项都需要加上前缀 "-Wl,", 选项和值之间用","隔开

所以gcc的rpath用法:

copy
    -Wl,-rpath,dir

多个dir之间用冒号分隔:

copy


    $ORIGING

    代表程序目录,需要加单引号,否则会被解释为变量ORIGIN的值。这样gcc的链接flags为
    copy

    copy
    '-Wl,$ORIGIN'

用 readelf 查看编译后的程序
copy
    readelf-dpath
会发现多了类似与这么一行
copy
    0x0000000f(RPATH)Libraryrpath:[$ORIGIN]

这样,程序运行前会先搜索程序所在路径有没有依赖的库。


Makefile 中的写法: 注意Makefile里要用两个$$,只用一个$会展开成变量值,$$相当与转义成$
copy
    LFLAGS+='-Wl,$$dir'

qmake 工程中的写法:

copy
    QMAKE_LFLAGS+=-Wl,\'\$\$dir\'
copy
    QMAKE_RPATHDIR+=:\'\$\$dir\'
注意QMAKE_RPATHDIR最开始要加冒号,因为生成Makefile会自动在前面加上-Wl,$$PWD
bash 里执行 make 命令:
copy
    makeLDFLAGS="'-Wl,-R,\$\$ORIGIN'"

其他有待调查的问题

1. ld -z -origin 或 g++ -Wl,-z,origin
不知道这个有什么作用,文档里一笔带过没看明白。readelf 看了下多了类似与如下的一行

0x6ffffffb (FLAGS_1) Flags: ORIGIN
2. macx
@executable_path : relative to the main executable
@loader_path : relative to the referring binary
@rpath : relative to any of a list of paths.
from qtcreator/src/rpath.pri:
!isEmpty(TIGER_COMPAT_MODE) {
QMAKE_LFLAGS_SONAME = -Wl,-install_name,@executable_path/../PlugIns/
} else {
QMAKE_LFLAGS += -Wl,@loader_path,@executable_path
}
使用 otool 查看
3. clang
4. RUNPATH,DT_RUNPATH
参考文献: http://itee.uq.edu.au/~daniel/using_origin/
http://stackoverflow.com/questions/9263256/can-you-please-help-me-understand-how-mach-o-libraries-work-in-mac-os-x
http://stackoverflow.com/questions/6324131/rpath-origin-not-having-desired-effect
http://www.delorie.com/gnu/docs/binutils/ld_3.html
http://labs.qt.nokia.com/2011/10/28/rpath-and-runpath/
http://blog.csdn.net/dbzhang800/article/details/6918413

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...