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

感谢支持,长期连载

欢迎关注

相关推荐
阿钱真强道10 天前
15 嵌入式操作系统 | 库的下载、编译、安装与验证(libubox / ubus / uci)
ubuntu·cmake·uci·ubus·libubox
阿钱真强道11 天前
22 嵌入式操作系统 | 串口命令行调试(socat / stty / printf / hexdump)
ubuntu·cmake·uci·ubus·libubox
五_谷_丰_登19 天前
cmake脚本学习——持续更新
脚本·cmake
程序员老陆19 天前
CMake 常用关键字与命令全景:从 set到 target_link_options的现代工程视角
c++·cmake·程序开发
idealzouhu21 天前
现代 CMake 依赖管理详解:从构建树、Target 封装到 find_package 工作原理
c++·cmake
熊猫钓鱼>_>23 天前
ArkTS 性能优化实战:从冷启动到长列表,一套可复现的实测方法论
app·harmonyos·arkts·鸿蒙·组件·性能·arkui
小王C语言24 天前
cmake教程
c++·cmake
雾里看山1 个月前
源码目录、构建目录与 out-of-source build
c++·软件构建·cmake
DreamLife☼1 个月前
复杂Agent系统架构设计
系统架构·wpf·agent·组件·设计·构架·说明
ysu_03141 个月前
工具链通关02-CMake进阶超100个文件
cmake