TExcelTAD
Home › Modern CMake (with CTest & CPack) › Generator Expressions

Generator Expressions

A generator expression (genex) is a piece of text in the form

lt;...> that CMake evaluates when it generates the build files, not while it runs CMakeLists.txt. At that point it knows things the configure step doesn't: which configuration is being generated (multi-config generators produce several), the final file name of every target, and which compiler and language each source file uses.

cmake
target_compile_definitions(app PRIVATE 
lt;
lt;CONFIG:Debug>:APP_DEBUG>) # │ │ └ value if true # │ └ condition: 1 when the config is Debug # └
lt;cond:value> = value if cond is 1, else nothing

Seeing what they evaluate to

You can't message() a generator expression, because it isn't evaluated yet during configure. Instead, file(GENERATE) writes a file at generate time, once per configuration, with the expressions evaluated. It is the standard debugging tool. With the multi-config generator you see every configuration:

bash · try it yourself
mkdir -p genex && cd genex
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Genex VERSION 2.0.0 LANGUAGES CXX)
add_library(core SHARED core.cpp)
set_target_properties(core PROPERTIES VERSION 2.0.0 SOVERSION 2)
add_executable(app main.cpp)

message("during configure: 
lt;CONFIG>") # not evaluated here: printed literally file(GENERATE OUTPUT genex-
lt;CONFIG>.txt CONTENT "config =
lt;CONFIG> is Debug? =
lt;CONFIG:Debug> debug-or-release =
lt;IF:
lt;CONFIG:Debug>,debug,release> compiler =
lt;CXX_COMPILER_ID>
lt;CXX_COMPILER_VERSION> compiler is GNU? =
lt;CXX_COMPILER_ID:GNU> core file =
lt;TARGET_FILE_NAME:core> core soname =
lt;TARGET_SONAME_FILE_NAME:core> core dir =
lt;TARGET_FILE_DIR:core> app type =
lt;TARGET_PROPERTY:app,TYPE> bool logic =
lt;AND:1,
lt;NOT:0>>
lt;OR:0,0>
lt;BOOL:OFF> strings =
lt;UPPER_CASE:hello>
lt;JOIN:a;b;c,+>
lt;VERSION_GREATER:4.4,3.25> " TARGET app) # compiler queries such as
lt;CXX_COMPILER_ID> need a target to ask about CM echo 'int core() { return 1; }' > core.cpp echo 'int main() { return 0; }' > main.cpp cmake -S . -B build -G "Ninja Multi-Config" --log-level=NOTICE | grep -v '^--' cat build/genex-Debug.txt echo "---" diff build/genex-Debug.txt build/genex-Release.txt | grep '^>'
during configure: 
lt;CONFIG> config = Debug is Debug? = 1 debug-or-release = debug compiler = GNU 13.3.0 compiler is GNU? = 1 core file = libcore.so.2.0.0 core soname = libcore.so.2 core dir = /home/learner/genex/build/Debug app type = EXECUTABLE bool logic = 1 0 0 strings = HELLO a+b+c 1 --- > config = Release > is Debug? = 0 > debug-or-release = release > core dir = /home/learner/genex/build/Release

Note the configure-time message() printed

lt;CONFIG> literally. Note also the TARGET app argument: compiler and language queries such as
lt;CXX_COMPILER_ID>
need a target to answer for (each target could use a different compiler), and without it file(GENERATE) fails with
lt;CXX_COMPILER_ID> may only be used with binary targets
. Generator expressions work only where CMake documents them: in target properties and the target_* commands, install() destinations and some arguments, add_custom_command, add_test, and file(GENERATE).

The building blocks

Kind Examples Meaning
Boolean conditions
lt;CONFIG:Debug,RelWithDebInfo>
,
lt;PLATFORM_ID:Linux>
,
lt;CXX_COMPILER_ID:GNU,Clang>
,
lt;COMPILE_LANGUAGE:CXX>
,
lt;BOOL:${var}>
evaluate to 1 or 0
Logic
lt;AND:…>
,
lt;OR:…>
,
lt;NOT:…>
,
lt;IF:cond,a,b>
combine conditions
Conditional value
lt;cond:value>
value if cond is 1, else empty
Target queries
lt;TARGET_FILE:t>
,
lt;TARGET_FILE_DIR:t>
,
lt;TARGET_LINKER_FILE:t>
,
lt;TARGET_PROPERTY:t,PROP>
,
lt;TARGET_EXISTS:t>
paths and properties known only at generate time
Output context
lt;BUILD_INTERFACE:…>
,
lt;INSTALL_INTERFACE:…>
,
lt;LINK_ONLY:…>
which side of an export
Strings
lt;LOWER_CASE:…>
,
lt;JOIN:list,sep>
,
lt;LIST:…>
(3.27+),
lt;PATH:…>
(3.24+)
text manipulation

Common patterns

cmake
# Per-configuration definitions and flags
target_compile_definitions(app PRIVATE 
lt;
lt;CONFIG:Debug>:APP_TRACE=1>) # Compiler-specific warnings (a list inside a genex: wrap it in quotes or use ;) target_compile_options(app PRIVATE "
lt;
lt;CXX_COMPILER_ID:GNU,Clang>:-Wall;-Wextra>"
lt;
lt;CXX_COMPILER_ID:MSVC>:/W4>) # Only for C++ sources in a mixed C/C++ target target_compile_options(app PRIVATE
lt;
lt;COMPILE_LANGUAGE:CXX>:-fno-exceptions>) # Path to a built tool, in a custom command or test (also adds a dependency) add_test(NAME runs COMMAND
lt;TARGET_FILE:app> --selftest)

