[Mingw-users] Including winsock2.h considered harmful?

Back to archive index

Eli Zaretskii eliz****@gnu*****
Sun Jul 29 04:21:26 JST 2018


> From: Keith Marshall <keith****@users*****>
> Date: Sat, 28 Jul 2018 19:40:45 +0100
> 
> >   #if !defined _WIN32_WINNT || _WIN32_WINNT < 0x501
> >   # undef _WIN32_WINNT
> >   # define _WIN32_WINNT 0x501
> >   #endif
> >   #include <winsock2.h>
> >   #include <ws2tcpip.h>
> > 
> > This used to work with MinGW runtime 3.x, but now fails, evidently
> > because winsock2.h no longer includes windows.h,
> 
> Actually, it does, but indirectly via <winsock.h>, with which it now
> shares code which is common to WinSock v1.1 and v2 protocols.

Hmm... you are right.  So the problem happens due to this chain of
events:

  . winsock2.h includes winsock.h
  . winsock.h defines __WINSOCK_H_SOURCED__
  . winsock.h then includes winerror.h
  . winerror.h sees that __WINSOCK_H_SOURCED__ is defined, and
    refrains from defining ERROR_* macros

> > So I need to include winerror.h before winsock2.h, in order to have
> > those error codes defined.
> 
> It shouldn't matter which order you include them; <winsock2.h> first,
> followed by <winerror.h> should work just as well.

Right.  But include it I must, yes?  In which case, at least for a
while, a solution such as the one below is the best I can use:

  #if defined __MINGW32_VERSION && __MINGW32_VERSION >= 5000002L
  # include <winerror.h>
  #endif
  #include <winsock2.h>

Or is there a better/cleaner way out, which doesn't break older w32api
versions (nor MinGW64, which doesn't define __MINGW32_VERSION)?

> > Do these programs do something that isn't "kosher" nowadays?  What
> > should a program do if it wants to include winsock2.h, but doesn't
> > want to include windows.h before that?  Is that allowed?
> 
> Yes.  In fact, IIRC, it is required for strict MSVC compatibility.
> 
> What is less clear cut is: should <winsock2.h>, (and indeed
> <winsock.h>), unconditionally expose all of <winerror.h>, or just those
> definitions which are relevant for the WinSock protocols?

The problems happen in programs that include winsock2.h, but also need
to handle Windows errors that have nothing to do with sockets.  I
think what w32api v5.0.2 does assumes that this combination cannot
happen, but it does, of course.

> On balance, it may be best to just expose all of <winerror.h>, whenever
> it is included

Agreed.

Thanks.




More information about the MinGW-Users mailing list
Back to archive index