Ubuntu/Linux系统编译安装boost1.80库

Home / C++ MrLee 8月前 1640

Ubuntu下编译使用Boost 1.80.0版本

http://www.boost.org/下载boost的安装包,以boost_1_80_0.tar.gz为例下载完成后进行解压缩:

sudo -i
tar -zxvf boost_1_80_0.tar.gz
cd boost_1_80_0
./bootstrap.sh
./b2 //开始编译(看机器性能,一般10~30分钟,也可以指定库编译,速度更快,如果是学习建议全部编译)
./b2 --prefix=/usr/local/boost install //安装 当然你也可以省略这一步,只是编译的时候需要自己配置CMakeLists.txt中boost库的路径

指定编译库

# 只编译filesystem库
./b2 --with-filesystem

指定库类型

# 生成静态库
./b2 link=static
 
# 生成动态库
./b2 link=shared

使用语言标准

# 添加编译器标志,例如使用C++17标准
./b2 cxxflags=-std=c++17

编辑环境变量

sudo vi /etc/profile
# 头文件路径
CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:/usr/local/boost/include
# 动态库以及静态库
LIBRARY_PATH=$LIBRARY_PATH:/usr/local/boost/lib
export LIBRARY_PATH CPLUS_INCLUDE_PATH 
#加载
source /etc/profile

使用C++程序进行测试boost库是否安装完成

#include <iostream>
#include <boost/version.hpp>
#include <boost/config.hpp>
#include <boost/thread/thread.hpp>
#include <cstdlib>
using namespace std;
volatile bool isRuning = true;
void func1()
{
    static int cnt1 = 0;
    while(isRuning)
    {
        cout << "func1:" << cnt1++ << endl;
        sleep(1);
    }
}
void func2()
{
    static int cnt2 = 0;
    while(isRuning)
    {
        cout << "\tfunc2:" << cnt2++ << endl;
        sleep(2);
    }
}
int main()
{
    boost::thread thread1(&func1);
    boost::thread thread2(&func2);
    system("read");
    isRuning = false;
    thread2.join();
    thread1.join();
    cout << "exit" << endl;
    return 0;
}

进行测试以及遇到的问题解决方法

编译方法:

#需要手动指定动态库路径
g++ main.cpp -o main -L/usr/local/boost/lib  -lboost_thread -lpthread

注意:如果在编译过程中出现无法找到头文件问题,则再次执行:"source /etc/profile"即可。

编译完成后尝试执行可执行程序

root@tl-vmware:/home# ./main 
./main: error while loading shared libraries: libboost_thread.so.1.83.0: cannot open shared object file: No such file or directory
# 无法打开共享目标文件:没有这样的文件或目录

解决方法:

1、临时使用(仅对当前终端有效,终端退出后失效)

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/boost/lib
#因为我们安装是安装在/usr/local/boost的

2、修改/.bashrc或/.bash_profile或/etc/profile。

区别是前两个只对当前用户生效,/etc/profile对所有用户起效。

修改~/.bashrc的例子

sudo gedit ~/.bashrc
# 添加一句
export LD_LIBRARY_PATH=/usr/local/boost/lib:$LD_LIBRARY_PATH
# 保存退出
source ~/.bashrc

修改/etc/profile的例子

sudo gedit /etc/profile
# 在文件末尾添加
export LD_LIBRARY_PATH=/usr/local/boost/lib{LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
# 保存退出
source /etc/profile

在根目录/etc/ld.so.conf.d/路径下创建任意boost.conf文件(有冲突则更改),把lib文件的路径写在里面

sudo gedit /etc/ld.so.conf.d/boost.conf
# 写入
/usr/local/boost/lib
# 保存退出
 
# 更新缓存
sudo ldconfig


本文链接:https://it72.com/12770.htm

推荐阅读
最新回复 (0)
返回