This problem is caused when including <windows.h>
before <winsock2.h>
. Try arrange your include list that <windows.h>
is included after <winsock2.h>
or define _WINSOCKAPI_
first:
#define _WINSOCKAPI_ // stops windows.h including winsock.h
#include <windows.h>
// ...
#include "MyClass.h" // Which includes <winsock2.h>
See also this.
As others suggested, 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
before windows.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 with WinSock2.h
is included, windows.h
can be already included from some other header/implementation file.
Define WIN32_LEAN_AND_MEAN
before windows.h
or project wide. But it will exclude many other stuff you may need and you should include it by your own.
Define _WINSOCKAPI_
before windows.h
or project wide. But when you include WinSock2.h
you get macro redefinition warning.
Use windows.h
instead of WinSock2.h
when winsock.h
is enough for your project (in most cases it is). This will probably result in longer compilation time but solves any errors/warnings.
Oh - the ugliness of Windows... Order of includes are important here. You need to include winsock2.h before windows.h. Since windows.h is probably included from your precompiled header (stdafx.h), you will need to include winsock2.h from there:
#include <winsock2.h>
#include <windows.h>
By using "header guards":
#ifndef MYCLASS_H
#define MYCLASS_H
// This is unnecessary, see comments.
//#pragma once
// MyClass.h
#include <winsock2.h>
class MyClass
{
// methods
public:
MyClass(unsigned short port);
virtual ~MyClass(void);
};
#endif
I ran into this problem when trying to pull a third party package which was apparently including windows.h somewhere in it's mess of headers. Defining _WINSOCKAPI_
at the project level was much easier (not to mention more maintainable) than wading through their soup and fixing the problematic include.
I checked the recursive includes, I spotted the header files which include (recursively) some #include "windows.h"
and #include "Winsock.h"
and write a #include "Winsock2.h"
. in this files, i added #include "Winsock2.h"
as the first include.
Just a matter of patience, look at includes one by one and establish this order, first #include "Winsock2.h"
then #include "windows.h"
In VS 2015, the following will work:
#define _WINSOCKAPI_
While the following won't:
#define WIN32_LEAN_AND_MEAN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With