How to Set Up CI for C++ (CMake) With GitHub Actions
Configure and build with cmake, run the suite with ctest, and cache the build directory to speed reconfigures.
Configure the build with cmake -B build, compile with cmake --build, and run tests with ctest. An OS matrix exercises the toolchains you ship on, and caching the build dir speeds incremental work.
Steps
- Check out the code.
- Cache the
build/directory keyed on the CMake files. - Configure with
cmake -B build -DCMAKE_BUILD_TYPE=Release. - Build with
cmake --build buildand test withctest.
Workflow
.github/workflows/ci.yml
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
build:
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: build
key: cmake-${{ matrix.os }}-${{ hashFiles('**/CMakeLists.txt') }}
- run: cmake -B build -DCMAKE_BUILD_TYPE=Release
- run: cmake --build build --config Release
- run: ctest --test-dir build --output-on-failureGotchas
ctestonly sees tests registered viaadd_testorgtest_discover_testsin CMake.- On Windows runners, pass
--config Releaseto both build and ctest for multi-config generators.
Related guides
How to Set Up CI for Rust With GitHub ActionsSet up GitHub Actions CI for a Rust crate: install the toolchain with rustup, cache the cargo registry and ta…
How to Set Up CI for Go With GitHub ActionsSet up GitHub Actions CI for a Go module: setup-go caches the build and module caches, go build verifies comp…