运行时链接到不在LD_LIBRARY_PATH上的动态库 [英] Run-time linking to dynamic libraries not on LD_LIBRARY_PATH
问题描述
我正在尝试将我的项目链接到放置在项目基本目录[proj_dir]/lib上的一组特定的自定义编译库-而不是系统的任何/lib,/usr/lib或/usr/local/lib-避免与已安装的相同库的版本冲突.
我可以通过传递带有 -L
标志的库路径来编译项目,但是在加载共享库libXXX.so时出现错误:无法打开共享对象文件:当我运行编译的二进制文件时,没有这样的文件或目录
,并且 ldd
告诉我找不到那些特定的库.
另一方面,如果将 LD_LIBRARY_PATH = [proj_dir]/lib
传递给可执行文件,则可以运行它而不会出现问题.还有,是否有一种隐式链接这些库的方法,而不必在运行时手动设置 LD_LIBRARY_PATH
?
您可以
- 在调用实际程序之前写一个包装脚本,使其始终包含
LD_LIBRARY_PATH
(更灵活). - 将
-Wl,-rpath =<目录>
添加到链接器选项,以将目录添加到运行时库搜索路径.因此,假设您有一个libfoo.so
,并且您的程序和DSO应该位于同一目录中,那么您的编译命令应如下所示:gcc -o myprogam main.c -L.-lfoo -Wl,-rpath ='$ ORIGIN'
.
更新:如Maxim所指出的那样,设置 -rpath =.
gcc联机帮助页,有关 -rpath
的信息,请参见 ld联机帮助页./p>
I'm trying to link a project of mine to a particular set of custom-compiled libraries placed on the project's base directory [proj_dir]/lib - not on any of the system's /lib, /usr/lib or /usr/local/lib - to avoid conficts with the installed stock versions of those same libraries.
I'm able to compile the project by passing the library path with the -L
flag, but I get error while loading shared libraries libXXX.so: cannot open shared object file: No such file or directory
when I run the compiled binary, and ldd
tells me it can't find those particular libs.
On the other hand, I am able to run it without issue if I pass LD_LIBRARY_PATH=[proj_dir]/lib
to the executable. Still, is there a way to link those libraries implicitly, without having to manually set the LD_LIBRARY_PATH
at runtime?
You can either
- Write a wrapper script to always include
LD_LIBRARY_PATH
before calling the actual program (more flexible). - Add
-Wl,-rpath=<directory>
to your linker options to add a directory to the runtime library search path. So assuming you have alibfoo.so
and your program and DSO should lie in the same directory, your compilation command could look like this:gcc -o myprogam main.c -L. -lfoo -Wl,-rpath='$ORIGIN'
.
Update: As correctly noted by Maxim, setting -rpath=.
is dangerous and should be avoided.
For -Wl,
, see the gcc manpage and for -rpath
see the ld manpage.
这篇关于运行时链接到不在LD_LIBRARY_PATH上的动态库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!