我想鏈接到一個模板類的共享庫,但它給我「未定義的符號」錯誤。我將問題簡化爲約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