注意:几个相关问题(例如,这个问题)最终被标记为与此问题重复。我知道这个特定问题,并按照相应答案中的解决方案进行操作。但是,不同的编译器会产生不同的行为,我不知道为什么。
我的库有一个类模板,我想为库中的某些模板参数提供实例,因为模板需要一些大量的编译时间。类模板可能如下所示 ( stack.hpp
)
#ifndef MY_STACK
#define MY_STACK
template<class T>
class stack
{
public:
stack();
};
#endif
它的实现驻留在相应的stack.tpp
文件中
#ifndef MY_STACK_TPP
#define MY_STACK_TPP
#include <iostream>
template<class T>
stack<T>::stack()
{
std::cout << "My stack constructor!" << std::endl;
}
#endif
由于我只想为某些模板参数提供支持,因此我stack.cpp
创建了以下显式模板实例:
#include "stack.hpp"
template class stack<double>;
template class stack<char>;
#include "stack.tpp"
这可以使用 g++ 和 clang++ 编译,但生成的共享库的符号存在差异:
g++ -std=c++11 -c stack.cpp -o stack.so
nm -C stack.so | grep stack
0000000000000049 t _GLOBAL__sub_I_stack.cpp
0000000000000000 W stack<char>::stack()
0000000000000000 W stack<char>::stack()
0000000000000000 n stack<char>::stack()
0000000000000000 W stack<double>::stack()
0000000000000000 W stack<double>::stack()
0000000000000000 n stack<double>::stack()
对比
clang++-7 -std=c++11 -c stack.cpp -o stack.so
nm -C stack.so | grep stack
0000000000000050 t _GLOBAL__sub_I_stack.cpp
在我的应用程序中,使用 clang++ 找不到这样一个显式实例化类的构造函数,但使用 g++ 可以正常工作。我认为这个基本的 MWE 给出了原因。谁能告诉我如何使用 clang++ 获取类模板的构造函数符号?