Why does MinGW-w64 require winsock2 to be manually included?

孤街醉人 提交于 2019-12-12 16:12:59

问题


Some code and associated warnings/errors:

#include <windows.h>
#include <iphlpapi.h>
int main() { }

F:/Prog/mingw-w64/x86_64-4.9.2-win32-seh-rt_v3-rev1/mingw64/x86_64-w64-mingw32/include/ws2ipdef.h:71:3: error: 'ADDRESS_FAMILY' does not name a type

ADDRESS_FAMILY si_family;
#include <windows.h>
#include <winsock2.h>
#include <iphlpapi.h>
int main() { }     // this compiles successfully, only gives warning

F:/Prog/mingw-w64/x86_64-4.9.2-win32-seh-rt_v3-rev1/mingw64/x86_64-w64-mingw32/include/winsock2.h:15:2: warning: #warning Please include winsock2.h before windows.h [-Wcpp]

#include <winsock2.h>
#include <windows.h>
#include <iphlpapi.h>
int main() { }

(compilation successful).

My questions are:

  • Why doesn't iphlpapi.h (and other files that rely on winsock) do #include <winsock2.h> themself, or at least give a nicer error message?
  • Why does there a warning for it to come before windows.h ?

回答1:


windows.h includes winsock.h by default. winsock.h and winsock2.h do not coexist. If winsock2.h is included first, it disables winsock.h, and all is good. But if winsock.h is included first, winsock2.h fails to compile, because it redeclares a lot of things that winsock.h already declares. Thus why you need to include winsock2.h first.

Microsoft wants people to use one or the other, not both. winsock2.h is meant to replace winsock.h rather than supplement it. But why they made winsock2.h so incompatible that it completely breaks if winsock.h is included first is anyone's guess. They could have just as easily made winsock2.h #ifdef any duplicate declarations to avoid errors. Or even have winsock2.h include winsock.h for the declarations. But they didn't.



来源:https://stackoverflow.com/questions/29069904/why-does-mingw-w64-require-winsock2-to-be-manually-included

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!