为什么Mac Os X中的Mach-O库需要install_name_tool和otool?
我正在使用最新版本的Xcode 4开发Cocoa应用程序,我想将动态库链接到我的项目(dylibs
).
I am developing a Cocoa Application using the latest version of Xcode 4, I want to link dynamic libraries to my project (dylibs
).
我在某处读到,在我的项目中添加库还不够,因为我必须运行install_name_tool
和otool
才能使我的项目使用项目中捆绑的库.
I read somewhere that adding the libraries in my project was not enough as I have to run install_name_tool
and otool
to make my project use the libraries that were bundled in my project.
我已经阅读了install_name_tool
的手册页,但是我不明白为什么必须这样做.
I have read the manual pages for install_name_tool
, but I do not understand WHY I have to do this.
图书馆如何运作?对应用程序和库的路径指向我的计算机中特定位置的部分特别感兴趣,例如运行otool -L
How do libraries work? Especially interested in the part where the application and the libraries have paths that point to specific places in my machine, like /usr/local/lib/mylibrary.dylib
when running otool -L
Apple有几种查找共享库的方法:
Apple has several ways of locating shared libraries:
-
@executable_path
:相对于主要可执行文件 -
@loader_path
:相对于引用二进制文件 -
@rpath
:相对于任何路径列表.
-
@executable_path
: relative to the main executable -
@loader_path
: relative to the referring binary -
@rpath
: relative to any of a list of paths.
@rpath
是OS X 10.5中引入的最新功能.
@rpath
is the most recent addition, introduced in OS X 10.5.
例如,如果您想将可执行文件放在Contents/MacOS
中,将库放在Contents/Libraries
中,则可以执行以下操作:
If for instance you want to have your executable in Contents/MacOS
and libraries in Contents/Libraries
you could do the following:
install_name_tool -id @rpath/Libraries/lib_this.dylib builddir/lib_this.dylib
,并在顶级可执行文件集rpath
中设置为:
and in the top-level executable set rpath
with:
install_name_tool -add_rpath @loader_path/.. myexecutable
和:
install_name_tool -change builddir/lib_this.dylib @rpath/Libraries/lib_this.dylib myexecutable
注意:-change
之后的第一个路径必须与二进制文件中的当前路径完全匹配.
Note: that the first path after -change
must match exactly what is currently in the binary.
如果迷路了,otool -l -v myexecutable
会告诉您可执行文件中当前到底有哪些加载命令.
If you get lost otool -l -v myexecutable
will tell you what load commands exactly are currently in the executable.
有关更多信息,请参见man dyld
和man install_name_tool
.
See man dyld
and man install_name_tool
for more information.