timeval undefined when using windows.h and WIN32_LEAN_AND_MEAN

8.2k Views Asked by At

To avoid conflicts with winsock2.h, I want to wrap my include of windows.h with WIN32_LEAN_AND_MEAN (I undef it after windows.h so as not to interfere with applications that include my headers). Doing this causes timeval to be undefined when winsock2.h isn't included. Including time.h doesn't define timeval either.

How can I get timeval defined (a) without having to include winsock2.h, (b) not requiring applications that include my headers to include winsock2.h before my headers, (c) allowing application to include winsock2.h if they need them, and (d) not having to define timeval myself, because it may already be defined by a header the parent application is including?

4

There are 4 best solutions below

0
On

I don't define either of the LEAN_AND_MEANs, instead I explicitly do the following for each of the 'NOs' prior to including windows.h

//  Exclude Input Method Manager (International stuff...one day)
#if !defined    NOIMM
    #define NOIME
    #define NOIMM
#endif

//  Exclude Metafile API
#if !defined    NOMETAFILE
    #define NOMETAFILE
#endif

This allows me to use the same StdAfx.h. With VS2010 I can include Winsock2 after windows.h without conflicts.

Stdafx is a little longer, but clearly documents what is included and excluded.

1
On

Remember that WIN32_LEAN_AND_MEAN is a compiler performance optimisation. Using it makes your apps compile somewhat faster at the expense of omitting some less-used parts of the Windows API.

You could use one of the more granular disables (NOIMM, etc), but these have even less impact on compile time than the LEAN_AND_MEAN one does.

Unless your project is very large and has long, onerous compile times I would simply stop using WIN32_LEAN_AND_MEAN.

Martyn

0
On

This is how I handle problems with winsock2.h (assuming Visual C++):

  • I configured the build system to always pass in /D_WINSOCKAPI_ to the compiler on the command line so that no winsock header files are ever implicitly included.
  • When I want to include winsock2.h, I do it via a proxy header file that does some preprocessor magic for me.

This is how my header file works:

#pragma push_macro("_WINSOCKAPI_")
#undef _WINSOCKAPI_
#include <winsock2.h> 
#pragma pop_macro("_WINSOCKAPI_")

If you do this then you don't need to #define WIN32_LEAN_AND_MEAN and you can use winsock2.h only when needed.

1
On

I don't think what you want is possible. The timeval struct is defined in winsock.h and winsock2.h, thus you have to include one of those to get the definition. If you don't define WIN32_LEAN_AND_MEAN, windows.h will include winsock.h; this makes it impossible to include winsock2.h. If you define WIN32_LEAN_AND_MEAN, neither of the winsock header files are automatically included thus you don't get the definition for timeval. I think your best option is to require applications to include one of the winsock headers explicitly.