1. 程式人生 > >Linux下BOOST庫的安裝與使用

Linux下BOOST庫的安裝與使用

本文簡介Linux環境下C++非標準庫boost的安裝與使用。

1.下載boost安裝包(http://www.boost.org/)並解壓,boost_1_61_0.tar.gz
tar -zxvf boost_1_61_0.tar.gz
2. 執行載入程式,配置安裝環境
進入解壓後的檔案目錄
cd boost_1_61_0
檢視安裝載入程式bootstrap.sh,執行該指令碼的附加選項有:
–prefix=PREFIX install Boost into the given PREFIX
在bootstrap.sh指令碼中將其預設配置為:PREFIX=/usr/local
也就是說預設安裝到/usr/local,這裡我們不進行修改,雖然一些安裝教程建議將預設路徑改為/usr,堅持安裝到/usr/local路徑下的理由是:能夠更好的管理這些自行安裝的軟體。這裡還是解釋一下,為什麼這麼做?
首先,usr是Unix Software Resource的縮寫,也就是Unix作業系統軟體資源所放置的目錄:
/usr/include:c/c++等程式語言的標頭檔案及相關包含文件的目錄
/usr/lib:包含各應用軟體的函式庫、目標檔案(object file),以及不被一般使用者慣用的執行檔或指令碼(script)。
將預設路徑改為/usr,安裝後會將標頭檔案和庫檔案放到/usr目錄下的include和lib目錄下,這樣編譯程式時不用擔心找不到標頭檔案這以及連結時找不到庫檔案。但是這樣的話,會導致標頭檔案(或庫檔案)和其他標頭檔案(或庫檔案)‘雜糅’在一起,不便於管理。
如果將其安裝到/usr/local目錄下,安裝完後boost標頭檔案位於/usr/local/include/boost,庫檔案位於/usr/local/lib。編譯時如果找不到標頭檔案,只要加上標頭檔案路徑一起編譯就好了,如果你嫌麻煩,那就用makefile管理吧。

執行引導指令碼bootstrap.sh

[[email protected] boost_1_61_0]# ./bootstrap.sh 
Building Boost.Build engine with toolset gcc... tools/build/src/engine/bin.linuxx86/b2
Detecting Python version... 2.4
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 ....

3.安裝
執行載入程式後,會生成兩個用於編譯和安裝的可執行檔案 b2和bjam,這裡選擇b2進行安裝,安裝選項Targets and Related Options:

install Install headers and compiled library files to the
======= configured locations (below).

–prefix= Install architecture independent files here.
Default; C:\Boost on Win32
Default; /usr/local on Unix. Linux, etc.

–exec-prefix= Install architecture dependent files here.
Default;

–libdir=

Install library files here.
Default; /lib

–includedir= Install header files here.
Default; /include

stage Build and install only compiled library files to the
===== stage directory.

–stagedir= Install library files here
Default; ./stage認配置,直接安裝
[[email protected] boost_1_61_0]# ./b2 install

4.驗證使用

/*
 *遞迴遍歷boost標頭檔案所在目錄下檔案
 */
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>

using namespace std;
using namespace boost;

int main()
{
    string strPath = "/usr/local/include/boost";
    filesystem::recursive_directory_iterator itEnd;
    for(filesystem::recursive_directory_iterator itor( strPath.c_str() ); itor != itEnd ;++itor)
    {
        filesystem::path filePath(*itor);
        cout<<filePath.filename()<<endl; 
        //在本版本的boost中,filename()返回的是path物件,如果想要獲得string型別的檔名,需要使用path的方法string();即filePath.filename().string()
    }
    return 0;
}