我在 dylib 的 cmake 配置上遇到了一些困难。
这是我的测试:
mylibfunc.cpp
#include <stdio.h>
static int count = 0;
extern "C"
{
int mylibfunc()
{
count++;
return count;
}
}
基本测试.cpp
#include <stdio.h>
#include <dlfcn.h>
#include <mach-o/dyld.h>
typedef int (*funcPtr)();
int main()
{
// Load first library
void* handleA = dlopen("libmylib.dylib", RTLD_LAZY);
funcPtr functionA = (int(*)())dlsym(handleA, "mylibfunc");
fprintf(stderr, "Handle A: %p\tFunction A: %p\t Count: %d\n", handleA, functionA, (*functionA)());
// Reload same library
void* handleB = dlopen("libmylib.dylib", RTLD_LAZY);
funcPtr functionB = (int(*)())dlsym(handleB, "mylibfunc");
fprintf(stderr, "Handle B: %p\tFunction B: %p\t Count: %d\n", handleB, functionB, (*functionB)());
// Load copy of first library (just rename)
void* handleC = dlopen("libmylib_copy.dylib", RTLD_LAZY);
funcPtr functionC = (int(*)())dlsym(handleC, "mylibfunc");
fprintf(stderr, "Handle C: %p\tFunction C: %p\t Count: %d\n", handleC, functionC, (*functionC)());
return 0;
}
CMakeLists:
cmake_minimum_required(VERSION 2.8.11)
SET(src_dir mylibfunc.cpp)
add_library(mylib SHARED ${src_dir})
target_link_libraries(mylib ${EXTRA_LIBS})
在命令行上测试 1:
clang++ -dynamiclib mylibfunc.cpp -o libmylib.dylib
cp libmylib.dylib libmylib_copy.dylib
clang++ basictest.cpp -o basictest
./basictest
输出:
Handle A: 0x7fba614039b0 Function A: 0x10f7a5f50 Count: 1
Handle B: 0x7fba614039b0 Function B: 0x10f7a5f50 Count: 2
Handle C: 0x7fba61403de0 Function C: 0x10f7d8f50 Count: 1
--> 每个库都有自己的静态计数,工作正常。
使用 cmake 测试 2:
cmake -G"Xcode"
open Project.xcodeproj and build project on xcode 4
cp libmylib.dylib libmylib_copy.dylib
clang++ basictest.cpp -o basictest
./basictest
输出:
Handle A: 0x7ff5424039b0 Function A: 0x104a63f50 Count: 1
Handle B: 0x7ff5424039b0 Function B: 0x104a63f50 Count: 2
Handle C: 0x7ff5424039b0 Function C: 0x104a63f50 Count: 3
--> 每个库共享同一个计数器,这不是我想要的......
我应该在 cmake 或 xcode 属性中进行哪些更改?