The problem is when windows.h
is included before WinSock2.h
. Because windows.h
includes winsock.h
. You can not use both WinSock2.h
and winsock.h
.
Solutions:
-
Include
WinSock2.h
beforewindows.h
. In the case of precompiled headers, you should solve it there. In the case of simple project, it is easy. However in big projects (especially when writing portable code, without precompiled headers) it can be very hard, because when your header withWinSock2.h
is included,windows.h
can be already included from some other header/implementation file. -
Define
WIN32_LEAN_AND_MEAN
beforewindows.h
or project wide. But it will exclude many other stuff you may need and you should include it by your own. -
Define
_WINSOCKAPI_
beforewindows.h
or project wide. But when you includeWinSock2.h
you get macro redefinition warning. -
Use
windows.h
instead ofWinSock2.h
whenwinsock.h
is enough for your project (in most cases it is). This will probably result in longer compilation time but solves any errors/warnings.
原文链接:https://stackoverflow.com/questions/1372480/c-redefinition-header-files-winsock2-h