TExcelTAD

Unity Build Pitfalls

A unity build changes the meaning of "translation unit". Code that relied on each .cpp file being compiled alone can break, or worse, keep compiling while hiding bugs. This lesson reproduces the classic failures for real and shows the CMake tools to deal with them.

1. Clashing internal names

Anonymous namespaces and static functions are private to a TU. In a unity build, two files that each define namespace { int helper(); } end up in the same TU:

bash · try it yourself
mkdir -p clash/src && cd clash
for n in parse render; do cat > src/$n.cpp <<SRC
namespace { int helper() { return 1; } }
int $n() { return helper(); }
SRC
done
echo 'int parse(); int render(); int main() { return parse() + render() - 2; }' > src/main.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Clash CXX)
add_executable(app src/main.cpp src/parse.cpp src/render.cpp)
CM
cmake -S . -B build -G Ninja -DCMAKE_UNITY_BUILD=ON > /dev/null
cmake --build build 2>&1 | grep -E 'error|note' | sed 's#/home/learner/clash/##'
src/render.cpp:1:17: error: redefinition of ‘int {anonymous}::helper()’
src/parse.cpp:1:17: note: ‘int {anonymous}::helper()’ previously defined here

There are three fixes, from best to worst:

  1. Rename or move the helper into a shared internal header if it really is the same function.
  2. UNITY_BUILD_UNIQUE_ID (CMake 3.20+): CMake defines a macro to a different value for each source file in the unity file, and you wrap the anonymous namespace contents in a namespace with that name:
bash · try it yourself
mkdir -p uid/src && cd uid
for n in parse render; do cat > src/$n.cpp <<SRC
#ifndef UNITY_ID
#define UNITY_ID   // normal builds: an empty name, i.e. a plain nested anonymous namespace
#endif
namespace { namespace UNITY_ID { int helper() { return 1; } } }
int $n() { return UNITY_ID::helper(); }
SRC
done
echo 'int parse(); int render(); int main() { return parse() + render() - 2; }' > src/main.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Uid CXX)
add_executable(app src/main.cpp src/parse.cpp src/render.cpp)
set_target_properties(app PROPERTIES UNITY_BUILD_UNIQUE_ID UNITY_ID)
CM
cmake -S . -B build -G Ninja -DCMAKE_UNITY_BUILD=ON > /dev/null
cmake --build build | tail -1
./build/app && echo "unity build runs"
grep -c 'define UNITY_ID unity_' build/CMakeFiles/app.dir/Unity/unity_0_cxx.cxx
[2/2] Linking CXX executable app
unity build runs
3

The generated unity file now contains #define UNITY_ID unity_<hash> before each included source (three of them here), so each file's helper lives in its own namespace.

  1. Exclude the file: set_source_files_properties(src/legacy.cpp PROPERTIES SKIP_UNITY_BUILD_INCLUSION ON) compiles it on its own. Fine for a handful of files; if you need it for many, the unity build isn't paying off for that target.

2. Leaking using directives and macros

A using namespace std; or a #define at the top of one file is still active in the files included after it:

bash · try it yourself
mkdir -p leak/src && cd leak
cat > src/a_tools.cpp <<'SRC'
#include <algorithm>
#include <vector>
using namespace std;                         // fine in a normal TU...
int tools() { vector<int> v{1, 2}; return int(count(v.begin(), v.end(), 1)); }
SRC
cat > src/b_stats.cpp <<'SRC'
int count = 0;                               // ...but clashes with std::count in a unity TU
int stats() { return ++count; }
SRC
echo 'int tools(); int stats(); int main() { return tools() + stats() - 2; }' > src/main.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Leak CXX)
add_executable(app src/main.cpp src/a_tools.cpp src/b_stats.cpp)
CM
cmake -S . -B normal -G Ninja > /dev/null && cmake --build normal | tail -1
cmake -S . -B unity -G Ninja -DCMAKE_UNITY_BUILD=ON > /dev/null
cmake --build unity 2>&1 | grep -m1 'error' | sed 's#/home/learner/leak/##'
[4/4] Linking CXX executable app
src/b_stats.cpp:2:24: error: reference to ‘count’ is ambiguous

