我在编译下面的C程序时遇到了困难,这只是我试图理解winsock的开始。问题是在编译程序client.c时,我得到一个错误(C2143)缺少';' 在“类型”之前但是当我将源文件重命名为“client.cpp”时,程序编译时没有错误或警告。我不明白语法错误是 C 但不是 C++ 中的错误。
#define WIN32_LEAN_AND_MEAN
#define DEBUG
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define PORT "12186"
#define BUFFERLEN 512
int main(int argc, char* argv[])
{
/*
Variable Declorations
*/
WSADATA wsaData;
SOCKET ConnectionSocket = INVALID_SOCKET;
struct addrinfo *result = NULL, *ptr = NULL, hints;
int addrResult;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC; //unspecified so we can be compatible with IPv4 and IPv6
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
#ifdef DEBUG
printf("IPPROTO_TCP: %d", IPPROTO_TCP);
#endif
//Buffers
char * sendbuffer; // Error C2143
char recievebuffer [BUFFERLEN]; //Error C2143
//Initialize Winsock
addrResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if(addrResult !=0)
{
printf("WSAStartup failed: %d", addrResult);
}
addrResult = getaddrinfo(argv[1], PORT, &hints, &result);
if(addrResult != 0)
{
printf("getaddrinfo failed: %d", addrResult);
WSACleanup();
return 1;
}
return 0;
}
编辑:C 变量声明必须在 MSVC C 函数中的所有其他代码之前进行。问题解决了。这是 C89 的东西还是只是 MSVC?