gpt4 book ai didi

c++ - 如何解决boost多线程简单程序的编译错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:35:12 25 4
gpt4 key购买 nike

我在我的 PC 上编译 boost 集成源代码时遇到问题。我正在以下环境中工作

OS: CentOs 6.3
Boost version: 1.41
Boost installation header file directory: /usr/include/boost/
IDE: code::block

编译程序:

#include <boost/thread.hpp>
#include <iostream>

using namespace std;

void ThreadFunction()
{
int counter = 0;

for(;;)
{
std::cout << "thread iteration " << ++counter << " Press Enter to stop" << std::endl;

try
{
// Sleep and check for interrupt.
// To check for interrupt without sleep,
// use boost::this_thread::interruption_point()
// which also throws boost::thread_interrupted
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}
catch(boost::thread_interrupted&)
{
std::cout << "Thread is stopped" << std::endl;
return;
}
}
}

int main()
{
// Start thread
boost::thread t(&ThreadFunction);

// Wait for Enter
char ch;
std::cin.get(ch);

// Ask thread to stop
t.interrupt();

// Join - wait when thread actually exits
t.join();
std::cout << "main: thread ended" << std::endl;


return 0;
}

错误输出:

Build: Debug in testPro (compiler: GNU GCC Compiler) ===|
obj/Debug/main.o||In function `main':|
<path to code>/main.cpp|40|undefined reference to `boost::thread::interrupt()'|
<path to code>/main.cpp|43|undefined reference to `boost::thread::join()'|
<path to code>/main.cpp|47|undefined reference to `boost::thread::~thread()'|
<path to code>/main.cpp|47|undefined reference to `boost::thread::~thread()'|
obj/Debug/main.o||In function `thread_data_base':|
/usr/include/boost/thread/pthread/thread_data.hpp|65|undefined reference to `vtable for boost::detail::thread_data_base'|
obj/Debug/main.o||In function `void boost::this_thread::sleep<boost::date_time::subsecond_duration<boost::posix_time::time_duration, 1000l> >(boost::date_time::subsecond_duration<boost::posix_time::time_duration, 1000l> const&)':|
/usr/include/boost/thread/pthread/thread_data.hpp|122|undefined reference to `boost::this_thread::sleep(boost::posix_time::ptime const&)'|
obj/Debug/main.o||In function `thread<void (*)()>':|
/usr/include/boost/thread/detail/thread.hpp|191|undefined reference to `boost::thread::start_thread()'|
obj/Debug/main.o||In function `~thread_data':|
/usr/include/boost/thread/detail/thread.hpp|40|undefined reference to `boost::detail::thread_data_base::~thread_data_base()'|
]+0x10)||undefined reference to `typeinfo for boost::detail::thread_data_base'|
||=== Build failed: 9 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

在错误控制台中,编译器无法找到在 boost 库中声明的方法。我尝试了几个示例应用程序,但结果是一样的。请帮助我找出问题所在或建议我检查 boost 安装状态的方法。

最佳答案

您需要使用 boost_thread 库 -lboost_thread 编译您的代码例如

gcc test.c -o test -lboost_thread

关于c++ - 如何解决boost多线程简单程序的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23264373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com