macos 如何在 Mac OSX 下使用 gcc 设置可执行文件的运行时路径(-rpath)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4513799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the runtime path (-rpath) of an executable with gcc under Mac OSX?
提问by maxschlepzig
I want to set under Mac OSX the runtime path of an executable (for the linker) at compile time, such that shared libraries at non-standard locations are found by the dynamic linker at program start.
我想在 Mac OSX 下在编译时设置可执行文件(用于链接器)的运行时路径,以便动态链接器在程序启动时找到非标准位置的共享库。
Under Linux this is possible with -Xlinker -rpath -Xlinker /path/to
(or using -Wl,-rpath,/path/to
) and under Solaris you can add -R/path/to
to the compiler command line.
在 Linux 下,这可以使用-Xlinker -rpath -Xlinker /path/to
(或使用-Wl,-rpath,/path/to
),而在 Solaris 下,您可以将其添加-R/path/to
到编译器命令行。
I found some informationthat Mac OS X gcc has -rpath support since 10.5, i.e. since ~ 2008.
我发现一些信息表明 Mac OS X gcc 从 10.5 开始就支持 -rpath,即从 2008 年开始。
I tried to get it working with a minimal example - without success:
我试图用一个最小的例子让它工作 - 没有成功:
$ cat blah.c
int blah(int b)
{
return b+1;
}
And:
和:
$ cat main.c
#include <stdio.h>
int blah(int);
int main ()
{
printf("%d\n", blah(22));
return 0;
}
Compiled it like this:
编译成这样:
$ gcc -c blah.c
$ gcc -dynamiclib blah.o -o libblah.dylib
$ gcc main.c -lblah -L`pwd` -Xlinker -rpath -Xlinker `pwd`/t
Now the test:
现在测试:
$ mkdir t
$ mv libblah.dylib t
$ ./a.out
dyld: Library not loaded: libblah.dylib
Referenced from: /Users/max/test/./a.out
Reason: image not found
Trace/BPT trap
Thus the question: How to I set the runtime path for the linker under Mac OSX?
因此问题是:如何在 Mac OSX 下为链接器设置运行时路径?
Btw, setting DYLD_LIBRARY_PATH
works - but I don't want to use this hack.
顺便说一句,设置DYLD_LIBRARY_PATH
有效 - 但我不想使用这个黑客。
Edit:Regarding otool -L
:
编辑:关于otool -L
:
$ otool -L a.out
a.out:
libblah.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.1)
It seems that otool -L
only prints the library names (and probable the locations at link time) the executable was linked against and no runtime path information.
似乎otool -L
只打印可执行文件链接的库名称(以及链接时可能的位置),而没有运行时路径信息。
采纳答案by Ben Karel
Found by experimentation, and inspecting the command lines generated by Xcode for a reference rpath demo project by Dave Driblin:
通过实验发现,并检查 Xcode 生成的命令行以获取Dave Driblin的参考 rpath 演示项目:
otool -L
shows you the install name of the linked libraries. To get @rpath
to work, you need to change the install name of the library:
otool -L
显示链接库的安装名称。要开始@rpath
工作,您需要更改库的安装名称:
$ gcc -dynamiclib blah.o -install_name @rpath/t/libblah.dylib -o libblah.dylib
$ mkdir t ; mv libblah.dylib t/
$ gcc main.c -lblah -L`pwd`/t -Xlinker -rpath -Xlinker `pwd`