从DLL(Visual Studio 2008编译器)使用(专用)模板类时,出现链接器错误 - 未解析的符号。我试图用Stackoverflow中描述的'显式模板实例化'技巧,但它不起作用。我把它分解成一个非常简单的可重现的例子:链接器错误(无法解析的符号)与DLL中的模板类
我有一个动态库(DLL)'MyTemplates.lib'与头文件'MyTemplates.h'(和源文件'MyTemplates.cpp'没有任何代码它只是包含这个头文件),内容如下:
template <class T>
class A
{
public:
A()
{ int x = 7; }
};
template <class T>
class B : public A<T>
{
public:
B()
{}
};
// do explicit template instantiation for classes A<int> and B<int>
// macro 'MYTEMPLATES_API' is defined in the usual way as:
//#ifdef MYTEMPLATES_EXPORTS
// #define MYTEMPLATES_API __declspec(dllexport)
//#else
// #define MYTEMPLATES_API __declspec(dllimport)
//#endif
template class MYTEMPLATES_API A<int>;
template class MYTEMPLATES_API B<int>;
现在我有另一个动态库“UserLibary”(与文件的Util.h“和Util.cpp链接反对“MyTemplates.lib”) ”。文件“Util.h”如下:
#include "MyTemplates.h"
class UserClass
{
public:
UserClass();
public:
A<int> bla;
B<int> blubb;
};
和文件“Util.cpp”的内容是:现在,我的图书馆“UserLibrary”确实编译
#include "Util.h"
UserClass::UserClass()
{
}
的问题是好了,但它给了如下两个连接错误:
1>Util.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall B<int>::B<int>(void)" ([email protected]@@[email protected]) referenced in function "public: __thiscall UserClass::UserClass(void)" ([email protected]@[email protected])
1>Util.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall A<int>::A<int>(void)" ([email protected]@@[email protected]) referenced in function "public: __thiscall UserClass::UserClass(void)" ([email protected]@[email protected])
因此链接找不到类A<int>
和B<int>
默认的构造函数的符号。为什么这是可能的,我如何摆脱这些链接器错误?我认为类A<int>
和B<int>
(在'MyTemplates.h'文件中)的explict模板实例化可以解决这个问题,但不幸的是它似乎没有帮助 - 或者我以错误的方式使用它?我的编译器是Visual Studio 2008,操作系统是Windows 7 64位,代码编译为64位。
你在链接中包含mytemplates.lib吗? –
是的,我在项目'UserLibrary' – user2454869