Linux下编译使用boost库:

时间:2023-03-09 15:04:46
Linux下编译使用boost库:

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:

  1. #include <boost/lambda/lambda.hpp>
  2. #include <iostream>
  3. #include <iterator>
  4. #include <algorithm>
  5. int main()
  6. {
  7. using namespace boost::lambda;
  8. typedef std::istream_iterator<int> in;
  9. std::for_each(
  10. in(std::cin), in(), std::cout << (_1 * 3) << " " );
  11. }

编译

$ g++ test.cpp -o test -I /home/xzz/boost_1_56_0/include

-I: 大写的i, 指定头文件搜索目录

执行 ./test 测试, 输入一个数, 返回这个数乘3的值.

再测试需要用到二进制库的功能模块:

将下面的代码保存为 test.cpp:

  1. #include <iostream>
  2. #include <boost/filesystem.hpp>
  3. using namespace boost::filesystem;
  4. int main(int argc, char *argv[])
  5. {
  6. if (argc < 2) {
  7. std::cout << "Usage: tut1 path\n";
  8. return 1;
  9. }
  10. std::cout << argv[1] << " " << file_size(argv[1]) << std::endl;
  11. return 0;
  12. }

编译的时候需要注意:

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

转自:http://blog.csdn.net/xzz_hust/article/details/39583653?utm_source=tuicool&utm_medium=referral