dll中匯出一個類.匯出模板STL.vector,遭遇的警告.

來源:互聯網
上載者:User

複雜嗎?這要分類討論

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.