【发布时间】:2010-11-04 14:09:45
【问题描述】:
我正在尝试使用模板类链接到共享库,但它给了我“未定义的符号”错误。我已经将问题压缩到大约 20 行代码。
shared.h
template <class Type> class myclass {
Type x;
public:
myclass() { x=0; }
void setx(Type y);
Type getx();
};
shared.cpp
#include "shared.h"
template <class Type> void myclass<Type>::setx(Type y) { x = y; }
template <class Type> Type myclass<Type>::getx() { return x; }
main.cpp
#include <iostream>
#include "shared.h"
using namespace std;
int main(int argc, char *argv[]) {
myclass<int> m;
cout << m.getx() << endl;
m.setx(10);
cout << m.getx() << endl;
return 0;
}
这是我编译库的方式:
g++ -fPIC -c shared.cpp -o shared.o
g++ -dynamiclib -Wl,-dylib_install_name -Wl,libshared.dylib -o libshared.dylib shared.o
还有主程序:
g++ -c main.cpp
g++ -o main main.o -L. -lshared
只得到以下错误:
Undefined symbols:
"myclass<int>::getx()", referenced from:
_main in main.o
_main in main.o
"myclass<int>::setx(int)", referenced from:
_main in main.o
如果我删除shared.h/cpp 中的“模板”内容,并将它们替换为“int”,一切正常。另外,如果我只是将模板类代码复制并粘贴到main.cpp,并且不链接到共享库,那么一切正常。
如何让这样的模板类通过共享库工作?
我正在使用带有 GCC 4.0.1 的 MacOS 10.5。
【问题讨论】:
标签: c++ templates gcc class linker