【发布时间】:2017-12-04 01:55:39
【问题描述】:
我目前使用的是 Boost 1.54.0。我正在关注example 中的代码。
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
我已经用相同的库编译并链接了其他程序,没有错误。那么代码中的错误是什么?这似乎令人怀疑,因为代码直接来自文档。任何见解都值得赞赏。
【问题讨论】:
-
只是一个问题:所有这些功能都可以在标准库中使用 c++1z 标志。你需要使用boost吗?
-
也许,我只是为了学习目的而浏览 Boost 网站上的一些代码。我很震惊,它没有用。 ://
-
您可能会为此自责,但错误可能链接到
-lboost_thread而不是-lboost_thread-mt。-mt代表“多线程”。 -
@AlexanderHuszagh
mt变种多年来一直是相同的,IIRC -
@JordanJelinek 我的猜测是编译标志不兼容。构建库时使用了什么编译器版本/标志?你自己建造的吗?
标签: c++ boost boost-thread