boost库某些库不需要编译,包含头文件就可以使用,有些需要编译后才能使用。
不一定非得按照教程安装完成才能使用,那样太过于庞大。并且还要安装很多依赖,所以只需要取需要的库就可以了。
使用命令解压:
tar zxvf boost_1_69_0.tar.gz
进入解压后的文件夹。使用命令查看哪些库需要单独编译:
./bootstrap.sh --show-libraries
结果如下:
The Boost libraries requiring separate building and installation are:
- atomic
- chrono
- container
- context
- contract
- coroutine
- date_time
- exception
- fiber
- filesystem
- graph
- graph_parallel
- iostreams
- locale
- log
- math
- mpi
- program_options
- python
- random
- regex
- serialization
- stacktrace
- system
- test
- thread
- timer
- type_erasure
- wave
接下来就是使用了,先使用不需要编译的库,直接使用头文件,测试代码:
#include <boost/lexical_cast.hpp> //不需要单独编译的库
#include <iostream>
using namespace std;
int main()
{
using boost::lexical_cast;
int a=lexical_cast<int>("123");
double b=lexical_cast<double>("123.0123456789");
string s0=lexical_cast<string>(a);
string s1=lexical_cast<string>(b);
cout<<"number: "<<a<<" "<<b<<endl;
cout<<"string: "<<s0<<" "<<s1<<endl;
int c=0;
try{
c=lexical_cast<int>("abcd");
}
catch(boost::bad_lexical_cast& e){
cout<<e.what()<<endl;
}
return 0;
}
然后开始编译,使用命令时记得加上库的路径:
g++ -o test test.cpp -I /home/maomao/boost/boost_1_69_0/
接下来使用需要编译的库。
加上一个库 #include<boost/asio.hpp>,这个库是需要便宜的,因为使用了thread。直接编译报错:
[maomao@localhost boost]$g++ -o test test.cpp -I /home/maomao/boost/boost_1_69_0/
/tmp/ccj8x1Mh.o:在函数‘boost::asio::detail::posix_thread::~posix_thread()’中:
test.cpp:(.text._ZN5boost4asio6detail12posix_threadD2Ev[_ZN5boost4asio6detail12posix_threadD5Ev]+0x26):对‘pthread_detach’未定义的引用
/tmp/ccj8x1Mh.o:在函数‘boost::asio::detail::posix_thread::join()’中:
test.cpp:(.text._ZN5boost4asio6detail12posix_thread4joinEv[_ZN5boost4asio6detail12posix_thread4joinEv]+0x2b):对‘pthread_join’未定义的引用
collect2: 错误:ld 返回 1
所以开始编译库,需要用到哪个就编译哪个。
./bootstrap.sh --with-libraries=thread --prefix=/home/maomao/boost/
指定需要的库和库生成的路径,然后开始编译安装。
./b2 install
之后指定路径下出现include和lib文件夹。lib中出现我们需要的库:
开始使用:
g++ -I /home/maomao/boost/boost_1_69_0/ -o test test.cpp -L. /home/maomao/boost/lib/libboost_thread.so /home/maomao/boost/lib/libboost_system.so -lpthread
命令因为加了路径所以显得长,后面还连接了-lpthread。
执行时需要指定链接库的路径:
export LD_LIBRARY_PATH=/home/maomao/boost/lib/:$LD_LIBRARY_PATH
这样就ok了