Search code examples
c++boost-asiowinsockc-preprocessorwinsock2

Boost::asio winsock and winsock 2 compatibility issue


My project uses windows.h in which winsock.h is used, and I need to include boost:assio which uses winsock2. So I get many errors that says Winsock.h already included. I can define WIN32_LEAN_AND_MEAN. so that windows.h wouldn't use winsock. The problem is , that I need windows.h to use it, and I just need Asio for asynchronous timers. I don't need its winsock2.h . I tried searching how to disable its winsock2 use, and I found that I could do that by defining BOOST_ASIO_NO_WIN32_LEAN_AND_MEAN before including boost:asio, but I still get the same error.

#include <windows.h>
#define BOOST_ASIO_NO_WIN32_LEAN_AND_MEAN
#include <boost/asio.hpp>

Error

1>c:\program files\boost\boost_1_47\boost\asio\detail\socket_types.hpp(22): fatal error C1189: #error : WinSock.h has already been included


Solution

  • As Danius (the OP) points out a compile with

    #include <windows.h>
    #include <boost/asio.hpp>
    

    fails with this error:

    1>c:\source\<SNIP>\boost\1.51.0\boost\asio\detail\socket_types.hpp(22): fatal error C1189: #error :  WinSock.h has already been included
    

    On the other hand

    #include <boost/asio.hpp>
    #include <windows.h>
    

    Produces a bunch of noise and sets the windows version # incorrectly

    1?  Please define _WIN32_WINNT or _WIN32_WINDOWS appropriately. For example:
    1>  - add -D_WIN32_WINNT=0x0501 to the compiler command line; or
    1>  - add _WIN32_WINNT=0x0501 to your project's Preprocessor Definitions.
    1>  Assuming _WIN32_WINNT=0x0501 (i.e. Windows XP target).
    

    I couldn't find any way around this that didn't leave a bad taste, but this:

    #ifdef _WIN32
    #  ifdef USE_ASIO
    //     Set the proper SDK version before including boost/Asio
    #      include <SDKDDKVer.h>
    //     Note boost/ASIO includes Windows.h. 
    #      include <boost/asio.hpp>
    #   else //  USE_ASIO
    #      include <Windows.h>
    #   endif //  USE_ASIO
    #else // _WIN32
    #  ifdef USE_ASIO
    #     include <boost/asio.hpp>
    #  endif // USE_ASIO
    #endif //_WIN32
    

    Does produce a clean compile.

    <EDITORIAL> It shouldn't be that hard </EDITORIAL>