Macros are worse: #define ERROR 0 or #define min(a, b) … in one file silently changes the meaning of code in the next. Keep using namespace out of file scope and #undef file-local macros at the end of the file.

3. Hidden missing includes

The opposite problem: a file that forgets an include compiles fine in the unity build because an earlier file in the batch included it. Then someone builds without unity, or the batch boundaries move when a file is added, and the build breaks:

bash · try it yourself
mkdir -p hidden/src && cd hidden
printf '#include <string>\nint first() { return std::string("a").size(); }\n' > src/a_first.cpp
printf '// forgot #include <string>\nint second() { return std::string("bb").size(); }\n' > src/b_second.cpp
echo 'int first(); int second(); int main() { return first() + second() - 3; }' > src/main.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Hidden CXX)
add_executable(app src/main.cpp src/a_first.cpp src/b_second.cpp)
CM
cmake -S . -B unity -G Ninja -DCMAKE_UNITY_BUILD=ON > /dev/null
cmake --build unity | tail -1
cmake -S . -B normal -G Ninja > /dev/null
cmake --build normal 2>&1 | grep -m1 'error' | sed 's#/home/learner/hidden/##'
[2/2] Linking CXX executable app
src/b_second.cpp:2:28: error: ‘string’ is not a member of ‘std’

Keep one CI job building without unity (and without PCH). It's the only reliable way to keep every file self-contained.

4. Incremental builds get coarser

Edit one file and the whole batch it belongs to is recompiled:

bash · try it yourself
mkdir -p inc/src && cd inc
for n in a b c d e f g h; do printf '#include <map>\n#include <string>\nint %s() { return std::map<std::string, int>{{"%s", 1}}.size(); }\n' $n $n > src/$n.cpp; done
echo 'int main() { return 0; }' > src/main.cpp
printf 'cmake_minimum_required(VERSION 3.25)\nproject(Inc CXX)\nfile(GLOB SRCS CONFIGURE_DEPENDS src/*.cpp)\nadd_executable(app ${SRCS})\n' > CMakeLists.txt
for unity in OFF ON; do
  cmake -S . -B b-$unity -G Ninja -DCMAKE_UNITY_BUILD=$unity -DCMAKE_CXX_FLAGS=-H > /dev/null
  cmake --build b-$unity > /dev/null 2>&1
done
sleep 1 && touch src/c.cpp
for unity in OFF ON; do
  echo "UNITY=$unity, after editing c.cpp: $(cmake --build b-$unity 2>&1 | grep -c '^\. /home/learner/inc/src/') source files recompiled"
done
UNITY=OFF, after editing c.cpp: 0 source files recompiled
UNITY=ON, after editing c.cpp: 8 source files recompiled

One edit, eight files' worth of compiling. For day-to-day development, that's often slower than a normal build. Many teams therefore enable unity builds only for CI and release configurations (-DCMAKE_UNITY_BUILD=ON in a CI preset), or use small batches.

5. Other things to watch

  • Debugging and coverage still map to the original files (the #include keeps line information), but warnings and errors show the unity file in the "In file included from" chain.
  • ccache caches the unity TU as a whole: a hit needs all files in the batch unchanged.
  • Static initialisation order within one TU follows the include order, which can mask (or expose) order bugs between files.

Test yourself

Two files both define namespace { int helper(); }. What happens in a unity build?

  1. Nothing, anonymous namespaces are per file
  2. A redefinition error, because both end up in the same TU
  3. A link error
  4. CMake renames them automatically

What does UNITY_BUILD_UNIQUE_ID give you?

  1. A different batch for each file
  2. A macro defined to a unique value per source file, to name a nested namespace
  3. A unique object file name
  4. A hash of the build

Why keep one CI job building without unity?

  1. Unity builds are slower in CI
  2. To catch files that only compile because an earlier file in the batch included something
  3. Because ccache doesn't work with unity
  4. To test the linker