2013-06-05 41 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

相關問題