到http://www.boost.org/下載boost的安裝包,以boost_1_58_0.tar.gz爲例
下載完成後進行解壓縮:css
tar zxvf boost_1_58_0.tar.gz
先進入解壓縮後的目錄:html
cd boost_1_58_0
而後運行bootstrap.sh腳本並設置相關參數:python
./bootstrap.sh --with-libraries=all --with-toolset=gcc
--with-libraries
指定編譯哪些boost庫,all的話就是所有編譯,只想編譯部分庫的話就把庫的名稱寫上,之間用 , 號分隔便可,可指定的庫有如下幾種:linux
庫名 | 說明 |
---|---|
atomic | |
chrono | |
context | |
coroutine | |
date_time | |
exception | |
filesystem | |
graph | 圖組件和算法 |
graph_parallel | |
iostreams | |
locale | |
log | |
math | |
mpi | 用模板實現的元編程框架 |
program_options | |
python | 把C++類和函數映射到Python之中 |
random | |
regex | 正則表達式庫 |
serialization | |
signals | |
system | |
test | |
thread | 可移植的C++多線程庫 |
timer | |
wave |
--with-toolset
指定編譯時使用哪一種編譯器,Linux下使用gcc便可,若是系統中安裝了多個版本的gcc,在這裏能夠指定gcc的版本,好比--with-toolset=gcc-4.4
ios
./b2 install --build-type=complete --layout=versioned --with-thread --prefix="/usr/local"c++
命令執行完成後看到顯示以下即爲成功:正則表達式
Building Boost.Build engine with toolset gcc... tools/build/src/engine/bin.linuxx86_64/b2 Detecting Python version... 2.6 Detecting Python root... /usr Unicode/ICU support for Boost.Regex?... not found. Generating Boost.Build configuration in project-config.jam... Bootstrapping is done. To build, run: ./b2 To adjust configuration, edit 'project-config.jam'. Further information: - Command line help: ./b2 --help - Getting started guide: http://www.boost.org/more/getting_started/unix-variants.html - Boost.Build documentation: http://www.boost.org/build/doc/html/index.html
執行如下命令開始進行boost的編譯:算法
./b2 toolset=gcc
編譯的時間大概要10多分鐘,耐心等待,結束後會有如下提示:shell
...failed updating 60 targets... ...skipped 21 targets... ...updated 663 targets...
最後執行如下命令開始安裝boost:編程
./b2 install --prefix=/usr
--prefix=/usr
用來指定boost的安裝目錄,不加此參數的話默認的頭文件在/usr/local/include/boost
目錄下,庫文件在/usr/local/lib/
目錄下。這裏把安裝目錄指定爲--prefix=/usr
則boost會直接安裝到系統頭文件目錄和庫文件目錄下,能夠省略配置環境變量。
安裝完畢後會有如下提示:
...failed updating 60 targets... ...skipped 21 targets... ...updated 11593 targets...
最後須要注意,若是安裝後想立刻使用boost庫進行編譯,還須要執行一下這個命令:
ldconfig
更新一下系統的動態連接庫
以boost_thread爲例,測試剛安裝完的boost庫是否能正確使用,測試代碼以下:
#include <boost/thread/thread.hpp> //包含boost頭文件 #include <iostream> #include <cstdlib> 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; }
在編譯程序時,須要加入對boost_thread庫的引用:
g++ main.cpp -g -o main -lboost_thread
若是boost庫的安裝位置不是在系統目錄下,則還須要在編譯時加上-I和-L指定boost頭文件和庫文件的位置
編譯成功後運行程序,利用boost實現的多線程任務正確運行:
func1: func2:00 func1:1 func2:1 func1:2 func1:3 func2:2 func1:4 func1:5 func2:3 func1:6 func1:7 func2:4 func1:8 func1:9 func2:5 func1:10 func1:11 func2:6 func1:12 func1:13 func2:7 func1:14 func1:15 func2:8 func1:16 exit