CMake实现客户端、服务端交流

@bit::Shadow
✧(≖ ◡ ≖✿

手写CMakeLists.txt构建

cpp 复制代码
# 1. 版本最低限制
cmake_minimum_required(VERSION 3.18)
# 2. 设置项目名称
project(UdpComunication)
# 3. 指定C++标准
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# 3. 设置项目依赖
add_executable(udpServer UdpServer.cc)
add_executable(udpClient UdpClient.cc)

首次cmake .输出解释

bash 复制代码
w@instance-qhw6x01g:~/e2026/Auguest/8-7UDP$ cmake .
-- The C compiler identification is GNU 11.4.0
-- The CXX compiler identification is GNU 11.4.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/w/e2026/Auguest/8-7UDP
w@instance-qhw6x01g:~/e2026/Auguest/8-7UDP$ cmake .
-- Configuring done
-- Generating done
-- Build files have been written to: /home/w/e2026/Auguest/8-7UDP

解释

关键信息

bash 复制代码
-- Build files have been written to: /home/w/e2026/Auguest/8-7UDP/build

证明已经配置完成,未出错。

可能出现的经典问题及原因

虽然你这次成功了,但这些是 CMake 新手最常踩的坑:

问题1:cmake .mkdir -p build && cd build && cmake .. 的区别

方式 优点 缺点
cmake . 简单直接 污染源码目录(生成一大堆 CMake 临时文件)
mkdir build && cd build && cmake .. 源码目录干净 ,方便 git 管理 多打几个命令

推荐做法 :永远用 make -p build && cd build && cmake ..,不要用 cmake .

当CMakeLists.txt再次更改

bash 复制代码
cd build          # 进入已有的 build 目录(如果当前不在的话)
cmake ..          # 重新配置,更新 Makefile
make              # 重新编译

CMake + 路径的作用范围

cmake . 只作用于"当前目录下的 CMakeLists.txt 文件",不会自动去下级目录找 .cc 源文件或 CMakeLists.txt

make

成功编译构建,生成了两个可执行程序udpServer与udpClient

bash 复制代码
w@instance-qhw6x01g:~/e2026/Auguest/8-7UDP/build$ make
Consolidate compiler generated dependencies of target udpServer
[ 25%] Building CXX object CMakeFiles/udpServer.dir/UdpServer.cc.o
[ 50%] Linking CXX executable udpServer
[ 50%] Built target udpServer
[ 75%] Building CXX object CMakeFiles/udpClient.dir/UdpClient.cc.o
[100%] Linking CXX executable udpClient
[100%] Built target udpClient

感谢支持,长期连载

欢迎关注

相关推荐
idealzouhu21 小时前
现代 CMake 依赖管理详解:从构建树、Target 封装到 find_package 工作原理
c++·cmake
熊猫钓鱼>_>3 天前
ArkTS 性能优化实战:从冷启动到长列表,一套可复现的实测方法论
app·harmonyos·arkts·鸿蒙·组件·性能·arkui
小王C语言4 天前
cmake教程
c++·cmake
雾里看山14 天前
源码目录、构建目录与 out-of-source build
c++·软件构建·cmake
DreamLife☼14 天前
复杂Agent系统架构设计
系统架构·wpf·agent·组件·设计·构架·说明
ysu_031415 天前
工具链通关02-CMake进阶超100个文件
cmake
图扑可视化16 天前
统一 DataModel 底座,HT UI 组件万物同源|中篇・运笔
ui·数字孪生·组件
十五年专注C++开发16 天前
CMake基础:BUILD_INTERFACE 与 INSTALL_INTERFACE 完全解析
c++·cmake·build_interface
羑悻的小杀马特18 天前
百度ASR+BRPC+ETCD高并发高可用架构搭建,C++客户端API封装+语音识别子服务注册发现+全链路测试调优终极指南!
架构·sdk·etcd·cmake·百度智能云·brpc·语音识别子服务
_YouziTech_19 天前
VS Code环境下LVGL模拟器的配置与运行
visualstudio·mingw·cmake·lvgl·vs code·模拟器·sdl2