複雜嗎?這要分類討論
1:情況一
如果類的定義裡面僅含有 編譯器內建的類型變數, int, float 等等. 或者成員函數僅使用了這些變數作為參數, 那麼很簡單.
直接
class __declspec(dllexport) YourClass
{
}
就行了.
2:情況二
如果類內部使用了別的類, 那麼別的類最好也匯出, 不然, 首先編譯的時候會出現編譯警告:
warning C4251: needs to have dll-interface
意思是,你使用另外的一些類型/介面, 但是這些類型或介面沒有匯出. 當你的client使用這些類型/介面的時候, 會出錯!
class __declspec(dllexport) YourClass
{
YourAnatherClass m_data; // 這裡會 出現 warning 4251. 如果YourAnatherClass 沒有匯出的話.
}
解決辦法就是: 在YourAnatherClass定義的地方加上
class __declspec(dllexport) YourAnatherClass
{
}
如上, 當你的YourAnatherClass沒有匯出的時候, dll的使用方會出現連結錯誤
3:情況三
當類的內部使用了STL模板的時候, 也會出現C4251警告, 情況會有所不同
class __declspec(dllexport) YourClass
{
vector<int> m_data; // 這裡會 出現 warning 4251. 因為vector<int>類型沒有被匯出
}
上面的使用模板(無論是stl模板,還是自訂模板)的代碼,編譯dll時會出現C4251警告, 但是dll的使用方, 卻不會出現連結錯誤!!!
這個因為, dll的使用方那裡也有一套模板的定義, 當他們使用那個vector<int>的時候, 雖沒有匯出, 但是使用者自己也有一套STL模板(或者是自訂的模板),使用者會利用自己的模板執行個體化這個dll中沒有匯出的東西!
所以, 對於因為使用STL(或模板)出現的c4251警告, 關閉之即可
#pragma warning(push)
#pragma warning(disable:4251)
//your declarations that cause 4251
#pragma warning(pop)
若想不使用通過關閉警告的方式關閉警告, 那麼就這樣
1)對於使用者自訂的模板
template class DLLImportExportMacro SomeTemplate<int>;
SomeTemplate<int> y;
2)對於STL的模板
template class DLLImportExportMacro std::allocator<int>
template class DLLImportExportMacro std::vector<int,
std::allocator<int> >;
vector<int> m_data;
參見:
http://www.unknownroad.com/rtfm/VisualStudio/warningC4251.html