前言 我今天真的是被这个boost库搞到头炸,怎么在linux下安装boost库,及后续使用。一开始用sudo apt-get install libboost-dev
倒是能解决代码中头文件引用不存在问题,但是编译不成功,总是会出现什么未定义引用错误,之后remove掉,重新下载源码编译还是会存在一些问题。
安装全过程
到这里 下载boost的源码包,我下载的是unix平台的boost源码包,Version 为1.73.0。
这里 有官网指导教程。
下载好,复制到桌面吧,之后解压,得到压缩包。
1 tar --bzip2 -xf boost_1_73_0.tar.bz2
切换到源码目录,cd boost_1_73_0
,可以看到有一个bootstrap.sh文件
然后运行bootstrap.sh脚本并设置相关参数:
1 2 3 ./bootstrap.sh --with-libraries=all --with-toolset=gcc # --with-libraries指定编译哪些boost库,all把全部选上,以免出了啥子差错 # --with-toolset指定编译时使用哪种编译器,Linux使用gcc,当然默认就有
设置完成以后,开始编译,编译命令./b2
,编译过程有点慢,编译结束后大致涨这个模样。
接着就是安装boost,安装命令./b2 install --prefix=/usr
--prefix=/usr
用来指定boost的安装目录,不加此参数的话默认的头文件在/usr/local/include/boost
目录下,库文件在/usr/local/lib/
目录下。这里把安装目录指定为–prefix=/usr则boost会直接安装到系统头文件目录和库文件目录下,可以省略配置环境变量。
我没有指定安装目录,直接``./b2 install`,结果还要配置环境变量烦。
还要注意的一点,这个操作是往usr目录写入一些文件,没有提示需要root权限居然也执行成功了,但是在该出现的目录却没有应该要出现的文件,心态崩了,所以需要在root权限下执行,我又重新做了一遍。
最后运行一下ldconfig
, 该命令通常在系统启动时运行,而当用户安装了一个新的动态链接库时,就需要手工运行这个命令。
示例使用 示例代码
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 #include <boost/filesystem.hpp> #include <iostream> #include <vector> #include <string> #include <time.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> std ::vector <std ::string > dirs;int INTERVAL = 10 ;int main () { for ( boost::filesystem::recursive_directory_iterator end , dir("./0" );dir != end ; ++dir ) { std ::string s = dir->path().c_str(); dirs.push_back(s); } std ::srand(42 ); int ndirs = dirs.size (); std ::cout << "Directories found: " << ndirs << std ::endl ; std ::vector <std ::string > files; for (int i=0 ; i<10000000 ; i++) { int r = std ::rand() % ndirs; std ::string * d = &dirs[r]; std ::string n = *d + "/f" + std ::to_string(i); files.push_back(n); } int nfiles = files.size (); std ::cout << "Files generated: " << nfiles << std ::endl ; int start = (int )time(NULL ); int count = 0 ; int lastcount = 0 ; for (std ::string fn : files) { count++; int f = open (fn.c_str(), O_WRONLY | O_CREAT, 0777 ); close (f); int current = (int )time(NULL ); if (current - start >= INTERVAL) { start = current; printf ("%d:%d\n" , count, (count-lastcount)/INTERVAL); fflush(stdout ); lastcount = count; } } return 0 ; }
调试执行,需要在末尾后面指定 -lboost_filesystem,因为我的示例代码导入了#include <boost/filesystem.hpp>
,相应的其他的也需要指定
1 2 3 4 5 mm@ubuntu:~/桌面/filt$ g++ create.cpp -o creat -lboost_filesystem mm@ubuntu:~/桌面/filt$ ./creat terminate called after throwing an instance of 'boost::filesystem::filesystem_error' what(): boost::filesystem::directory_iterator::construct: No such file or directory: "./0" 已放弃 (核心已转储)
总结 我感觉我的折腾劲在一点点磨掉,我不断地搜索着我出现的问题,其实也就那些前人遇到问题,我不断地尝试,不断地复现,而新问题,我解决不了,还是搜索,求人。