mar*_*hon 5 c++ macos shared-libraries
我正在尝试在mac osx上创建一个.so.似乎.so和.dylib类型之间存在区别.
$ file some_real.so
some_real.so: Mach-O 64-bit bundle x86_64
Run Code Online (Sandbox Code Playgroud)
dynamiclib标志按预期生成dylib
$ g++ -dynamiclib -o libgtest-1.7.0.dylib [my .o files]
$ file libgtest-1.7.0.dylib
libgtest-1.7.0.dylib: Mach-O 64-bit dynamically linked shared library x86_64
#### ^^^ as expected
Run Code Online (Sandbox Code Playgroud)
共享标志没有给出我想要的东西
$ g++ -shared -o libgtest-1.7.0.so [my .o files]
$ file libgtest-1.7.0.so
libgtest-1.7.0.dylib: Mach-O 64-bit dynamically linked shared library x86_64
#### ^^^ not as expected; wanted bundle x86_64
Run Code Online (Sandbox Code Playgroud)
这个stackoverflow回答谈了一下,并提到了-fPIC标志.我将它添加到命令行,它仍然生成一个dynlib
$ g++ -shared -fPIC -o libgtest-1.7.0.so [my .o files]
$ file libgtest-1.7.0.so
libgtest-1.7.0.dylib: Mach-O 64-bit dynamically linked shared library x86_64
#### ^^^ not as expected; wanted bundle x86_64
Run Code Online (Sandbox Code Playgroud)
(为什么:我需要此输出为.so/MH_BUNDLE类型,因为我正在尝试针对已经采用.so格式的内容创建一些谷歌测试,并且链接器拒绝链接gtest .dylib和我的.所以.)
如果您想构建一个bundle使用-bundle而不是-dynamiclib在创建文件时.
bundle和dylib之间最明显的区别是你可以在编译时链接到dylib.
例如g++ -o testfile testcode.c -lmylib将链接到libmylib.dylib,而如果您尝试链接您获得的包:
ld: can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB) file 'test.bundle' for architecture x86_64
Run Code Online (Sandbox Code Playgroud)
这是最大的区别 - 您无法动态链接包,而是必须dlopen或使用对象文件图像功能.我只是偏离了OS X的功能 - 它们已被弃用,您可以从dl*功能中获得所需的所有功能.
至于构建每个,我会举一个例子:
对象文件test.o,制作一个dylib:
g++ -dynamiclib -o test.dylib test.o
Run Code Online (Sandbox Code Playgroud)
捆绑:
g++ -bundle -o test.bundle test.o
Run Code Online (Sandbox Code Playgroud)
在运行时链接一个包并获取一个符号:
void *v = dlopen("test.bundle", RTLD_LOCAL);
// declare func_ptr as a pointer to a fn taking void, returning an int
int (*func_ptr)(void);
func_ptr = (int (*)(void))dlsym(v, "symbol");
Run Code Online (Sandbox Code Playgroud)
使用旧例程链接一个bundle (严重的是,不要这样做):
#include <mach-o/dyld.h>
int rc;
NSObjectFileImage img;
NSModule handle;
NSSymbol sym;
rc = NSCreateObjectFileImageFromFile("test.bundle", &img);
if (rc != NSObjectFileImageSuccess) {
fprintf(stderr, "Could not load libanswer.bundle.\n");
exit(-1);
}
/* Get a handle for the bundle. */
handle = NSLinkModule(img, "test.bundle", FALSE);
/* Look up the get_answer function. */
sym = NSLookupSymbolInModule(handle, "_get_answer");
if (sym == NULL)
{
fprintf(stderr, "Could not find symbol: _get_answer.\n");
exit(-2);
}
int (*func_ptr)(void);
func_ptr = NSAddressOfSymbol(sym);
Run Code Online (Sandbox Code Playgroud)
如果你正在使用clang编译,那么你会得到一堆警告:
warning: 'NSCreateObjectFileImageFromFile' is deprecated: first deprecated in OS X 10.5
Run Code Online (Sandbox Code Playgroud)
即请不要使用这些功能.
| 归档时间: |
|
| 查看次数: |
2274 次 |
| 最近记录: |