How to Cache ccache for C++ Builds in GitHub Actions
Point CCACHE_DIR at a cached directory and key it per commit with a prefix fallback so the compiler reuses object files.
ccache caches compiled object files so unchanged translation units are not recompiled. In CI, set CCACHE_DIR, cache that directory keyed on the commit with a branch prefix fallback, and configure ccache to point your compiler through it.
Steps
- Install ccache and set
CCACHE_DIRto a known path. - Cache that path keyed on
github.shawith arestore-keysprefix. - Build with the compiler launcher set to ccache.
- Run
ccache -sto confirm the hit rate.
Workflow
.github/workflows/ci.yml
env:
CCACHE_DIR: ${{ github.workspace }}/.ccache
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update && sudo apt-get install -y ccache
- uses: actions/cache@v4
with:
path: ${{ env.CCACHE_DIR }}
key: ccache-${{ runner.os }}-${{ github.sha }}
restore-keys: |
ccache-${{ runner.os }}-
- run: |
cmake -B build -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
cmake --build build
ccache -sGotchas
- sccache is the analogous tool for Rust and can use the gha cache backend directly, but ccache pairs with
actions/cache. - Set
CCACHE_MAXSIZEso the cache does not grow past the per-repo cache budget and trigger eviction.
Related guides
How to Cache Cargo Registry and target in GitHub ActionsCache the Cargo registry, git index, and the target directory in GitHub Actions keyed on Cargo.lock, so Rust…
How to Cache a Custom Directory with a Hashed Key in GitHub ActionsCache any directory in GitHub Actions with actions/cache using a key built from hashFiles, so an expensive ge…