Socket中winsock.h和winsock2.h的不同

欢迎访问我的新博客:http://www.milkcu.com/blog/

原文地址:http://www.milkcu.com/blog/archives/1370588160.html

译文:Socket中winsock.h和winsock2.h的不同

原文:Is there a difference between and ?

译者:MilkCu

引言

初学Socket网络编程,很明显用于linux操作系统,但是除了版本不同外,还有什么不同呢?

译文

windows.h在新的Windows版本下编译时会包含winsock2.h,而在老版本中包含winsock.h,但是问题不仅局限在windows.h。当winsock.h在winsock2.h前包含时,编译会报错,因为两个文件不能共存的很好。winsock2.h设计的目的是替代winsock.h,而不是扩展它。在winsock.h中定义的所有内容在winsock2.h中也都定义了。如果winsock2.h在winsock.h前包含,winsock2.h定义了_WINSOCKAPI_,阻止编译器去处理后面的winsock.h,编译不会报错。但是如果winsock.h在winsock2.h前包含,winsock2.h没有检测到这些,而去重新定义winsock.h已经定义的东西,从而编译报错。

在同一个项目中同时使用winsock.h和winsock2.h要格外小心。例如,当使用winsock2.h编写自己的代码,但是使用仍包含winsock.h的第三方库的时候。

原文

windows.h includes winsock2.h when compiling for newer Windows versions, but for older development it includes winsock.h instead. 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.his included before winsock.hwinsock2.h defines _WINSOCKAPI_ to prevent the compiler from processing subsequent winsock.h includes, and all is fine. But if winsock.h is included beforewinsock2.hwinsock2.h does not detect that and tries to re-define everything that winsock.hhas 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.hin 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.

后记

这是Stack Overflow上的一篇问答,有点像国内的知乎,有些回答的质量不错的,正确性就要自己判断啦。

(全文完)

转载于:https://www.cnblogs.com/milkcu/archive/2013/06/11/3808923.html

你可能感兴趣的:(操作系统)