2017-04-07 73 views
0

我正在使用QT Creator构建一个C普通项目。我的项目包含套接字创建,我收到很多参考错误。如何在C中正确链接winsock2.h?

我的代码很简单:

#include <winsock2.h> 
#include <stdio.h> 

// Need to link with Ws2_32.lib 
#pragma comment (lib, "Ws2_32.lib") 

int main(int argc , char *argv[]) 
{ 
    WSADATA wsa; 
    SOCKET s; 

    printf("\nInitialising Winsock..."); 
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) 
    { 
     printf("Failed. Error Code : %d",WSAGetLastError()); 
     return 1; 
    } 

    printf("Initialised.\n"); 

    if((s = socket(AF_INET , SOCK_STREAM , 0)) == INVALID_SOCKET) 
    { 
     printf("Could not create socket : %d" , WSAGetLastError()); 
    } 

    printf("Socket created.\n"); 

    return 0; 
} 

编译错误:

undefined reference to `[email protected]' 
undefined reference to `[email protected]' 
undefined reference to `[email protected]' 
undefined reference to `[email protected]' 

话,我想这意味着不包括winsock2.h库。如何在没有#pragma comment()的情况下做到这一点?

+0

@ a3f感谢提醒!我刚刚检查了答案,它现在正在工作 –

回答

0

您的#include <winsock2.h>用法很好。这是你需要更新你的项目设置,并添加ws2_32.lib作为链接库。

对于Qt,只需将此行添加到.pro文件。假设你使用的是微软的编译器:

LIBS += ws2_32.lib 

注:我不得不真正删除命令行“打造”目录,然后改变做一个“干净的构建”从Qt Creator中生效。

+0

Visual Studio项目? –

+0

哦,我没有看到'Qt'标签....我很快就会解决这个问题.... – selbie

+0

是啊!此解决方案有效 –