OHMS BLOG

Tuesday, May 03, 2011

code

Fixing the winsock header file mess

Do you write Windows Sockets code? Are you having conflicts between winsock.h and winsock2.h?


If you take a look at winsock.h, you will notice that it uses the _WINSOCKAPI_ macro to prevent multiple inclusion. winsock2.h uses _WINSOCK2API_ to prevent multiple inclusion, but it also sets _WINSOCKAPI_ to fool the preprocessor into thinking that winsock.h has already been included.

Knowing this information, we can take this a step further and suppress winsock.h across the board (assuming Visual C++):

  1. First, modify your build system so that /D_WINSOCKAPI_ is always passed to the compiler. This makes the preprocessor think that winsock.h has already been included, so it never makes it past winsock.h's multiple inclusion preprocessor directives.
  2. Create a proxy header file using the following code snippet. Instead of including winsock2.h directly, always include the proxy header instead.
#ifndef __MYWINSOCK2_H
#define __MYWINSOCK2_H
#pragma push_macro("_WINSOCKAPI_")
// We clear _WINSOCKAPI_ to avoid preprocessor warnings about
// multiple definitions of the _WINSOCKAPI_ macro, as winsock2.h will
// attempt to #define _WINSOCKAPI_ itself.
#undef _WINSOCKAPI_
#include <winsock2.h>
#pragma pop_macro("_WINSOCKAPI_")
#endif // __MYWINSOCK2_H

2 comments:

Anonymous said...

NICE !!!
It works. Thanks a lot

Anonymous said...

Thanks so much, saved me many hours :)

Release 7.0; Copyright © 1996-2012 Aaron Klotz. All Rights Reserved.