Ubuntu下安装和编译boost库

c++编译可能需要用到Boost库,因此要安装Boost库。

1.下载Boost安装包

http://www.boost.org/
到此网站进行下载:
Ubuntu下安装和编译boost库
Ubuntu下安装和编译boost库
Ubuntu下安装和编译boost库
https://www.boost.org/users/history/ 这是旧版本列表的链接
之后就可以根据需要找你想要的版本了,在此以Version 1.59.0为例,下载boost_1_59_0.tar.gz
Ubuntu下安装和编译boost库
下载完成后,进行解压:

tar zxvf boost_1_59_0.tar.gz

2.安装

先进入解压缩后的目录:

cd boost_1_59_0

然后运行bootstrap.sh脚本:

./bootstrap.sh 

也可以添加prefix参数:

./bootstrap.sh --with-libraries=all --with-toolset=gcc

--with-libraries指定编译哪些boost库,all的话就是全部编译,只想编译部分库的话就把库的名称写上,之间用 , 号分隔即可.
也可以添加prefix参数, 自定义生成的头文件和二进制库文件目录:

./booststrap.sh --prefix /usr/local/lib/boost

则生成的头文件在/usr/local/lib/boost/include中, 二进制库文件在/usr/local/lib/boost/lib中。
命令执行完毕后,若成功会有如下显示:
Ubuntu下安装和编译boost库
接下来,根据提示,执行以下命令开始进行boost的编译:

./b2 toolset=gcc

大概要等10分钟吧,会出现以下结果:

...failed updating 20 targets...
...skipped 21 targets...
...updated 663 targets...

之后,进行安装指令:

./b2 install

安装完成后,大概的提示:
Ubuntu下安装和编译boost库

查看文件

查看安装目录中有无安装的头文件等:
Ubuntu下安装和编译boost库
如果有,说明安装成功。

3.boost使用测试

如果安装完毕后,想马上使用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头文件和库文件的位置。
我的运行后,报错:
Ubuntu下安装和编译boost库
因此在指令后,添加lboost_system

g++ main.cpp -g -o main -lboost_thread -lboost_system

这次编译成功后,运行程序:

./main

Ubuntu下安装和编译boost库