Speed Up C++ Builds on Linux with ccache and Ninja

,
Speed Up C++ Builds on Linux with ccache and Ninja

Slow C++ builds tax every edit. A five-minute rebuild after switching branches or touching a header adds up quickly, and CI pipelines feel it even more. Two tools fix most of this on Linux without changing your code: Ninja, a fast build executor, and ccache, a compiler cache that skips compilations it has already done.

This guide sets both up with CMake, shows how to measure the speedup, and covers the settings and pitfalls that decide whether the cache actually hits. Commands target Ubuntu and Debian; package names are similar elsewhere.

Quick fix: sudo apt install ninja-build ccache, then configure with cmake -S . -B build -G Ninja -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache. Build twice (with a clean in between) and check ccache -s for hits.

What do Ninja and ccache each speed up?

ToolWhat it doesHelps most with
NinjaRuns build steps with low overhead and parallel jobs by defaultIncremental builds, large projects, no-op builds
ccacheCaches object files keyed by compiler input and flagsClean rebuilds, branch switches, CI
Both togetherNinja schedules, ccache short-circuits each compileNearly every workflow

Neither tool makes a single compilation faster. Ninja reduces wasted time around compilations, and ccache avoids repeating them.

Step 1: Install the tools

  1. Install from the distribution:
    sudo apt install ninja-build ccache
    ninja --version
    ccache --version | head -1

    You should see a Ninja version such as 1.11.x and ccache version 4.x.

Step 2: How do you make CMake use Ninja?

  1. Configure a fresh build directory with the Ninja generator:
    cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo
    cmake --build build

    You should see progress lines like [42/180] Building CXX object ... instead of Make’s percentages.

Note: You cannot switch generators in an existing build directory. CMake reports Does not match the generator used previously. Delete the directory or use a new one such as build-ninja.

Ninja uses all CPU cores by default. On machines with limited RAM, heavy template code can run out of memory; limit jobs with cmake --build build -j 4.

Step 3: How do you add ccache to a CMake build?

  1. Use CMake’s compiler launcher variables, which work with any generator:
    cmake -S . -B build -G Ninja \
      -DCMAKE_C_COMPILER_LAUNCHER=ccache \
      -DCMAKE_CXX_COMPILER_LAUNCHER=ccache

    You should see a normal configure run. To confirm, grep LAUNCHER build/CMakeCache.txt should show ccache.

  2. Or set it in CMakeLists.txt so every developer gets it when available:
    find_program(CCACHE_PROGRAM ccache)
    if(CCACHE_PROGRAM)
      set(CMAKE_C_COMPILER_LAUNCHER "${CCACHE_PROGRAM}")
      set(CMAKE_CXX_COMPILER_LAUNCHER "${CCACHE_PROGRAM}")
    endif()

    You should see builds succeed whether or not ccache is installed.

Step 4: How do you measure the speedup?

  1. Reset statistics and do a cold build:
    ccache -z
    time cmake --build build

    This first run prints the full build time and fills the cache.

  2. Clean and rebuild:
    cmake --build build --target clean
    time cmake --build build
    ccache -s

    Here is the real output from a clean-then-rebuild on a 120-file test project (each file pulls in <regex>, <map>, and <format>), built with g++ 14.2.0, CMake 4.4.4, Ninja 1.13.2, and ccache 4.11.2 on an 8-core Debian 13 machine:

    Cacheable calls:    242 / 242 (100.0%)
      Hits:             121 / 242 (50.00%)
        Direct:         121 / 121 (100.0%)
        Preprocessed:     0 / 121 ( 0.00%)
      Misses:           121 / 242 (50.00%)
    Local storage:
      Cache size (GiB): 0.0 / 5.0 ( 0.32%)

    The counters cover both builds since the last ccache -z: 121 misses from the cold build plus 121 direct hits from the rebuild. The 120 units plus main.cpp give 121 compiles per build. A 50% total hit rate here means the second build hit on every file.

Real speedups depend on the project. Builds dominated by compilation benefit most; builds dominated by linking or code generation benefit less.

Measured on a real project: before and after

I timed the same project four ways with /usr/bin/time. The numbers are from one machine, so read them as a shape, not a promise for your codebase.

BuildWall timeWhat it shows
make -j8, cold73.82 sBaseline: every file compiles
Ninja, cold74.97 sSame work, so about the same time
Make no-op rebuild0.20 sMake re-stats everything
Ninja no-op rebuild0.09 sninja: no work to do.
Ninja + ccache, empty cache74.18 sThe cache adds no visible overhead on a miss
Ninja + ccache after clean, warm cache0.38 sEvery compile is a direct-mode hit
Terminal output timing a 120-file C++ project on Debian 13: make -j8 cold 73.82 s, Ninja cold 74.97 s, Ninja no-op 0.09 s, ccache warm rebuild after clean 0.38 s, and ccache -s showing 121 of 242 hits
Real run: g++ 14.2.0, CMake 4.4.4, Ninja 1.13.2, ccache 4.11.2, 8 cores, Debian 13.

