How to link ws2_32 in Clion

2019-03-01 07:32发布

问题:

I am using Clion, which uses MinGW and Cmake. When I try to use the standalone asio library I am getting

undefined reference to `WSAStartup@8'
undefined reference to `WSASetLastError@4'
undefined reference to `closesocket@4'
...

I believe I have to link the C:/Windows/System32/ws2_32.dll library. I tried adding something like -L C:/Windows/System32 -lws2_32:

set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS} -static -lws2_32")

But that didn't help. How can I fix these errors ?

回答1:

The following CMakeLists.txt compiled error-less. Only 1 line is really required: link_libraries(ws2_32 wsock32)

cmake_minimum_required(VERSION 3.3)
project(server_client)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -s -O3 -I C:/Users/Shiro/Desktop/asio-1.10.6/include")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS} -static")
link_libraries(ws2_32 wsock32)


set(SOURCE_FILES chat_server.cpp)
add_executable(server_client ${SOURCE_FILES})