1. 下载后编译
./bootstrap.sh
./b2
2. demo
网上demo ,感谢原作
#include <iostream>
#include <cstdlib>
#include <boost/thread/thread.hpp>
using namespace std;
volatile bool isRuning = true;
void func1()
{
static int cnt1 = 0;
while (isRuning)
{
cout << "func1:" << cnt1++ << endl;
sleep(1);
}
}
void func2()
{
static int cnt2 = 0;
while (isRuning)
{
cout << "\tfunc2:" << cnt2++ << endl;
sleep(2);
}
}
int main()
{
boost::thread thread1(&func1);
boost::thread thread2(&func2);
system("read");
isRuning = false;
thread2.join();
thread1.join();
cout << "exit" << endl;
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
set(name demo)
project (${name})
set( boost_dir /var/work/vendor/boost_1_73_0 )
file( GLOB sources ${CMAKE_SOURCE_DIR}/*.cpp )
#if used boost
add_definitions(-DKXVER=3)
add_definitions(-DBOOST_ALL_DYN_LINK)
set(CMAKE_CXX_FLAG "${CMAKE_CXX_FLAG} -std=c++11 -g " )
link_directories("${boost_dir}/stage/lib")
include_directories( "${boost_dir}" )
link_libraries(pthread)
add_executable( ${name} ${sources} )
target_link_libraries(${name} PUBLIC ${boost_dir}/stage/lib/libboost_thread.so )
3. 编译错误 , 最终的上面的cmake文件是编译ok的,在此之前遇到了错误,如下:
/usr/bin/ld: CMakeFiles/demo.dir/test.cpp.o: undefined reference to symbol 'pthread_condattr_setclock@@GLIBC_2.3.3'
//usr/lib64/libpthread.so.0: error adding symbols: DSO missing from command line
原因: 找不到 pthread 库 , 在CMAKE_CXX_FLAG 中添加 -pthread 不能解决, 需要在CMakeLists中显示引用, 添加 target_link_libraries(${name} PUBLIC pthread) , 编译通过。