Linux下編譯使用boost庫

Boost是什麼不多說, 下面說說怎樣在Linux下編譯使用Boost的所有模塊.

1. 先去Boost官網下載最新的Boost版本, 我下載的是boost_1_56_0版本, 解壓.

2. 進入解壓後目錄: cd boost_1_56_0, 執行下面的命令:

 

$ ./bootstrap.sh --prefix=path/to/installation/prefix

 

prefix的值是你希望安裝boost的路徑, 不開啓此參數的話默認安裝在 /usr/local 下. 我安裝在 /home/xzz/boost_1_56_0目錄下:

 

$ ./bootstrap.sh --prefix=/home/xzz/boost_1_56_0

 

Note: 家目錄不要用 ~ 表示, 編譯腳本不識別 ~, 會在當前目前新建一個名爲 '~' 的目錄.

接着執行:

 

$ ./b2 install

 

這條命令把boost的頭文件文件夾 include/ 安裝在prefix定義的目錄中, 並且會編譯所有的boost模塊, 並將編譯好的庫文件夾 lib/ 也放在prefix定義的目錄中. 所有如果成功編譯的的話, prefix目錄即 /home/xzz/boost_1_56_0目錄應當包含有 include/ 和 lib/ 兩個文件夾.

3. 測試

先測試只依賴頭文件的功能模塊:

將下面的代碼保存爲 test.cpp:

 

[cpp] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. #include <boost/lambda/lambda.hpp>  
  2. #include <iostream>  
  3. #include <iterator>  
  4. #include <algorithm>  
  5.   
  6. int main()  
  7. {  
  8.     using namespace boost::lambda;  
  9.     typedef std::istream_iterator<int> in;  
  10.   
  11.     std::for_each(  
  12.         in(std::cin), in(), std::cout << (_1 * 3) << " " );  
  13. }  

 

編譯

 

$ g++ test.cpp -o test -I /home/xzz/boost_1_56_0/include

-I: 大寫的i, 指定頭文件搜索目錄

執行 ./test 測試, 輸入一個數, 返回這個數乘3的值.

 

 

再測試需要用到二進制庫的功能模塊:

將下面的代碼保存爲 test.cpp:

 

[cpp] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. #include <iostream>  
  2. #include <boost/filesystem.hpp>  
  3.   
  4. using namespace boost::filesystem;  
  5.   
  6. int main(int argc, char *argv[])  
  7. {  
  8.     if (argc < 2) {  
  9.         std::cout << "Usage: tut1 path\n";  
  10.         return 1;  
  11.     }  
  12.     std::cout << argv[1] << " " << file_size(argv[1]) << std::endl;  
  13.     return 0;  
  14. }  


編譯的時候需要注意:

 

 

$ g++ test.cpp -o test -I /home/xzz/boost_1_56_0/include -L /home/xzz/boost_1_56_0/lib -lboost_system -lboost_filesystem

 

 

-L: 後接boost庫文件夾

-l: 這是小寫的 L, 接源文件編譯所需用到的庫文件, 注意使用 -l 要注意, 庫文件之間也存在依賴關係, 比如這裏 boost_filesystem 庫依賴於boost_system 庫, 所以boost_filesystem 要寫在後面, 否則可能會出現符號解析錯誤. 下面是 man g++ 裏的一段話.

引用It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in z, those functions may not be loaded.

 

執行 ./test, 這個時候會出現一個問題:

 

./test: error while loading shared libraries: libboost_system.so.1.56.0: cannot open shared object file: No such file or directory

 

 

原因是在存在動態庫和靜態庫時, gcc優先使用動態庫, 但動態庫在linux下默認搜索路徑是/lib, /usr/lib/usr/local/lib. 所以程序運行的時候出錯. 解決辦法可以將動態庫拷貝到動態庫的搜索路徑下. 也可以使用 -static 參數指定程序使用靜態庫. 這篇博客裏面提供了更多解決方案. 改爲使用下面的命令編譯:

 

$ g++ test.cpp -o test -I /home/xzz/boost_1_56_0/include -L -static /home/xzz/boost_1_56_0/lib -lboost_system -lboost_filesystem

 

執行 ./test, 輸出

 

Usage: tut1 path

 

 

 

如果兩個用例都成功編譯了, 那麼恭喜你, boost庫安裝成功.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章