【问题标题】:MSVC 10.0 c vs c++ differencesMSVC 10.0 c 与 c++ 的区别
【发布时间】:2012-07-12 20:22:29
【问题描述】:

我在编译下面的 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?

【问题讨论】:

    标签: visual-c++ portability c89 visual-studio-2010


    【解决方案1】:

    问题可能出在变量声明的位置。将它们与其他变量放在函数的开头。

    See the last example from MSDN that can cause this error code.

    【讨论】:

    • "在C程序中,变量必须在函数开头声明,函数执行非声明指令后不能声明。"谢谢!将变量声明移到提示的设置值之上,使 c 编译器能够正确编译。
    【解决方案2】:

    VS 附带的 C 编译器仅实现 C89(说真的……),因此您必须在给定函数的顶部声明所有变量。

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 2013-09-15
      • 1970-01-01
      相关资源
      最近更新 更多