国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > 互联网 > Linux 下编译使用Boost

Linux 下编译使用Boost

来源:程序员人生   发布时间:2014-09-30 01:51:43 阅读次数:3039次

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

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生