從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