2017-04-07 75 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

是啊!此解決方案有效 –