如何修复 CLion 中对“__imp_WSACleanup”(Boost.Asio)的未定义引用

How to fix undefined reference to `__imp_WSACleanup' (Boost.Asio) in CLion

我的 C++ 项目包括 Boost and WebSocket++ 库。我阅读了其他主题,我需要将 -lws2_32 添加到 gcc 命令,但我有 CLion,但我不知道如何修复它。

控制台:

CMakeFiles\WsServer.dir/objects.a(main.cpp.obj): In function `boost::asio::detail::winsock_init_base::startup(boost::asio::detail::winsock_init_base::data&, unsigned char, unsigned char)':
C:/MinGW/include/boost/asio/detail/impl/winsock_init.ipp:39: undefined reference to `__imp_WSAStartup'
CMakeFiles\WsServer.dir/objects.a(main.cpp.obj): In function `boost::asio::detail::winsock_init_base::cleanup(boost::asio::detail::winsock_init_base::data&)':
C:/MinGW/include/boost/asio/detail/impl/winsock_init.ipp:56: undefined reference to `__imp_WSACleanup'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\WsServer.dir\build.make:99: WsServer.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:67: CMakeFiles/WsServer.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:79: CMakeFiles/WsServer.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:117: WsServer] Error 2

我该怎么办?

您可以在 CMakeLists.txt 中通过 target_link_libraries 传递 ws2_32,例如:

if(MINGW)
  target_link_libraries(YourTargetName ws2_32)
endif()