我正在尝试使用模板类链接到共享库,但它给了我"未定义的符号"错误.我已经将问题浓缩为大约20行代码.
shared.h
template <class Type> class myclass {
Type x;
public:
myclass() { x=0; }
void setx(Type y);
Type getx();
};
Run Code Online (Sandbox Code Playgroud)
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; }
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
这是我编译库的方式:
g++ -fPIC -c shared.cpp -o …Run Code Online (Sandbox Code Playgroud) 我已经看过一些相关的 帖子,但是我无法理解我需要做些什么来修复我正在为入门级C++课程制作的程序.
我的错误是:
Build Final Project of project Final Project with configuration Debug
Ld "build/Debug/Final Project" normal x86_64
cd "/Users/nick/Dropbox/|Syncs/Xcode/Final Project"
setenv MACOSX_DEPLOYMENT_TARGET 10.6
/Developer/usr/bin/g++-4.2 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.6.sdk "- L/Users/nick/Dropbox/|Syncs/Xcode/Final Project/build/Debug" "-F/Users/nick/Dropbox/|Syncs/Xcode/Final Project/build/Debug" -filelist "/Users/nick/Dropbox/|Syncs/Xcode/Final Project/build/Final Project.build/Debug/Final Project.build/Objects-normal/x86_64/Final Project.LinkFileList" -mmacosx-version-min=10.6 -o "/Users/nick/Dropbox/|Syncs/Xcode/Final Project/build/Debug/Final Project"
Undefined symbols:
"Vector<double>::Vector()", referenced from:
_main in main.o
"Vector<double>::length()", referenced from:
_main in main.o
"Vector<double>::Vector(double const&, double const&, double const&)", referenced from:
_main in main.o
_main in main.o
"Vector<double>::getx() const", referenced from:
_main …Run Code Online (Sandbox Code Playgroud)