簡體   English   中英

C ++ Boost示例:創建和管理線程(編譯錯誤)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM