Linux 下编译使用Boost

49 篇文章 0 订阅

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\n";
		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库安装成功.

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值