可行但易失败:CMake常因编译器未找到、std::filesystem链接失败、测试不执行等问题报错;需确认CMake版本与gcc匹配,如ubuntu-latest自带cmake 3.22和gcc 11。

直接用 GitHub Actions + CMake 跑 CI 是可行的,但默认配置下大概率会编译失败——CMake 找不到 compiler、std::filesystem 链接失败、测试不执行,都是高频问题。
确认 CMake 版本与编译器是否匹配
GitHub Actions 的 ubuntu-latest 默认带 cmake 3.22 和 gcc 11,但如果你的 CMakeLists.txt 用了 target_link_libraries(myapp PRIVATE stdc++fs)(为 std::filesystem 手动链接),在 gcc 或 cmake 下就会报错。更稳妥的做法是让 CMake 自动处理:
- 用
find_package(Threads REQUIRED)替代硬写-pthread - 用
find_package(stdc++fs REQUIRED)(CMake 3.18+)或条件判断$控制链接逻辑 - 在
CMakeLists.txt开头显式声明最低版本:cmake_minimum_required(VERSION 3.16),避免被低版本 CI 环境误执行
在 GitHub Actions 中正确设置构建环境
别直接用 run: cmake ... && make。CI 环境没有缓存、路径不稳定,容易因 build/ 目录残留或 CMAKE_BUILD_TYPE 缺失导致行为不一致。推荐标准化流程:
- 固定使用
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_STANDARD=17 - 加
-G Ninja加速构建(比 Make 快 20%~40%,且 Ninja 在 CI 中更少出隐式依赖问题) - 用
actions/checkout@v4后加fetch-depth: 0,否则git describe或子模块会失败 - 若项目含
submodule,必须显式运行git submodule update --init --recursive
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install dependencies
run: sudo apt-get update && sudo apt-get install -y ninja-build
- name: Configure
run: cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_STANDARD=17
- name: Build
run: cmake --build build
- name: Test
run: ctest --test-dir build -C Release --output-on-failure
CTest 集成常被忽略的关键点
ctest 不会自动发现测试,除非你在 CMakeLists.txt 中调用了 add_test() 或启用了 enable_testing()。更常见的是:测试可执行文件编译了,但没注册进 CTest,导致 ctest 显示 0 tests。
立即学习“C++免费学习笔记(深入)”;
- 每个测试可执行文件需单独
add_test(NAME mytest COMMAND mytest) - 如果测试程序依赖动态库,确保
build/下的RPATH正确(加set_target_properties(mytest PROPERTIES INSTALL_RPATH "$ORIGIN/../lib")) - CI 中建议加
--output-on-failure,否则测试崩溃时只输出***Failed***,看不到断言失败详情 - 避免在测试里读写绝对路径(如
/tmp/data.bin),改用${CMAKE_CURRENT_BINARY_DIR}或临时目录 API
最麻烦的其实是跨平台兼容性:Windows 上 std::filesystem::current_path() 返回带盘符的路径,Linux/macOS 没有;CI 日志里看不到颜色输出,catch2 或 gtest 的 verbose 模式得手动开。这些细节不提前验证,PR 一合并就红。











