我有一个C++动态库(在macOS上),它有一个模板化的函数,带有一些在公共API中导出的显式实例化.客户端代码只能看到模板声明; 他们不知道里面发生了什么,并依赖这些实例在链接时可用.
出于某种原因,只有一些显式实例化在动态库中可见.
这是一个简单的例子:
// libtest.cpp
#define VISIBLE __attribute__((visibility("default")))
template<typename T> T foobar(T arg) {
return arg;
}
template int VISIBLE foobar(int);
template int* VISIBLE foobar(int*);
Run Code Online (Sandbox Code Playgroud)
我希望两个实例都可见,但只有非指针实例是:
$ clang++ -dynamiclib -O2 -Wall -Wextra -std=c++1z -stdlib=libc++ -fvisibility=hidden -fPIC libtest.cpp -o libtest.dylib
$ nm -gU libtest.dylib | c++filt
0000000000000f90 T int foobar<int>(int)
Run Code Online (Sandbox Code Playgroud)
此测试程序无法链接,因为缺少指针1:
// client.cpp
template<typename T> T foobar(T); // assume this was in the library header
int main() {
foobar<int>(1);
foobar<int*>(nullptr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
$ clang++ -O2 -Wall -Wextra -std=c++1z -stdlib=libc++ …Run Code Online (Sandbox Code Playgroud)