Windows WSL2 Ubuntu下VSCode配置Boost库编译报错求助
问题:WSL2 Ubuntu 20.04下VSCode编译Boost库出现pthread未定义引用错误
环境与安装情况
- Windows 10 WSL2 Ubuntu 20.04环境,VSCode全新配置
- 已通过
sudo apt-get install libboost-all-dev安装Boost全量库 - g环境配置完成,可正常编译运行基础C程序
配置的tasks.json文件
{ "tasks": [ { "type": "cppbuild", "label": "C/C++: g++ build active file", "command": "/usr/bin/g++", "args": [ "-fdiagnostics-color=always", "-g", "-I/usr/local/include", "-L/usr/local/lib", "-lboost_system", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" }
代码头文件引用(Linter无报错)
#include <boost/beast/core.hpp> #include <boost/beast/websocket.hpp> #include <boost/asio/connect.hpp> #include <boost/asio/ip/tcp.hpp> using tcp = boost::asio::ip::tcp; namespace websocket = boost::beast::websocket;
编译错误信息
Starting build... /usr/bin/g++ -fdiagnostics-color=always -g -I/usr/local/include -L/usr/local/lib -lboost_system /home/laptop/cppbot/helloworld.cpp -o /home/laptop/cppbot/helloworld /usr/bin/ld: /tmp/ccmv4tdX.o: in function `boost::asio::detail::posix_event::posix_event()': /usr/include/boost/asio/detail/impl/posix_event.ipp:42: undefined reference to `pthread_condattr_setclock' /usr/bin/ld: /tmp/ccmv4tdX.o: in function `boost::asio::detail::posix_thread::~posix_thread()': /usr/include/boost/asio/detail/impl/posix_thread.ipp:35: undefined reference to `pthread_detach' /usr/bin/ld: /tmp/ccmv4tdX.o: in function `boost::asio::detail::posix_thread::join()': /usr/include/boost/asio/detail/impl/posix_thread.ipp:42: undefined reference to `pthread_join' /usr/bin/ld: /tmp/ccmv4tdX.o: in function `boost::asio::detail::posix_thread::start_thread(boost::asio::detail::posix_thread::func_base*)': /usr/include/boost/asio/detail/impl/posix_thread.ipp:59: undefined reference to `pthread_create' /usr/bin/ld: /tmp/ccmv4tdX.o: in function `boost::asio::detail::posix_signal_blocker::posix_signal_blocker()': /usr/include/boost/asio/detail/posix_signal_blocker.hpp:43: undefined reference to `pthread_sigmask' /usr/bin/ld: /tmp/ccmv4tdX.o: in function `boost::asio::detail::posix_signal_blocker::~posix_signal_blocker()': /usr/include/boost/asio/detail/posix_signal_blocker.hpp:50: undefined reference to `pthread_sigmask' collect2: error: ld returned 1 exit status
解决方案
错误根源是Boost.Asio依赖POSIX线程库(pthread),但当前编译命令未链接该库,同时存在库链接顺序错误。需修改tasks.json的编译参数:
- 添加
-pthread参数以链接pthread库 - 调整库参数顺序:源文件
${file}必须放在-lboost_system等库参数之前(g++链接器按顺序解析符号,后出现的库无法为前面的目标文件提供符号)
修改后的tasks.json关键部分:
"args": [ "-fdiagnostics-color=always", "-g", "-I/usr/local/include", "-L/usr/local/lib", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}", "-lboost_system", "-pthread" ]
内容的提问来源于stack exchange,提问作者Pearl
相关产品推荐
相关产品推荐

