如何在 Mac OSX 下使用 gcc 设置可执行文件的运行时路径(-rpath)? [英] How to set the runtime path (-rpath) of an executable with gcc under Mac OSX?
问题描述
我想在 Mac OSX 下在编译时设置可执行文件(用于链接器)的运行时路径,以便动态链接器在程序启动时找到非标准位置的共享库.
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.
在 Linux 下,这可以通过 -Xlinker -rpath -Xlinker/path/to
(或使用 -Wl,-rpath,/path/to
)和在 Solaris 下实现您可以将 -R/path/to
添加到编译器命令行.
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.
我发现 一些信息 Mac OS X gcc 从 10.5 开始支持 -rpath,即自 2008 年以来.
I found some information that Mac OS X gcc has -rpath support since 10.5, i.e. since ~ 2008.
我试图用一个最小的例子让它工作 - 没有成功:
I tried to get it working with a minimal example - without success:
$ cat blah.c
int blah(int b)
{
return b+1;
}
还有:
$ cat main.c
#include <stdio.h>
int blah(int);
int main ()
{
printf("%d
", blah(22));
return 0;
}
编译如下:
$ gcc -c blah.c
$ gcc -dynamiclib blah.o -o libblah.dylib
$ gcc main.c -lblah -L`pwd` -Xlinker -rpath -Xlinker `pwd`/t
现在测试:
$ 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
因此问题:如何在 Mac OSX 下为链接器设置运行时路径?
Thus the question: How to I set the runtime path for the linker under Mac OSX?
顺便说一句,设置 DYLD_LIBRARY_PATH
有效 - 但我不想使用这个 hack.
Btw, setting DYLD_LIBRARY_PATH
works - but I don't want to use this hack.
关于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)
似乎 otool -L
只打印可执行文件链接的库名称(可能还有链接时的位置),没有运行时路径信息.
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.
推荐答案
通过实验发现,并检查 Xcode 生成的命令行以获取 参考 Dave Driblin 的 rpath 演示项目:
Found by experimentation, and inspecting the command lines generated by Xcode for a reference rpath demo project by Dave Driblin:
otool -L
显示链接库的安装名称.要使 @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:
$ 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`
这篇关于如何在 Mac OSX 下使用 gcc 设置可执行文件的运行时路径(-rpath)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!