Skip to content
Latchkey

ccache in CI: Persisting CCACHE_DIR Between Runs

ccache only helps in CI if its cache directory survives between runs, so the build restores and saves CCACHE_DIR.

A fresh runner starts with an empty ccache, so every build is a full build unless you persist the cache directory. The pattern is: point CCACHE_DIR at a known path, restore it before building, save it after.

What it does

CCACHE_DIR sets where ccache stores objects; restoring that directory at the start of a job and saving it at the end carries hits across runs. CCACHE_BASEDIR rewrites absolute paths under it to relative ones so the cache hits even when the checkout path differs between runners.

Common usage

Terminal
export CCACHE_DIR="$PWD/.ccache"
export CCACHE_BASEDIR="$PWD"
export CCACHE_COMPILERCHECK="%compiler% -v"
ccache -M 2G
# GitHub Actions: restore/save $CCACHE_DIR keyed on a stable key
# - uses: actions/cache with path: .ccache
ccache -z                 # optional: reset stats to measure this run
cmake --build build
ccache -s                 # print hit rate for the log

Options

SettingWhat it does
CCACHE_DIRCache directory to persist between runs
CCACHE_BASEDIRRewrite absolute paths so hits survive path changes
CCACHE_COMPILERCHECKMake hits survive toolchain reinstalls
CCACHE_MAXSIZE / -MBound the cache to fit the CI cache quota
CCACHE_NOHASHDIRExclude the cwd from the hash (helps some setups)

In CI

Use a cache key that changes when the toolchain or major dependencies change but is otherwise stable across commits, with a restore fallback so most builds start warm. Set CCACHE_BASEDIR to the workspace root and CCACHE_COMPILERCHECK to a version command so checkout-path and reinstall differences do not cold-start the cache. End the step with ccache -s so the hit rate is visible.

Common errors in CI

Near-zero hits on a restored cache point at one of: the build dir or checkout path in the hash (fix with CCACHE_BASEDIR), the compiler reinstalled (fix with compiler_check), or the cache not actually being restored (check the cache step ran and the path matched). "Failed to create temporary file" means CCACHE_DIR is not writable on the runner.

Related guides

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