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

How to resolve compilation errors for boost multithreading simple program

本文关键字:错误 编译 简单 程序 多线程 boost 何解决 解决      更新时间:2023-10-16

我在电脑中编译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_thread库编译代码-lboost_thread例如

gcc test.c -o test -lboost_thread