skip to content

In CMake, how does cmake_parse_arguments give a helper like engine_add_library(core TYPE STATIC SOURCES a.cpp) keyword arguments?

level: middleimportance: should knowfreq 44%

answer

  1. options, one-value, multi-value
  2. prefix_KEYWORD result variables
  3. options are always TRUE or FALSE
  4. UNPARSED and KEYWORDS_MISSING_VALUES
  5. PARSE_ARGV keeps semicolons

basics

~10 s

cmake_parse_arguments sorts the call's arguments into option, one-value and multi-value keywords and sets prefix_KEYWORD variables. Leftovers go to prefix_UNPARSED_ARGUMENTS and keywords given no value to prefix_KEYWORDS_MISSING_VALUES, which the helper should reject.

solid answer

~40 s

Inside `function(engine_add_library name)`, call `cmake_parse_arguments(PARSE_ARGV 1 arg "WARNINGS_AS_ERRORS" "TYPE" "SOURCES;DEPS")`. It parses the arguments from index 1 on and sets `arg_WARNINGS_AS_ERRORS` to `TRUE` or `FALSE`, `arg_TYPE` to one value, and `arg_SOURCES` and `arg_DEPS` to lists. One- and multi-value variables are **undefined** when their keyword is absent, so defaults use `if(NOT DEFINED arg_TYPE)`. Arguments that arrive while no keyword is collecting values land in `arg_UNPARSED_ARGUMENTS`; a keyword followed by no value is listed in `arg_KEYWORDS_MISSING_VALUES` (CMake 3.15). Check both with `if(DEFINED ...)` and fail with `message(FATAL_ERROR)`. The catch: a misspelt keyword after a multi-value keyword is swallowed into that list, not reported. `PARSE_ARGV` also keeps a value containing `;` as one element; CMake 4.4 adds `PARSE_ARGN`.

code

cmake · 21 lines
cmake
function(engine_add_library name)
  cmake_parse_arguments(PARSE_ARGV 1 arg
    "WARNINGS_AS_ERRORS"   # options
    "TYPE"                 # one-value keywords
    "SOURCES;DEPS")        # multi-value keywords
  if(DEFINED arg_UNPARSED_ARGUMENTS OR DEFINED arg_KEYWORDS_MISSING_VALUES)
    message(FATAL_ERROR "engine_add_library(${name}): bad arguments "
      "'${arg_UNPARSED_ARGUMENTS}' / missing '${arg_KEYWORDS_MISSING_VALUES}'")
  endif()
  if(NOT DEFINED arg_TYPE)
    set(arg_TYPE STATIC)
  endif()
  add_library(${name} ${arg_TYPE} ${arg_SOURCES})
  target_compile_features(${name} PUBLIC cxx_std_20)
  target_link_libraries(${name} PRIVATE ${arg_DEPS})
  if(arg_WARNINGS_AS_ERRORS)
    set_property(TARGET ${name} PROPERTY COMPILE_WARNING_AS_ERROR ON)
  endif()
endfunction()

engine_add_library(core SOURCES src/core.cpp WARNINGS_AS_ERRORS)

go deeper

for a junior

Recall that cmake_parse_arguments turns keyword arguments into prefix_KEYWORD variables inside a helper.

for a middle

Explain options versus one- and multi-value keywords, which results are undefined when absent, and how to validate the call.

for a senior

Catch the swallowed-typo trap, choose PARSE_ARGV over ${ARGN} for semicolon safety, and make helpers fail loudly on bad calls.

for a principal

Decide how much logic shared helpers should own, since every wrapper is an internal API that every target in the repository depends on.

