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

感谢支持,长期连载

欢迎关注

相关推荐
繁重的秋春3 天前
Qt6.0下的CMake的部署配置
qt·cmake
Lee_jerome9 天前
《C/C++编译全家桶:g++四阶段、.a与.so区别、CMake构建、ARM交叉编译,这篇全讲透了》
c语言·开发语言·arm开发·c++·编译·cmake·cmakelists
开发者联盟league12 天前
cmake 创建和使用静态库(极简版)
c++·cmake·cpp
开发者联盟league15 天前
CMake 实战:创建并使用静态库(MinGW + clangd)
cmake·cpp
Javenwww16 天前
CMake入门——基本语法规则
cmake
郝学胜-神的一滴18 天前
中级OpenGL教程 023:Assimp模型加载全解——从源码到架构的骈文探秘
c++·unity·游戏引擎·cmake·unreal engine·opengl
橙色阳光五月天25 天前
CMake 构建配置文件解析
c++·cmake·plugin
blueman88881 个月前
Qt5通过vcpkg中调用时,在debug模式下调试时总是调用release的plugins文件夹中的dll
c++·qt·cmake
郝学胜-神的一滴1 个月前
CMake 038:OBJECT目标复用编译+Linux动态库版本自动化管理
linux·c++·程序人生·软件工程·软件构建·cmake·工程配置