本帖最后由 Qter 于 2020-9-10 14:33 编辑
Resolving Redefinition Errors Betwen ws2def.h and winsock.h
https://www.zachburlingame.com/2011/05/resolving-redefinition-errors-betwen-ws2def-h-and-winsock-h/
The SolutionYou basically have three options to fix this: Option 1: WIN32_LEAN_AND_MEAN- #define WIN32_LEAN_AND_MEAN
- #include <Windows.h>
- #include <WinSock2.h>
-
- int main( int argc, char* argv[] )
- {
- return 0;
- }
复制代码 Option 2: Explicitly include WinSock2.h before Windows.hBy explicitly including WinSock2.h before every place that you Windows.h, you prevent the collision. However, this can be quite cumbersome at times.
UPDATE 2011-11-12:This method can cause issues with struct packing and alignment if WIN32 isn’t defined before including WinSock2.h (see Oren’s comment below). To resolve this issue, either define WIN32 as a preprocessor flag in your project or explicitly define #WIN32 prior to the WinSock2.h include as I’ve done below.
- #ifndef WIN32
- #define WIN32
- #endif
- #include <WinSock2.h>
- #include <Windows.h>
-
- int main( int argc, char* argv[] )
- {
- return 0;
- }
复制代码
Option 3: Create a WinSock Wrapper HeaderThis option creates a header file that prevents the collision in the first place and then you include this at (or nearest as possible) to the top of every file that needs WinSock2.h. The following is based on code from this stackoverflowanswer.
- #ifndef _WINSOCK_WRAPPER_H_
- #define _WINSOCK_WRAPPER_H_
-
- #if _MSC_VER > 1000
- #pragma once
- #endif
-
- #ifndef _WINDOWS_
- #define WIN32_LEAN_AND_MEAN
- #include <windows.h>
- #undef WIN32_LEAN_AND_MEAN
- #endif
-
- #include <winsock2.h>
-
- #pragma comment(lib, "ws2_32.lib")
-
- #endif
复制代码
If the #pragma option above is unfamiliar to you, the compiler passes it along to the linker telling it to include the lib rather than having to set it in the project settings. Theres more on #pragma comment options over on MSDN.
|