add_custom_command: Generating Code
Not everything in a build is "compile a .cpp". Projects embed data files into the binary, generate code from schemas (protobuf, flatbuffers, shaders), or post-process outputs. add_custom_command adds such a step to the build graph: it has outputs, inputs and a command, and Ninja runs it only when an input changed, exactly like a compile step.
add_custom_command(
OUTPUT <files it creates>
COMMAND <program> <args>... # may be repeated
DEPENDS <files or targets it reads>
[BYPRODUCTS <other files>] [WORKING_DIRECTORY <dir>] [COMMENT "..."] [VERBATIM])The command runs when something needs its OUTPUT, typically because the output is listed as a source of a target. If nothing uses the output, the command never runs.
Embedding a data file
This project turns messages.txt into a C++ source file with an array of strings, using a CMake script as the generator (portable: cmake -P runs anywhere CMake does):
mkdir -p embed && cd embed
cat > messages.txt <<'TXT'
Welcome!
Build succeeded.
TXT
cat > gen_messages.cmake <<'CM'
# Usage: cmake -DINPUT=messages.txt -DOUTPUT=messages.cpp -P gen_messages.cmake
file(STRINGS "${INPUT}" lines)
list(LENGTH lines n)
set(body "")
foreach(line IN LISTS lines)
string(APPEND body " \"${line}\",\n")
endforeach()
file(WRITE "${OUTPUT}" "// generated from ${INPUT}: do not edit\n#include <cstddef>\nextern const char* const kMessages[] = {\n${body}};\nextern const std::size_t kMessageCount = ${n};\n")
CM
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Embed LANGUAGES CXX)
set(gen ${CMAKE_CURRENT_BINARY_DIR}/messages.cpp)
add_custom_command(
OUTPUT ${gen}
COMMAND ${CMAKE_COMMAND} -DINPUT=${CMAKE_CURRENT_SOURCE_DIR}/messages.txt
-DOUTPUT=${gen} -P ${CMAKE_CURRENT_SOURCE_DIR}/gen_messages.cmake
DEPENDS messages.txt gen_messages.cmake # rerun when the data OR the generator changes
COMMENT "Generating messages.cpp"
VERBATIM)
add_executable(app main.cpp ${gen})
CM
cat > main.cpp <<'SRC'
#include <cstdio>
#include <cstddef>
extern const char* const kMessages[];
extern const std::size_t kMessageCount;
int main() { for (std::size_t i = 0; i < kMessageCount; ++i) std::printf("%zu: %s\n", i, kMessages[i]); }
SRC
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build && ./build/app
echo "--- build again: nothing to do"
cmake --build build
echo "--- edit the data file"
sleep 1 && echo 'Goodbye.' >> messages.txt
cmake --build build && ./build/app
head -n 3 build/messages.cpp[1/4] Generating messages.cpp
[2/4] Building CXX object CMakeFiles/app.dir/main.cpp.o
[3/4] Building CXX object CMakeFiles/app.dir/messages.cpp.o
[4/4] Linking CXX executable app
0: Welcome!
1: Build succeeded.
--- build again: nothing to do
ninja: no work to do.
--- edit the data file
[1/3] Generating messages.cpp
[2/3] Building CXX object CMakeFiles/app.dir/messages.cpp.o
[3/3] Linking CXX executable app
0: Welcome!
1: Build succeeded.
2: Goodbye.
// generated from /home/learner/embed/messages.txt: do not edit
#include <cstddef>
extern const char* const kMessages[] = {
Key points:
${CMAKE_COMMAND}is the full path of the runningcmake, the portable way to call CMake (orcmake -Etools) from a build step.DEPENDSmust list every input, including the generator script. Forget one and edits to it won't trigger a rebuild, which is the most common custom-command bug.VERBATIMmakes CMake quote arguments correctly for the shell of each platform. Always add it.- The generated file lives in the build directory. After the edit, Ninja re-ran the generator, recompiled
messages.cppand relinked;main.cppwas not touched.
Running a step after a target is built
The second signature attaches commands to a target instead of producing files: PRE_BUILD, PRE_LINK or POST_BUILD.
mkdir -p post && cd post
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Post LANGUAGES CXX)
add_executable(tool main.cpp)
add_custom_command(TARGET tool POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/dist
COMMAND ${CMAKE_COMMAND} -E copy lt;TARGET_FILE:tool> ${CMAKE_BINARY_DIR}/dist/
COMMAND ${CMAKE_COMMAND} -E echo "copied lt;TARGET_FILE_NAME:tool> to dist/"
VERBATIM)
CM
echo 'int main() { return 0; }' > main.cpp
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build
ls build/dist[1/2] Building CXX object CMakeFiles/tool.dir/main.cpp.o
[2/2] Linking CXX executable tool
copied tool to dist/
tool
lt;TARGET_FILE:tool> is the generator expression for the built file's path, so this works with every generator and configuration. Typical POST_BUILD jobs: copying DLLs next to an executable on Windows, code signing, stripping or splitting debug info.
cmake -E: portable shell commands
Build steps shouldn't call cp, mkdir -p or rm -rf, which don't exist in a Windows shell. cmake -E provides portable equivalents:
cmake -E make_directory out/a/b
cmake -E echo "hello" > out/a/b/file.txt
cmake -E copy out/a/b/file.txt out/copy.txt
cmake -E copy_if_different out/copy.txt out/copy2.txt
cmake -E sha256sum out/copy.txt
cmake -E tar cf out.tar --mtime=2026-01-01 out
cmake -E rm -rf out
cmake -E tar tf out.tar
cmake -E compare_files out.tar out.tar && echo "identical"5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03 out/copy.txt
out/
out/a/
out/a/b/
out/a/b/file.txt
out/copy.txt
out/copy2.txt
identical
Run cmake -E with no arguments for the full list (create_symlink, env, time, capabilities, cat, touch…).
BYPRODUCTS
Some tools write more files than the ones you care about (a log, an index). List those as BYPRODUCTS: Ninja then knows who creates them (so it can order steps and clean them), and other targets may depend on them. With Ninja, a byproduct that something depends on must be declared, or Ninja reports a missing rule.
Test yourself
A custom command's OUTPUT is not used as a source by any target. When does the command run?
- On every build
- Never: something must depend on its output
- Only at configure time
- Only with --target all
You edit the generator script, but the generated file isn't regenerated. What's missing?
- VERBATIM
- The script in DEPENDS
- A POST_BUILD step
- BYPRODUCTS
Why use ${CMAKE_COMMAND} -E copy instead of cp in a build step?
- It is faster
- It works on every platform, including Windows shells
- cp is not allowed in CMake
- It preserves timestamps