Fighting Windows Sockets Legacy Troubles
I came across a really annoying problem while using win32 sockets one of my bigger projects. In short, the VisualC compiler complained about redefinitions of basic Windows socket macros:
C:\sdk\windows\v6.0a\include\ws2def.h(91) : warning C4005: 'AF_IPX' : macro redefinition C:\sdk\windows\v6.0a\include\winsock.h(460) : see previous definition of 'AF_IPX' C:\sdk\windows\v6.0a\include\ws2def.h(124) : warning C4005: 'AF_MAX' : macro redefinition C:\sdk\windows\v6.0a\include\winsock.h(479) : see previous definition of 'AF_MAX' C:\sdk\windows\v6.0a\include\ws2def.h(163) : warning C4005: 'SO_DONTLINGER' : macro redefinition C:\sdk\windows\v6.0a\include\winsock.h(402) : see previous definition of 'SO_DONTLINGER' C:\sdk\windows\v6.0a\include\ws2def.h(206) : error C2011: 'sockaddr' : 'struct' type redefinition C:\sdk\windows\v6.0a\include\winsock.h(485) : see declaration of 'sockaddr' C:\sdk\windows\v6.0a\include\ws2def.h(384) : error C2143: syntax error : missing '}' before 'constant' C:\sdk\windows\v6.0a\include\ws2def.h(384) : error C2143: syntax error : missing ';' before 'constant' C:\sdk\windows\v6.0a\include\ws2def.h(384) : error C2059: syntax error : 'constant' C:\sdk\windows\v6.0a\include\ws2def.h(437) : error C2143: syntax error : missing ';' before '} (...)
After some digging in the code I noticed that windows.h had been included before winsock2.h. And that windows.h includes winsock.h. When digging deeper, I found an article in the MSDN describing what had happened here:
actually, this is a legacy problem. In Windows versions <= Windows 98, WinSock 1.1 had been used. The current win32 socket implementation, Windows Sockets 2 (WinSock 2.0), is backwards compatible to Windows Sockets 1.1. Additionally, the winsock2.h header files prevents the inclusion of the legacy winsock.h header file. But once you include winsock.h, you can not include winsock2.h later on.
Unfortunately, windows.h still includes winsock.h.
Fortunately, you can disable the legacy parts of the Windows SDK easily:
#define WIN32_LEAN_AND_MEANYou will not be able to build Windows 95/Windows 98 applications when using this definition. But if you were targeting those OS versions, you wouldn’t be using Windows Sockets 2 anyway.