TExcelTAD

Unity Builds

A unity build (also called a jumbo or amalgamated build) compiles several .cpp files as one translation unit, by generating a file that #includes them one after another. Headers shared by those files are then parsed once per batch instead of once per file. Chromium, Unreal Engine, WebKit and many game studios have used unity builds for years, and SQLite ships its whole library as a single amalgamated .c file partly for the same reason.

CMake supports it natively since 3.16:

cmake
set(CMAKE_UNITY_BUILD ON)               # or -DCMAKE_UNITY_BUILD=ON at configure time (preferred)
set_target_properties(core PROPERTIES
  UNITY_BUILD ON
  UNITY_BUILD_BATCH_SIZE 16)            # files per generated unity source; default 8

CMAKE_UNITY_BUILD initialises the UNITY_BUILD property of every target created afterwards. Passing it on the command line keeps it a per-build choice: developers can keep normal builds while CI uses unity builds, or the other way round.

Counting translation units

This session builds a 13-file project in the normal way and as a unity build, with -H to count header opens (as in the PCH lesson):

bash · try it yourself
mkdir -p jumbo/src && cd jumbo
for n in a b c d e f g h i j k l; do cat > src/$n.cpp <<SRC
#include <map>
#include <string>
int $n() { std::map<std::string, int> m{{"$n", 1}}; return int(m.size()); }
SRC
done
echo 'int main() { return 0; }' > src/main.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Jumbo CXX)
file(GLOB SRCS CONFIGURE_DEPENDS src/*.cpp)
add_executable(app ${SRCS})
CM
for unity in OFF ON; do
  cmake -S . -B build-$unity -G Ninja -DCMAKE_UNITY_BUILD=$unity -DCMAKE_CXX_FLAGS=-H > /dev/null
  cmake --build build-$unity > build-$unity.log 2>&1
  echo "UNITY=$unity: $(grep -c 'Building CXX' build-$unity.log) compiles, $(grep -c '^\.' build-$unity.log) header opens"
done
echo "--- generated unity sources:"
ls build-ON/CMakeFiles/app.dir/Unity/
grep -c '#include' build-ON/CMakeFiles/app.dir/Unity/unity_0_cxx.cxx build-ON/CMakeFiles/app.dir/Unity/unity_1_cxx.cxx
UNITY=OFF: 13 compiles, 1944 header opens
UNITY=ON: 2 compiles, 337 header opens
--- generated unity sources:
unity_0_cxx.cxx
unity_0_cxx.cxx.o
unity_1_cxx.cxx
unity_1_cxx.cxx.o
build-ON/CMakeFiles/app.dir/Unity/unity_0_cxx.cxx:8
build-ON/CMakeFiles/app.dir/Unity/unity_1_cxx.cxx:5

Thirteen files became two compiles: the default batch size of 8 gives one unity source with 8 files and one with the remaining 5. <map> and <string> are parsed twice instead of twelve times, and the header-open count drops accordingly. Each generated file is just a list of #include "/abs/path/to/src/x.cpp" lines.

Choosing the batch size

Batch size Effect
small (2–4) modest savings; incremental builds stay cheap
default (8) a good start for most projects
large (16–50) biggest clean-build savings, but huge TUs: more memory per job, fewer jobs to spread over cores, and every edit recompiles a big batch
"whole target" one TU per target: maximum savings, worst incremental and parallel behaviour

The Amdahl lesson showed why fewer, larger jobs hurt on many-core machines and build farms: if a target becomes 4 unity files, at most 4 cores work on it. Tune the batch size so the number of unity TUs is still larger than your core count.

GROUP mode: choose the batches yourself

UNITY_BUILD_MODE GROUP (CMake 3.18+) lets you group files by hand with the UNITY_GROUP source property, for example to keep files that edit together in the same batch, or to keep a problematic file alone:

cmake
set_target_properties(core PROPERTIES UNITY_BUILD ON UNITY_BUILD_MODE GROUP)
set_source_files_properties(src/lexer.cpp src/parser.cpp PROPERTIES UNITY_GROUP "front")
set_source_files_properties(src/codegen.cpp src/emit.cpp PROPERTIES UNITY_GROUP "back")

Files without a group are compiled normally.

Unity builds vs PCH

Both attack the same cost, repeated header parsing, and they combine:

PCH Unity build
Saves parsing of the headers in the PCH parsing of all shared headers and repeated template instantiations in a batch
Code changes needed none, but hidden-include risk sometimes (name clashes, see the next lesson)
Incremental edits cheap unless the PCH changes recompile a whole batch
Parallelism unchanged fewer, larger jobs
ccache needs sloppiness settings works, but a hit needs the whole batch unchanged

A common recipe is PCH for third-party headers in every build, plus unity builds in CI and release builds where clean-build time matters most. The Mini Project measures both on the same code.

Test yourself

13 source files, CMAKE_UNITY_BUILD=ON and the default batch size. How many compiles?

  1. 1
  2. 2
  3. 8
  4. 13

Why can a very large batch size slow a build down on a 32-core machine?

  1. CMake limits batches to 8
  2. Fewer, larger TUs mean fewer jobs than cores, so cores sit idle
  3. Unity builds disable -O2
  4. Ninja can't build unity files in parallel

What is inside a generated unity source file?

  1. Preprocessed code
  2. #include lines for the original .cpp files
  3. Object code
  4. A list of headers