对于cmake构建的工程项目:
# CmakeList.txt添加如下内容
add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY)
# 或者
find_package(Boost 1.55.0 REQUIRED COMPONENTS system filesystem)
include_directories(untitled ${Boost_INCLUDE_DIRS})
link_directories(untitled ${Boost_LIBRARY_DIRS})
target_link_libraries(untitled ${Boost_LIBRARIES})
对于 g++ 编译器,需要添加编译选项,进行库的链接:
出现的问题:
/usr/include/boost/system/error_code.hpp:221: undefined reference to `boost::system::generic_category()'
/usr/include/boost/system/error_code.hpp:222: undefined reference to `boost::system::generic_category()'
/usr/include/boost/system/error_code.hpp:223: undefined reference to `boost::system::system_category()'
解决:
g++ -o test main.cpp -lboost_system
问题:
对‘vtable for boost::detail::thread_data_base’未定义的引用
对‘boost::thread::start_thread_noexcept()’未定义的引用
对‘boost::thread::detach()’未定义的引用
解决:
g++ -o main main.c -lboost_system -lboost_thread
总结:说白了就是缺少什么库就在后面链接指定的库即可
例子:
#include<boost/thread.hpp>
using namespace boost; //名字空间
#include<iostream>
using namespace std;
#pragma comment(lib, "libboost_thread-vc100-mt-gd-x32-1_67.lib")
void ThreadFun(string & threadName)
{
for (size_t i = 0; i < 5; i++)
{
printf("%s 执行!\n", threadName.c_str());
//线程睡眠
this_thread::sleep(posix_time::seconds(1));
}
}
int main()
{
//定义线程对象,线程执行函数,函数参数,构造
thread t1(ThreadFun, string("线程1"));//立即运行
thread t2(ThreadFun, string("线程2"));//立即运行
//t1.join();//先阻塞,等待子线程执行完毕后返回
//t2.join();//先阻塞,等待子线程执行完毕后返回
//如果线程还没结束,最多等待3秒
t1.timed_join(posix_time::seconds(8));
cout << "main结束!" << endl;
getchar();
return 0;
}