[英]C++ Boost Example: Creating and Managing Threads (Compilation Error)
我目前正在使用Boost 1.54.0。 我正在遵循此示例中的代码。
example_44_01.cpp
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <iostream>
void wait(int seconds)
{
boost::this_thread::sleep_for(boost::chrono::seconds{seconds});
}
void thread()
{
for (int i = 0; i < 5; ++i)
{
wait(1);
std::cout << i << std::endl;
}
}
int main(int argc, char** argv)
{
boost::thread t{thread};
t.join();
return 0;
}
因此,看起来我需要的是-lboost_thread和-lboost_chrono库,以便在编译时链接到它们。 我还添加了-lboost_system。
这是我的执行脚本。
g++-7 -Wall -std=c++1z -g -c example_44_01.cpp -o example_44_01.o
g++-7 -Wall -std=c++1z -g example_44_01.o -o example_44_01 -lboost_system -lboost_thread -lboost_chrono &>result.txt
这里发生了什么? 这是result.txt文件:
example_44_01.o: In function `boost::this_thread::sleep_for(boost::chrono::duration<long, boost::ratio<1l, 1000000000l> > const&)':
/usr/local/include/boost/thread/pthread/thread_data.hpp:243: undefined reference to `boost::this_thread::hidden::sleep_for(timespec const&)'
collect2: error: ld returned 1 exit status
我已经用相同的库编译并链接了其他程序,没有错误。 那么代码中的错误是吗? 由于代码直接来自文档,因此这似乎令人怀疑。 任何见解均表示赞赏。
我曾经遇到这个问题是因为我故意使用了不同版本的Boost(我首先从命令行安装Boost,然后几个月后从zip手动安装)。
尝试将Boost库的路径添加到编译器。 例如,如果您的库存储在/usr/local/lib
,请尝试:
g++-7 -Wall -std=c++1z -g example_44_01.o -o example_44_01 -L/usr/local/lib -lboost_system -lboost_thread -lboost_chrono &>result.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.