add_custom_target & Host Tools
add_custom_command creates files that targets need. add_custom_target creates a target that runs commands: a named job you can build on request (cmake --build build --target format), or one that runs on every build. Combined, they cover two classic jobs: a tool built by the project that generates code for the rest of the project, and stamps that must be refreshed on every build.
A code generator built in the same project
Here gen_table is a small C++ program that generates a lookup table, and the crc program uses its output. Because the custom command's COMMAND names the target gen_table, CMake substitutes the path of the built executable and makes sure the generator is built first. Watch what happens when the generator changes, though:
mkdir -p crc/tools && cd crc
cat > tools/gen_table.cpp <<'SRC'
// Writes a CRC-32 lookup table as C++ source.
#include <cstdint>
#include <cstdio>
int main(int argc, char** argv) {
if (argc != 2) return 1;
std::FILE* out = std::fopen(argv[1], "w");
std::fprintf(out, "// generated by gen_table\n#include <cstdint>\nextern const std::uint32_t kCrcTable[256] = {\n");
for (std::uint32_t i = 0; i < 256; ++i) {
std::uint32_t c = i;
for (int k = 0; k < 8; ++k) c = (c & 1) ? 0xEDB88320u ^ (c >> 1) : c >> 1;
std::fprintf(out, "0x%08Xu,%s", c, i % 6 == 5 ? "\n" : " ");
}
std::fprintf(out, "};\n");
std::fclose(out);
}
SRC
cat > crc.cpp <<'SRC'
#include <cstdint>
#include <cstdio>
#include <cstring>
extern const std::uint32_t kCrcTable[256];
std::uint32_t crc32(const char* s) {
std::uint32_t c = 0xFFFFFFFFu;
for (; *s; ++s) c = kCrcTable[(c ^ static_cast<unsigned char>(*s)) & 0xFF] ^ (c >> 8);
return c ^ 0xFFFFFFFFu;
}
int main() { std::printf("crc32(\"hello\") = %08x\n", crc32("hello")); }
SRC
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Crc LANGUAGES CXX)
add_executable(gen_table tools/gen_table.cpp) # the host tool
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/crc_table.cpp
COMMAND gen_table ${CMAKE_CURRENT_BINARY_DIR}/crc_table.cpp # target name -> its path
COMMENT "Generating CRC table"
VERBATIM)
add_executable(crc crc.cpp ${CMAKE_CURRENT_BINARY_DIR}/crc_table.cpp)
CM
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build && ./build/crc
echo "--- change the generator"
sleep 1 && sed -i 's|// generated by gen_table|// generated by gen_table v2|' tools/gen_table.cpp
cmake --build build
head -n 1 build/crc_table.cpp
echo "--- add DEPENDS gen_table and build again"
sed -i 's| COMMENT "Generating CRC table"| DEPENDS gen_table\n COMMENT "Generating CRC table"|' CMakeLists.txt
cmake --build build | grep -v -e '^--' -e 'Re-running'
head -n 1 build/crc_table.cpp[1/6] Building CXX object CMakeFiles/gen_table.dir/tools/gen_table.cpp.o
[2/6] Linking CXX executable gen_table
[3/6] Generating CRC table
[4/6] Building CXX object CMakeFiles/crc.dir/crc.cpp.o
[5/6] Building CXX object CMakeFiles/crc.dir/crc_table.cpp.o
[6/6] Linking CXX executable crc
crc32("hello") = 3610a686
--- change the generator
[1/2] Building CXX object CMakeFiles/gen_table.dir/tools/gen_table.cpp.o
[2/2] Linking CXX executable gen_table
// generated by gen_table
--- add DEPENDS gen_table and build again
[1/4] Generating CRC table
[2/4] Building CXX object CMakeFiles/crc.dir/crc_table.cpp.o
[3/4] Linking CXX executable crc
// generated by gen_table v2
crc32("hello") is 3610a686, the standard CRC-32, so the generated table is right. But the first edit of the generator only rebuilt it: the table was not regenerated, and the header line still says the old text. Naming a target in COMMAND adds a target-level dependency (build gen_table before this step), not a file-level one (re-run this step when gen_table changes). Adding DEPENDS gen_table adds the file-level dependency, and the next build re-ran the generator and recompiled the table. Always list the tool in DEPENDS. When cross-compiling, the generator would be built for the target and couldn't run; see Cross-Compiling.
Custom targets
add_custom_target(<name> [ALL] [COMMAND ...] [DEPENDS ...] [BYPRODUCTS ...] [VERBATIM])- Without
ALL, it runs only when requested:cmake --build build --target <name>. Good forformat,docs,lint,deploy. - With
ALL, it is part of the default build and runs every time (custom targets are always out of date). Good for stamps that must be fresh. add_dependencies(<target> <custom-target>)orders it before another target.
A version stamp refreshed on every build
The git commit changes without CMake re-running, so it can't come from configure_file alone. A custom target runs a script on every build; the script rewrites the header only if the content changed (file(CONFIGURE) does that), so nothing recompiles unless the commit really changed:
mkdir -p stamp && cd stamp
git init -q
cat > version.cmake <<'CM'
execute_process(COMMAND git rev-parse --short HEAD
WORKING_DIRECTORY ${SRC} OUTPUT_VARIABLE GIT_SHA OUTPUT_STRIP_TRAILING_WHITESPACE)
file(CONFIGURE OUTPUT ${OUT} CONTENT "#pragma once\n#define GIT_SHA \"@GIT_SHA@\"\n" @ONLY)
CM
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Stamp LANGUAGES CXX)
add_custom_target(git_version ALL
COMMAND ${CMAKE_COMMAND} -DSRC=${CMAKE_SOURCE_DIR} -DOUT=${CMAKE_BINARY_DIR}/git_version.h
-P ${CMAKE_SOURCE_DIR}/version.cmake
BYPRODUCTS ${CMAKE_BINARY_DIR}/git_version.h
COMMENT "Checking the git version"
VERBATIM)
add_executable(app main.cpp)
add_dependencies(app git_version)
target_include_directories(app PRIVATE ${CMAKE_BINARY_DIR})
CM
cat > main.cpp <<'SRC'
#include <cstdio>
#include "git_version.h"
int main() { std::printf("built from %s\n", GIT_SHA); }
SRC
git add . && git commit -q -m "first"
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build && ./build/app
echo "--- no new commit: the script runs, nothing recompiles"
cmake --build build
echo "--- new commit"
git commit -q --allow-empty -m "second"
cmake --build build && ./build/app[1/3] Checking the git version
[2/3] Building CXX object CMakeFiles/app.dir/main.cpp.o
[3/3] Linking CXX executable app
built from 2fce1d9
--- no new commit: the script runs, nothing recompiles
[1/3] Checking the git version
--- new commit
[1/3] Checking the git version
[2/3] Building CXX object CMakeFiles/app.dir/main.cpp.o
[3/3] Linking CXX executable app
built from 52c68be
The commit hashes are stable here because the course image fixes git's dates; on your machine they will differ. Note BYPRODUCTS: it tells Ninja that git_version.h comes from this target, so main.cpp's dependency on it is legal and ordered.
A target for a developer task
find_program(CLANG_FORMAT clang-format)
if(CLANG_FORMAT)
file(GLOB_RECURSE all_sources CONFIGURE_DEPENDS src/*.cpp src/*.hpp)
add_custom_target(format
COMMAND ${CLANG_FORMAT} -i ${all_sources}
COMMENT "Formatting sources"
VERBATIM)
endif()cmake --build build --target format runs it; a normal build never does. (A glob is fine here, because nothing is compiled from it; the field notes explain why globbing sources is a problem.)
Test yourself
In add_custom_command(... COMMAND gen_table out.cpp), gen_table is an executable target in the project. What does CMake do?
- Runs a program called gen_table from PATH
- Replaces it with the built executable's path and makes the command depend on the target
- Errors: COMMAND must be a path
- Builds gen_table at configure time
How often does an add_custom_target(x ALL ...) run?
- Once
- On every build
- Only when its DEPENDS change
- Only at configure time
Why does the version script use file(CONFIGURE ...) instead of file(WRITE ...)?
- It's faster
- It only rewrites the header when the content changes, so files that include it don't recompile on every build
- WRITE can't create headers
- CONFIGURE runs at configure time