Ubuntu22.04中使用CMake配置运行boost库示例程序

Ubuntu22.04中使用CMake配置运行boost库示例程序

boost是一个比较强大的C++准标准库,里面有很多值得学习的东西,比较asio网络库可以用来编写C++ TCP客户端或者TCP服务端接收程序。本文主要讲解如何在Ubuntu22.04中使用Cmake配置boost库,以及运行boost示例程序。

Ubuntu22.04上安装boost库

参考在Ubuntu上安装Boost的五种方法(全网最全,建议收藏)中使用apt-get安装libboost-all-dev包的方式安装boost库,目前最新稳定版本是1.74.0

shell 复制代码
sudo apt-get update
sudo apt-get install libboost-all-dev

对应的boost安装目录为:/usrinclude头文件所在目录为:/usr/includeso库文件安装目录为:/usr/lib/x86_64-linux-gnu

编写boost示例程序

boost示例程序BoostExample_array_003.cpp如下:

cpp 复制代码
#include <iostream>
#include <boost/array.hpp>

using namespace std;

int main()
{
    boost::array<int, 4> arr = {{1, 2, 3, 4}};
    std::cout << "hi " << arr[0] << std::endl;

    return 0;
}

编写CMakeLists.txt文件

在上述BoostExample_array_003.cpp示例源代码同级目录下新建一个CMakeLists.txt文件

首选我们需要安装cmake,至于如何在ubuntu22.04安装cmake,直接使用sudo apt-get install cmake即可,当然也可以下载cmake源代码安装。

CMakeLists.txt 复制代码
project(BoostExamples)
cmake_minimum_required(VERSION 3.7)
# 设置C++标准
set(CMAKE_CXX_STANDARD 14)

# 首选的Boost安装路径
set(BOOST_ROOT /usr)
# 首选的头文件搜索路径 e.g. <prefix>/include
set(BOOST_INCLUDEDIR /usr/include)
# 首选的库文件搜索路径 e.g. <prefix>/lib
set(BOOST_LIBRARYDIR /usr/lib/x86_64-linux-gnu)
# 默认是OFF. 如果开启了,则不会搜索用户指定路径之外的路径
set(BOOST_NO_SYSTEM_PATHS ON)

find_package(Boost COMPONENTS regex system REQUIRED)

if (Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})

    MESSAGE( STATUS "Boost_INCLUDE_DIRS = ${Boost_INCLUDE_DIRS}.")
    MESSAGE( STATUS "$Boost_LIBRARIES = ${Boost_LIBRARIES}.")
    MESSAGE( STATUS "Boost_LIB_VERSION = ${Boost_LIB_VERSION}.")
  
    add_executable(BoostExample_array_003 BoostExample_array_003.cpp)
    target_link_libraries(BoostExample_array_003 ${Boost_LIBRARIES})
endif()

关于在linux下使用cmake配置boost库,可以参考FindBoostCMake中引用Boost库

运行程序

cd到BoostExample_array_003.cpp源代码和CMakeLists.txt同级目录,执行'mkdir build创建一个build`目录用于cmake编译源代码,这样的话就不会污染源代码目录了,

复制代码
cd ~/workspace/CppProjects/BoostExamples
mkdir build
cmake ..
make

这样就生成了BoostExample_array_003可执行程序,

在命令行终端terminal中执行./BoostExample_array_003,运行结果如下:

参考资料

相关推荐
翻滚吧键盘2 分钟前
查看linux中steam游戏的兼容性
linux·运维·游戏
小能喵7 分钟前
Kali Linux Wifi 伪造热点
linux·安全·kali·kali linux
汀沿河21 分钟前
8.1 prefix Tunning与Prompt Tunning模型微调方法
linux·运维·服务器·人工智能
zly350034 分钟前
centos7 ping127.0.0.1不通
linux·运维·服务器
小哥山水之间1 小时前
基于dropbear实现嵌入式系统ssh服务端与客户端完整交互
linux
ldj20202 小时前
2025 Centos 安装PostgreSQL
linux·postgresql·centos
翻滚吧键盘2 小时前
opensuse tumbleweed上安装显卡驱动
linux
liulilittle3 小时前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
cui_win3 小时前
【内存】Linux 内核优化实战 - net.ipv4.tcp_tw_reuse
linux·网络·tcp/ip
十年编程老舅3 小时前
跨越十年的C++演进:C++20新特性全解析
c++·c++11·c++20·c++14·c++23·c++17·c++新特性