2013-06-05 31 views
0

从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位。

+0

你在链接中包含mytemplates.lib吗? –

+0

是的,我在项目'UserLibrary' – user2454869

回答

0

您的问题描述并不能说明您为什么需要拥有该DLL。无论如何,我只会开发 头文件库,当其中的所有内容都是模板时。因此无需导入 或导出,只需要#include,如果您需要某些东西。

+0

的项目设置中将'MyTemplates.lib'添加到链接器的'其他依赖项'中。我只有模板类A和B,没有'显式模板实例化'。问题在于(据我所知),当在'UserLibrary'库的多个.cpp文件中使用类A和B时,出现连接器错误,抱怨成员fns的'一个或多个多重定义的符号'。的A和B.所以我添加了这个'明确的模板瞬时'的东西,在各种论坛上搜索这个问题后。 – user2454869

相关问题