工作中遇到可执行程序要使用单独的动态库目录,但是直接修改环境变量则会影响其他可执行文件。
查找资料时发现了编译增加-Wl,-rpath
选项可以实现这个功能,
当明确知道动态库的绝对路径时,
gcc test.c -o test -Wl,-rpath,/usr/local/mylib/ -lfoo
当仅知道动态库相对于可执行文件的相对路径时,使用$ORIGIN代表可执行文件路径,
gcc test.c -o test -Wl,-rpath,'$$ORIGIN/../mylib' -lfoo
多个路径用:
分割
编译成功之后可以通过readelf -dl test 查看设置的rpath
root@cpe bin $ readelf -dl evh test
Dynamic section at offset 0x35b3920 contains 30 entries:
Tag Type Name/Value
0x000000000000001d (RUNPATH) Library runpath: [$ORIGIN/../mylib]
网友评论