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

时间:2014-04-24 09:01:29

标签: c++ multithreading boost

我在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库中声明的方法。我尝试了几个示例应用程序,但结果是一样的。请帮我找出问题或建议我检查一下升压安装的状态。

1 个答案:

答案 0 :(得分:1)

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

gcc test.c -o test -lboost_thread