我正在使用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()
的情况下做到这一点?
@ a3f感谢提醒!我刚刚检查了答案,它现在正在工作 –