如何解决windows.h和WinSocket2.h的冲突
在一个大的VC++工程里,经常会遇到这样一个问题,比如想要使用一个库,而这个库里要使用<Windows.h>头文件,但是这样会引起后面代码里使用WinSocket2.h的冲突,导致整个工程编译不过。为了解决这个问题,可以把WinSocket2.h提前,包含到<Windows.h>之前,如下所示:
#include <WinSocket2.h> #include <Windows.h> typedef struct { CRITICAL_SECTION cs; char is_valid; } mbedtls_threading_mutex_t;这样就会先包含WinSocket2.h文件,这样就不会导致冲突了。其实,VC里还提供了另外一个宏定义WIN32_LEAN_AND_MEAN,定义了这个宏就可以减少编译时包含的头文件,并且提高编译速度。由于定义这个宏,导致WinSocket2.h文件定义的宏就不有先定义了,它作用这样的:
#ifndef WIN32_LEAN_AND_MEAN #include <cderr.h> #include <dde.h> #include <ddeml.h> #include <dlgs.h> #ifndef _MAC #include <lzexpand.h> #include <mmsystem.h> #include <nb30.h> #include <rpc.h> #endif #include <shellapi.h> #ifndef _MAC #include <winperf.h> #include <winsock.h> #endif #ifndef NOCRYPT #include <wincrypt.h> #include <winefs.h> #include <winscard.h> #endif #ifndef NOGDI #ifndef _MAC #include <winspool.h> #ifdef INC_OLE1 #include <ole.h> #else #include <ole2.h> #endif /* !INC_OLE1 */ #endif /* !MAC */ #include <commdlg.h> #endif /* !NOGDI */ #endif /* WIN32_LEAN_AND_MEAN */从这里可以看到,它是怎么样减少头文件包含,以及不引起冲突的,所以冲突的头文件顺序可以写成这样:
#define WIN32_LEAN_AND_MEAN #include <Windows.h> typedef struct { CRITICAL_SECTION cs; char is_valid; } mbedtls_threading_mutex_t;到这里,就可以完善地解决了这个问题。
C++标准模板库从入门到精通 http://edu.csdn.net/course/detail/3324