Skip to content
Latchkey

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_DIR to a known path.
  • Cache that path keyed on github.sha with a restore-keys prefix.
  • Build with the compiler launcher set to ccache.
  • Run ccache -s to 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 -s

Gotchas

  • sccache is the analogous tool for Rust and can use the gha cache backend directly, but ccache pairs with actions/cache.
  • Set CCACHE_MAXSIZE so the cache does not grow past the per-repo cache budget and trigger eviction.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →