linux下安裝boost及boost::thread的使用
1.0 前言
由於專案需要,初次接觸boost,難免要面臨安裝除錯的問題。由於boost庫的發展還比較短,網上的中文資料也比較少,自己走了不少彎路,在這裡把自己檢驗過的正確的方法寫下來,希望能對後面的學習者有所幫助。本文主要參考了boost.org中的get start文件和Stack Overflow網站中的部分內容。
1.1 環境
2.0 boost的安裝
下載到 boost_1_49_0.tar.bz2 (當然,其他壓縮格式也可以)後,可以把它放在使用者目錄下,即:~/
解壓縮:tar -jxvf boost_1_49_0.tar.bz2
這樣,出現資料夾:~/boost_1_49_0
然後進入:$ cd boost_1_49_0
你會發現有一個sh命令:bootstrap.sh
執行它:$ ./bootstrap.sh (boost自己的get start文件中說設定引數 --prefix=dir 其中dir為你想指定的安裝資料夾,我建議就不用加這個引數,它會預設安裝到/usr/local)
結束後出現一個可執行檔案: ~/boost_1_49_0/b2
執行這個檔案: $ sudo ./b2 install (Ubuntu使用者千萬別忘了加sudo,不然安裝後將無法完全使用)
編譯安裝時間比較長,根據不同機器的情況20~40分鐘。結束後即安裝完畢。
3.0 boost::thread的使用
在這將一個簡單的多執行緒的例子附上,方便大家測試,檔名為 example.cpp
#include <boost/thread.hpp> #include <iostream> void task1() { // do stuff std::cout << "This is task1!" << std::endl; } void task2() { // do stuff std::cout << "This is task2!" << std::endl; } int main (int argc, char ** argv) { using namespace boost; thread thread_1 = thread(task1); thread thread_2 = thread(task2); // do other stuff thread_2.join(); thread_1.join(); return 0; }
編譯時的命令為:
$ g++ -I./inlcude -L./lib example.cpp -lboost_thread -o example
編譯之後會出現一個 example 的可執行檔案,可以執行:./example , 結果顯示:
This is task2!
This is task1!可能你在執行時會出現這樣的錯誤:error while loading shared libraries: libboost_thread.so.1.49.0: cannot open shared object file: No such file or directory
這是因為要用到的庫不在預設的環境變數裡,可以使用下面的命令新增:
$ sudo ldconfig /usr/local/lib新增後,再執行./example,這樣你就完成了你的第一個boost::thread程式。
祝大家好運!