Linux 下編譯使用Boost
來源:程序員人生 發布時間:2014-09-30 01:51:43 閱讀次數:3215次
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:
#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
using namespace boost::lambda;
typedef std::istream_iterator<int> in;
std::for_each(
in(std::cin), in(), std::cout << (_1 * 3) << " " );
}
編譯
$ g++ test.cpp -o test -I /home/xzz/boost_1_56_0/include
-I: 大寫的i, 指定頭文件搜索目錄
執行 ./test 測試, 輸入一個數, 返回這個數乘3的值.
再測試需要用到二進制庫的功能模塊:
將下面的代碼保存為 test.cpp:
#include <iostream>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
int main(int argc, char *argv[])
{
if (argc < 2) {
std::cout << "Usage: tut1 path
";
return 1;
}
std::cout << argv[1] << " " << file_size(argv[1]) << std::endl;
return 0;
}
編譯的時候需要注意:
$ 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庫安裝成功.
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