Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?
like image 205
M.M Avatar asked Mar 16 '15 05:03

M.M


1 Answers

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.

like image 179
Remy Lebeau Avatar answered Sep 29 '22 19:09

Remy Lebeau