23

I'm including as it's required by the MySQL C library.

The auto-complete in VS2010 is also showing a - any idea what this is?

Are they interchangeable, and are there any advantages of one over the other?

Thanks!

James
  • 1,430
  • 4
  • 20
  • 27

3 Answers3

37

@cost's answer links to a discussion that, amongst other things, asks this question that was never answered:

Is there a reason why I can't include windows.h before winsock2.h, it gives me tons of errors, but once I switch their order everything is okay... why is that?

windows.h includes winsock.h by default (if WIN32_LEAN_AND_MEAN is not defined). The problem is not limited to just windows.h, though. Any time winsock.h gets included before winsock2.h, there will be compiler errors.

The reason is because the two files DO NOT co-exist very well. winsock2.h was designed to replace winsock.h, not extend it. Everything that is defined in winsock.h is also defined in winsock2.h.

If winsock2.h is included before winsock.h, winsock2.h defines _WINSOCKAPI_ to prevent the compiler from processing subsequent winsock.h includes, and all is fine.

But if winsock.h is included before winsock2.h, winsock2.h does not detect that and tries to re-define everything that winsock.h has already defined, causing the compile to fail.

You have to be very careful when mixing code that uses winsock.h with code that uses winsock2.h in the same project. For instance, when writing your own socket code that uses winsock2.h, and using third-party libraries that still use winsock.h.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • "`windows.h` includes `winsock2.h` when compiling for newer Windows versions" - Where can I actually see this? I opened `Windows.h` from the Windows 10 19041 SDK, and it always fixedly includes the old `winsock.h` - and I get the compilation errors you mentioned when manually including `WinSock2.h` afterwards. – Ray Jun 15 '22 at 21:45
  • 1
    @Ray you are correct. The stock `windows.h` includes only `winsock.h`. My compiler's vendor modified their bundled copy of `windows.h` to include `winsock2.h` instead. I have updated my answer. – Remy Lebeau Jun 15 '22 at 22:23
  • Thank you so much. Great to see people maintaining their 10+ year old answers :) – Ray Jun 15 '22 at 23:15
9

You should use winsock2.h unless you want to use Winsock 1.1. winsock2.h is for Winsock 2.

You can read more about it at the Wikipedia Winsock page.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
0

Winsock2 is completely backwards compatible with the original winsock, so the only reason you would ever want to use the original winsock is when you are targeting a platform that doesn't support winsock2 (Everything that is newer than Windows 3.11 supports winsock2 I believe).