windows.h與winsock2.h的包含順序引起的問題

來源:互聯網
上載者:User

使用環境:

Windows、C++

錯誤描述:

在項目中用到通訊端和線程,對應包含標頭檔 #include <winsock2.h>和#include <windows.h>

但是在編譯的時候碰到很多錯誤,而且幾乎都是“ 類型/連結重定義 ”、“ 找不到標識符 ”之類的錯誤,而且幾乎都出現在 winsock2.h和ws2def.h 中;

例如:

error C2011: “sockaddr_in”:“struct”類型重定義
ws2def.h

error C2375: “accept”: 重定義;不同的連結         winsock2.h

error C3861: “socket”: 找不到標識符                 server.cpp

錯誤原因:

做網路開發很多時候都會同時包含標頭檔

  #include <winsock2.h>

#include <windows.h>

如若順序不當( windows.h 先於 winsock2.h )就會出現很多莫名其妙的錯誤。

原因在於:windows.h中包含了winsock.h 標頭檔,而winsock2.h 中的很多內容會與 winsock.h 中的內容相同,從而導致類型的重定義(winsock2.h是winsock.h的後期版本)

解決辦法:

看如下內容可知,如果沒有定義宏 WIN32_LEAN_AND_MEAN,則會在windows.h中包含winsock.h

因此,解決辦法:

在包含<windows.h>之前定義WIN32_LEAN_AND_MEAN宏,如
下所示:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

補充:

windows.h中有如下內容:

#ifndef WIN32_LEAN_AND_MEAN
#include <cderr.h>
#include <dde.h>
#include <ddeml.h>
#include <dlgs.h>
#ifndef _MAC
#include <lzexpand.h>
#include <mmsystem.h>
#include <nb30.h>
#include <rpc.h>
#endif
#include <shellapi.h>
#ifndef _MAC
#include <winperf.h>

#if(_WIN32_WINNT >= 0x0400)
#include <winsock2.h>
#include <mswsock.h>
#else
#include <winsock.h>
#endif /* _WIN32_WINNT >=  0x0400 */

#endif
#ifndef NOCRYPT
#include <wincrypt.h>
#endif

#ifndef NOGDI
#include <commdlg.h>
#ifndef _MAC
#include <winspool.h>
#ifdef INC_OLE1
#include <ole.h>
#else
#include <ole2.h>
#endif /* !INC_OLE1 */
#endif /* !MAC */
#endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.