A runnable model of the evaluator

Generator expressions are a small functional language: evaluate the innermost

lt;…> first, then the enclosing one. This model implements a handful of expressions; edit the context or the inputs and run it:

js · try it yourself
function evaluate(text, ctx) {
  // Repeatedly replace an innermost 
lt;...> (one without nested
lt;) until none are left. const inner = /\
lt;([^
lt;>]*)>/; let m; while ((m = text.match(inner))) { const [name, ...rest] = m[1].split(':'); const arg = rest.join(':'); let out; if (name === 'CONFIG') out = arg === '' ? ctx.config : String(+arg.split(',').includes(ctx.config)); else if (name === 'CXX_COMPILER_ID') out = arg === '' ? ctx.compiler : String(+arg.split(',').includes(ctx.compiler)); else if (name === 'NOT') out = arg === '1' ? '0' : '1'; else if (name === 'AND') out = String(+arg.split(',').every((x) => x === '1')); else if (name === 'IF') { const [c, a, b] = arg.split(','); out = c === '1' ? a : b; } else if (name === '1') out = arg; //
lt;1:value> else if (name === '0') out = ''; //
lt;0:value> else out = `<unknown ${name}>`; text = text.replace(m[0], out); } return text; } const inputs = [ '
lt;
lt;CONFIG:Debug>:APP_TRACE=1>', '
lt;IF:
lt;CONFIG:Debug>,-O0,-O2>', '
lt;
lt;AND:
lt;CXX_COMPILER_ID:GNU,Clang>,
lt;NOT:
lt;CONFIG:Debug>>>:-flto>', ]; for (const config of ['Debug', 'Release']) { const ctx = { config, compiler: 'GNU' }; console.log(`[${config}]`); for (const g of inputs) console.log(` ${g}\n -> "${evaluate(g, ctx)}"`); }
[Debug]
  
lt;
lt;CONFIG:Debug>:APP_TRACE=1> -> "APP_TRACE=1"
lt;IF:
lt;CONFIG:Debug>,-O0,-O2> -> "-O0"
lt;
lt;AND:
lt;CXX_COMPILER_ID:GNU,Clang>,
lt;NOT:
lt;CONFIG:Debug>>>:-flto> -> "" [Release]
lt;
lt;CONFIG:Debug>:APP_TRACE=1> -> ""
lt;IF:
lt;CONFIG:Debug>,-O0,-O2> -> "-O2"
lt;
lt;AND:
lt;CXX_COMPILER_ID:GNU,Clang>,
lt;NOT:
lt;CONFIG:Debug>>>:-flto> -> "-flto"

Debugging tips

  • Build a genex step by step, checking each piece with file(GENERATE).
  • An empty result is common and usually what you want (
    lt;
    lt;CONFIG:Debug>:X>
    in Release produces nothing, and CMake drops empty list items).
  • A genex that contains a ; list or spaces must be quoted as a whole, or CMake splits it into several broken arguments before it is ever evaluated.
  • Don't use if(CMAKE_BUILD_TYPE …) for per-configuration logic; it can't see multi-config builds (see Build Types).

Test yourself

Why does message("

lt;CONFIG>") print
lt;CONFIG>
literally?

  1. message() escapes dollar signs
  2. Generator expressions are evaluated at generate time, after CMakeLists.txt has run
  3. lt;CONFIG> is only valid on Windows
  4. It needs quotes

What does

lt;
lt;CONFIG:Debug>:APP_TRACE>
produce in a Release build?

  1. APP_TRACE
  2. 0
  3. An empty string
  4. An error

Which genex gives the full path of a target's built file?

  1. lt;TARGET_NAME:t>
  2. lt;TARGET_FILE:t>
  3. ${t_LOCATION}
  4. lt;TARGET_PROPERTY:t,SOURCES>