0%

Linux 编译和安装 boost 库

由于毕业设计要求需要安装 SHMA 然后依赖有许多库

而 boot 就是其中之一…

以下是我编译安装 boost 的步骤

1. 下载boost安装包并解压缩

http://www.boost.org/ 下载 boost 的安装包,我的版本是 1.66

2. 设置编译器和所选库

先进入解压缩后的目录:

cd boost_1_66_0

然后运行 bootstrap.sh 脚本并设置相关参数:

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

–with-libraries 指定编译哪些 boost 库,all 的话就是全部编译

3. 编译 boost

执行以下命令开始进行 boost 的编译:

./b2 toolset=gcc

编译的时间大概要10多分钟,耐心等待,结束后会有以下提示:

1
2
3
...failed updating xx targets...
...skipped xx targets...
...updated xxx targets...

4. 安装 boost

最后执行以下命令开始安装boost:

sudo ./b2 install --prefix=/usr

–prefix=/usr 用来指定 boost 的安装目录,不加此参数的话默认的头文件在 /usr/local/include/boost 目录下,库文件在 /usr/local/lib/目录下。这里把安装目录指定为 –prefix=/usr 则 boost 会直接安装到系统头文件目录和库文件目录下,可以省略配置环境变量。

安装完毕后会有以下提示:

1
2
3
...failed updating 60 targets...
...skipped 21 targets...
...updated 11593 targets...

最后需要注意,如果安装后想马上使用 boost 库进行编译,还需要执行一下这个命令:

sudo ldconfig

更新一下系统的动态链接库

5. boost 使用测试

boost_thread 为例,测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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 -lboost_system

Welcome to my other publishing channels