C ++错误:未定义引用(winsock2.h)

时间:2018-03-10 10:30:48

标签: c++ sockets client winsock2

我正在尝试使用库winsock2.h在windows中编译以下套接字服务器。在clion v3.8

#include <iostream>
#include <winsock2.h>

using namespace std;

int main()
{
WSADATA WSAData;

SOCKET server, client;

SOCKADDR_IN serverAddr, clientAddr;

WSAStartup(MAKEWORD(2,0), &WSAData);
server = socket(AF_INET, SOCK_STREAM, 0);

serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(5555);

bind(server, (SOCKADDR *)&serverAddr, sizeof(serverAddr));
listen(server, 0);

cout << "Listening for incoming connections..." << endl;

char buffer[1024];
int clientAddrSize = sizeof(clientAddr);
if((client = accept(server, (SOCKADDR *)&clientAddr, &clientAddrSize)) != INVALID_SOCKET)
{
    cout << "Client connected!" << endl;
    recv(client, buffer, sizeof(buffer), 0);
    cout << "Client says: " << buffer << endl;
    memset(buffer, 0, sizeof(buffer));

    closesocket(client);
    cout << "Client disconnected." << endl;
}
}

我从Winsock2库中的每个函数都得到以下错误,与

相同
CMakeFiles\projectServer.dir/objects.a(main.cpp.obj): In function `main':
C:/Users/yilmaz/CLionProjects/projectServer/main.cpp:17: undefined reference to `WSAStartup@8'
C:/Users/yilmaz/CLionProjects/projectServer/main.cpp:18: undefined reference to `socket@12'
C:/Users/yilmaz/CLionProjects/projectServer/main.cpp:22: undefined reference to `htons@4'
.......

我一直在寻找googe太多次了,但我还没有找到与clion兼容的东西。

1 个答案:

答案 0 :(得分:2)

  

<强>要求

+---------+------------+
| Library | Ws2_32.lib |
+---------+------------+

将Ws2_32.lib添加到链接器设置中的链接库。