【问题标题】:C++ Boost Example: Creating and Managing Threads (Compilation Error)C++ Boost 示例:创建和管理线程(编译错误)
【发布时间】: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


【解决方案1】:

我曾经遇到过这个问题,因为我无意中使用了不同版本的 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

【讨论】:

  • 哇,第一次尝试。这正是我所做的,按照您的描述更改 Boost 的版本。特维姆!我现在肯定会添加路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
  • 2018-12-13
  • 2021-12-07
  • 2016-03-24
  • 1970-01-01
  • 2016-02-25
相关资源
最近更新 更多