Why does the order of includes matter?

I just spent over an hour trying to figure out why I was getting like 50 errors and I had no clue why. Only one thing in my code was actually highlighted red and it was an invalid type conversion or something like that. All the others were giving redefinition errors. So anyways my headers were Windows.h and winsock2.h in that order. I retyped the headers just to make sure I was typing them correctly and I put winsock2.h first and what do you know? No errors, runs fine.
So can anyone explain why the order matters? Thankyou in advance.
closed account (jwkNwA7f)
I actually had the same problem once. When you define WinSock2.h, it defines _WINSOCKAPI_. Then, when you include Windows.h, it includes winsock.h and in winsock.h it has:

1
2
3
4
#ifndef _WINSOCKAPI_
#define _WINSOCKAPI_
//...
#endif 


Since _WINSOCKAPI_ has already been defined, then it won't define all of the stuff that will collide.

A line from WinSock2.h:
#define _WINSOCKAPI_ /* Prevent inclusion of winsock.h in windows.h */

So...

1
2
3
#define _WINSOCKAPI_
#include <Windows.h>
#include <WinSock2.h> 


Will work the same way as this:

1
2
#include <WinSock2.h>
#include <Windows.h> 


Hope this helped!
The problem is that windows.h includes the older winsock.h (unless you do something to stop it) which collides with the newer winsock2.h. But if you include winsock2.h before windows.h, then windows.h spots you've already got sockets support and doesn't include winsock.h.

#define WIN32_LEAN_AND_LEAN before windows.h stops it from including some headers, including winsock.h, so that's another possibility if you just need the core Wndows APIs. If you take this route, you might need to add header which were being automatically brought in before.

Andy
Last edited on
closed account (jwkNwA7f)
Oh yeah, I forgot to mention WIN32_LEAN_AND_MEAN.
Thank you for the clarification on that! Probably still would be messing with the code if I didn't think to switch the headers around.
Topic archived. No new replies allowed.