logo头像
Snippet 博客主题

boost库使用

windows下boost库使用

下面介绍完整安装boost库的方法:

1. 去boost官网下载最新的boost库

boost库官网

2. 解压boost压缩包,打开根目录

双击运行bootstrap.bat,会生成b2.exe。然后执行以下命令:

b2.exe --toolset=msvc --build-type=complete stage

或者直接双击运行b2.exe

等待编译完成,会在boost根目录下生成bin.v2stage两个文件夹,其中bin.v2是中间文件,可以删除。stage下才是生成的dll或lib文件。

3. 打开VS配置属性

打开项目属性,

  1. VC++目录–>包含目录,添加boost的根目录,如:C:\Users\KL179\Desktop\boost_1_81_0
  2. VC++目录–>库目录,添加stage下的库目录,如:C:\Users\KL179\Desktop\boost_1_81_0\stage\lib
  3. 链接器–>常规–>附加库目录,添加同2库目录。

至此环境就以及配置好了,下面测试一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "boost/thread/thread.hpp"
#include <iostream>
#include <string>

void hello()
{
std::cout << "Hello world, I''m a thread!"
<< std::endl;
}

int main()
{
boost::thread thrd(&hello);
thrd.join();
return 0;
}

程序正常运行:

4. b2编译命令说明

b2.exe --show-libraries 列出所有编译的库

b2.exe --help 查看所有参数使用

综合使用:

1
2
3
4
5
6
7
b2.exe toolset=msvc-10.0 architecture=x86 address-model=32

link=static variant=debug,release threading=multi runtime-link=shared

--without-python --without-mpi --without-wave --without-graph

--without-math --without-serialization stage
  1. toolset:表示编译器工具,我安装的是VS2010,所以是msvc-10(如果你是VS2005,可以使用msvc-8.0 VS2008是msvc-9.0)

  2. architecture:表示架构,也就是你的CPU架构,x86,x64,因为我安装的是win7 32位,所以使用了x86的架构。

  3. address-model:表示地址长度为32位。

  4. link:表示生成动态/静态链接库,动态链接库是shared,静态链接库是static,一般都会编译成静态库,因为给出程序的时候打包boost的库会非常庞大。

  5. variant:表示生成的Debug或者release版本,一般情况下会两种版本都会编译出来的。

  6. threading:表示单/多线程编译,一般我们的程序都会用到多线程,所以选择了multi。

  7. runtime-link:表示动态/静态链接C/C++运行时库(C/C++ Runtime),我们选择了动态链接。

  8. without/with:表示不需要编译/需要编译哪些库,一些自己不用的库可以无需编译。

  9. stage/install:stage表示只生成库文件(DLL和Lib),install还会生成包含头文件的include目录,推荐使用stage,因为boost_1_49\boost中就是boost库完整的头文件,所以无需再拷贝一份出来。编译出来的库会放在stage文件夹中。


Linux下boost库使用

1. 去boost官网下载最新的boost库

同上

2. 解压boost压缩包,进入根目录

执行./bootstrap.sh --prefix=/usr/local/boost_lib。生成编译工具b2。

prefix是指定编译生成的include/lib路径,默认是在/usr/local下。

注意:

执行./bootstrap.sh报下面错误:

./bootstrap.sh Could not find a suitable toolset. You can specify the toolset as the argument, i.e.: ./build.sh [options] gcc。。。

这是因为系统没有安装编译工具。

sudo apt update
sudo apt install build-essential // 这个命令将会安装一系列软件包,包括gcc,g++,和make。

3. 编译boost库

执行./b2 install --with=all

完全编译,并会把生成的include和lib目录放到/usr/local/boost_lib下。

4. 测试

测试程序同上。

编译命令:

1
g++ main.cpp -I /usr/local/boost_lib/include -I /home/boost_1_81_0 -L /usr/local/boost_lib/lib -lboost_thread -lboost_system -lpthread

-I 是指定头文件查找目录,多个用对应多个-I指定。

-L 是指定链接库目录。

-lxxx 是指定用到的库名称。

编译完成,会生成a.out执行文件,这时直接运行还会报错:

1
./a.out: error while loading shared libraries: libboost_thread.so.1.81.0: cannot open shared object file: No such file or directory

解决方法:

1
sudo ldconfig /usr/local/lib/boost_lib/lib

ldconfig命令的作用:ldconfig是一个动态链接库管理命令。安装完成某个工程后生成许多动态库,为了让这些动态链接库为系统所共享,还需运行动态链接库的管理命令–ldconfig。

执行结果: