我想链接到一个模板类的共享库,但它给我“未定义的符号”错误。我将问题简化为约20行代码。C++共享库模板:未定义的符号错误
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;
}
这是我编的lib郭宝宏:
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
中,并且不链接到共享库,则一切正常。
如何,我可以得到一个模板类,像这样通过一个共享库的工作?
我使用的MacOS 10.5 GCC 4.0.1。
Duplicate:http://stackoverflow.com/questions/999358/undefined-symbols-linker-error-with-simple-template-class/999383#999383 – 2009-06-20 21:48:21