@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
感谢支持,长期连载
欢迎关注