What I ran into

The first configure failed before any compiler ran. A fresh Debian container had CMake but no make, and the default generator printed CMake was unable to find a build program corresponding to "Unix Makefiles". CMAKE_MAKE_PROGRAM is not set. followed by CMAKE_CXX_COMPILER not set. The second message is a side effect of the first. Installing make (or passing -G Ninja) fixed both.

The other surprise was that Ninja did not beat Make on a cold build. With -j8, both keep eight compilers busy, so the 120 compiles dominate. Ninja wins on no-op and small incremental builds, and ccache wins when the same sources come back after a clean, a branch switch, or a fresh CI checkout. You can confirm the launcher took effect without reading build logs: grep CMAKE_CXX_COMPILER_LAUNCHER build/CMakeCache.txt printed CMAKE_CXX_COMPILER_LAUNCHER:UNINITIALIZED=ccache.

What happens on each compile with ccache?

Ninja reads build.ninja, compares file timestamps and recorded commands, and schedules only the steps that are out of date. For each compile step, it runs ccache g++ ... instead of g++ ... directly.

ccache first tries a fast “direct mode” lookup: it hashes the source file, the flags, the compiler identity, and the headers recorded last time. On a hit, it copies the stored object file and returns immediately. If that fails, it runs the preprocessor and hashes the result, which still avoids the expensive compile when the preprocessed code matches.

Only on a real miss does the compiler run, and ccache stores the new object for next time. Linking always runs normally, which is why link time becomes the bottleneck once the cache is warm.

Flowchart: Ninja skips up-to-date targets, otherwise runs ccache g++; ccache returns a cached object on a direct-mode or preprocessed hash hit, or runs the compiler and stores the result on a miss; linking always runs.
Ninja decides what to rebuild; ccache decides whether the compiler actually has to run.

How do you check that Ninja is not doing extra work?

Run the build twice without changing anything. The second run should be a no-op:

cmake --build build
ninja -C build -n -d explain | head

You should see ninja: no work to do. If Ninja keeps rebuilding the same targets, -d explain prints why, often a generated file with a fresh timestamp.

Why is ccache missing the cache?

ccache hashes the compiler, its flags, the source, and included headers. Anything that changes these produces a miss. Common culprits:

CauseSymptomFix
__DATE__ / __TIME__ macrosMisses on every buildRemove them, or set sloppiness = time_macros
Absolute paths differ (separate checkouts)No hits across directoriesSet base_dir to the common parent
Generated header changes each buildMisses for files including itOnly rewrite the header when content changes
Cache too smallHit rate drops over timeRaise max_size
Precompiled headersUncacheable callsSet sloppiness = pch_defines,time_macros and see ccache PCH docs

A minimal configuration in ~/.config/ccache/ccache.conf:

max_size = 10G
base_dir = /home/you/src
compression = true

Check active settings with ccache -p. You should see your values with the source file listed next to each.

Warning: Sloppiness options trade correctness checks for hit rate. Enable only the ones you understand, and if a build ever behaves strangely, clear the cache with ccache -C before chasing a phantom bug.

How do you use ccache in CI?

Point the cache to a directory your CI system persists between runs, and print statistics at the end:

export CCACHE_DIR="$PWD/.ccache"
ccache -z
cmake -S . -B build -G Ninja -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
cmake --build build
ccache -s

You should see a low hit rate on the first pipeline run and a high one afterwards, as long as the cache directory is restored. Key the CI cache on the compiler version and branch.

What else makes C++ builds faster?

  • Faster linker: -fuse-ld=mold or -fuse-ld=lld can cut link times sharply for large binaries.
  • Fewer header dependencies: forward declarations and smaller headers reduce recompilation after edits.
  • Split debug info: -gsplit-dwarf reduces linker work in debug builds.
  • Build only what you need: cmake --build build --target mytests.

If you are weighing a bigger change, Bazel provides remote caching and sandboxed builds out of the box; see Bazel vs CMake.

FAQ

Is ccache safe to use?

Yes with default settings. It only returns a cached object when the compiler, flags, and preprocessed input match exactly.

Does ccache work with Clang?

Yes. It supports GCC and Clang, and the CMake launcher setup is identical.

Should I use Ninja or Make with ccache?

ccache works with both. Ninja is usually faster for incremental and no-op builds, so the combination is a common default.

What about sccache?

sccache is a similar tool that can store its cache in cloud storage, which helps distributed CI. For a single machine, ccache is simpler.

Where to start

Switching to Ninja and adding ccache takes one configure command and often makes rebuilds dramatically faster. Measure with ccache -s, fix the usual hit-rate killers, and persist the cache in CI.

Related guides

Official references

Leave a Reply