## Why a wrapper needs keyword arguments CMake commands take keyword arguments, such as `install(TARGETS ... DESTINATION ...)`. A project helper that wraps `add_library()` with the team's common settings should read the same way, with optional parts in any order, rather than depending on positional `ARGV2`, `ARGV3` and so on. `cmake_parse_arguments` is the built-in parser; it has been a native command since CMake 3.5. ## The three keyword kinds ```cmake cmake_parse_arguments(PARSE_ARGV <N> <prefix> <options> <one_value_keywords> <multi_value_keywords>) ``` | Kind | Example | Result variable when present | When absent | |---|---|---|---| | Option | `WARNINGS_AS_ERRORS` | `arg_WARNINGS_AS_ERRORS` = `TRUE` | defined, `FALSE` | | One-value | `TYPE STATIC` | `arg_TYPE` = `STATIC` | undefined | | Multi-value | `SOURCES a.cpp b.cpp` | `arg_SOURCES` = `a.cpp;b.cpp` | undefined | Each result variable is named `<prefix>_<KEYWORD>`. Two extra variables report problems: - `<prefix>_UNPARSED_ARGUMENTS` holds the remaining arguments that no keyword consumed, and is undefined when there were none. - `<prefix>_KEYWORDS_MISSING_VALUES` (CMake 3.15) lists one- or multi-value keywords that received no value. A keyword ends the previous keyword's value list. That is how `RENAME FAST` in the documentation's example leaves `RENAME` empty and records it as missing. ## The trap: misspelt keywords disappear into lists Because only a known keyword ends a multi-value list, a typo after one is treated as more values: ```plaintext engine_add_library(audio SOURCES mix.cpp DEP fmt) # arg_SOURCES = mix.cpp;DEP;fmt arg_DEPS undefined arg_UNPARSED_ARGUMENTS undefined ``` CMake 4.4.4 parsed it exactly like that, with nothing reported. The mistake surfaces later, when `add_library()` cannot find a source file called `DEP`. `UNPARSED_ARGUMENTS` catches typos only where no multi-value keyword is open, for instance a stray word right after the name. When `add_library()` reports that it cannot find a source file named like a keyword, suspect this trap first. ## Validating the call Check both diagnostics with `DEFINED`, not with a truth test: an unparsed argument that happens to be `OFF` or `0` would make `if(arg_UNPARSED_ARGUMENTS)` false. ```cmake if(DEFINED arg_UNPARSED_ARGUMENTS OR DEFINED arg_KEYWORDS_MISSING_VALUES) message(FATAL_ERROR "engine_add_library(${name}): bad arguments ...") endif() ``` Calling `engine_add_library(audio TYPE SOURCES src/mix.cpp)` then stops the configure with `missing 'TYPE'`, pointing at the caller's line in the call stack. ## PARSE_ARGV versus ${ARGN} The older form passes the arguments explicitly: `cmake_parse_arguments(arg "..." "..." "..." ${ARGN})`. It works in macros and functions, but expanding `${ARGN}` re-splits any value that contained an escaped semicolon. The `PARSE_ARGV <N>` form (CMake 3.7, functions only) reads the `ARGV#` variables directly, starting at index `<N>`, so such values survive. In a CMake 4.4.4 run, `DEFS "LIST=a\;b" C=2` gave three elements through `${ARGN}` and two through `PARSE_ARGV 0`. CMake 4.4 adds `PARSE_ARGN`, which starts after the function's last named parameter, so the index no longer has to be kept in step with the signature. ## Lists are strings, and quoting decides the argument count Every result variable holding several values is a **list**: one string with `;` between elements. `list()` and `string()` operate on that string: - `list(APPEND arg_SOURCES extra.cpp)`, `list(LENGTH arg_SOURCES n)`, `list(REMOVE_DUPLICATES arg_DEPS)` edit or inspect it. - `string(REPLACE ";" ", " pretty "${arg_SOURCES}")` turns it into readable text for a message. How you expand it decides how many arguments a command receives. In a CMake 4.4.4 run, a function called with `${flags}` (where `flags` held `-Wall;-Wextra`) saw `ARGC=2`; called with `"${flags}"` it saw `ARGC=1`. Forward lists unquoted when each element should be its own argument, and quote them when the whole list is one value. ## Prefix and scope - In a **function**, the result variables live in the function's scope, so a short prefix such as `arg` is conventional. - In a **macro**, they are set in the caller's scope, so two macros using the same prefix and keywords overwrite each other; the documentation recommends a prefix built from the macro's name. ## Defaults and forwarding 1. Give one-value keywords defaults with `if(NOT DEFINED arg_TYPE)` then `set(arg_TYPE STATIC)`. 2. Forward lists unquoted, `add_library(${name} ${arg_TYPE} ${arg_SOURCES})`, so each element becomes its own argument. 3. Act on options with a truth test, `if(arg_WARNINGS_AS_ERRORS)`, since they are always defined.

  • Why does a misspelt keyword not show up in UNPARSED_ARGUMENTS?
    Only a recognised keyword ends a multi-value list, so an unknown word after `SOURCES` is just another source. `UNPARSED_ARGUMENTS` collects only arguments that arrive while no keyword is open, such as a stray word straight after the target name. The typo surfaces later, typically when `add_library()` cannot find a file named after it.
  • When must you use the ${ARGN} form instead of PARSE_ARGV?
    In a `macro()`, because `PARSE_ARGV` reads the `ARGV#` variables that exist only in a function's scope. The macro form passes `${ARGN}` explicitly, which re-splits values containing escaped semicolons, and its result variables land in the caller's scope, so the prefix should include the macro's name.

  • Expects a misspelt keyword to land in UNPARSED_ARGUMENTS
  • Tests an absent one-value keyword with if(arg_TYPE STREQUAL "") instead of DEFINED
  • Thinks an omitted option keyword leaves its variable undefined
  • Uses PARSE_ARGV inside a macro
  • Gives two macros the same prefix and keyword names

Assumes CMake 4.x: PARSE_ARGV dates from 3.7, KEYWORDS_MISSING_VALUES from 3.15, and the PARSE_ARGN signature was added in CMake 4.4.