The CMake Language
CMakeLists.txt is a program in a small scripting language. It is easy to read once you know its one big rule: everything is a string. A command takes a list of string arguments, variables hold strings, and a list is just a string with ; between the items.
You can run CMake code without a project in script mode: cmake -P file.cmake. All examples in this lesson do that.
Commands and arguments
A command is a name followed by arguments in parentheses, separated by whitespace. Command names are case-insensitive (message, MESSAGE), variable names are case-sensitive.
cat > demo.cmake <<'CM'
set(name "Ada") # a variable
message("Hello ${name}") # ${...} expands it
message(Hello ${name}) # unquoted: two arguments, joined without a space
set(empty "")
message("[${empty}] [${undefined}]") # undefined variables expand to nothing
set(path "C:/Program Files")
message("quoted: ${path}")
message([[raw: ${name} is not expanded]])
CM
cmake -P demo.cmakeHello Ada
HelloAda
[] []
quoted: C:/Program Files
raw: ${name} is not expanded
Note the second message: without quotes, Hello and Ada are two arguments and message concatenates them. Quote arguments that might contain spaces or semicolons.
Lists
A list is a ;-separated string. Unquoted, a list variable expands into several arguments; quoted, it stays one argument:
cat > lists.cmake <<'CM'
set(srcs main.cpp util.cpp io.cpp) # stored as "main.cpp;util.cpp;io.cpp"
message("srcs = ${srcs}")
list(LENGTH srcs n)
message("length = ${n}")
list(APPEND srcs net.cpp)
list(REMOVE_ITEM srcs io.cpp)
list(SORT srcs)
list(JOIN srcs ", " joined)
message("sorted = ${joined}")
list(TRANSFORM srcs PREPEND "src/" OUTPUT_VARIABLE full)
message("full = ${full}")
list(FIND srcs util.cpp idx)
message("util.cpp is at index ${idx}")
foreach(f IN LISTS srcs)
get_filename_component(stem ${f} NAME_WE)
message(" ${f} -> ${stem}.o")
endforeach()
CM
cmake -P lists.cmakesrcs = main.cpp;util.cpp;io.cpp
length = 3
sorted = main.cpp, net.cpp, util.cpp
full = src/main.cpp;src/net.cpp;src/util.cpp
util.cpp is at index 2
main.cpp -> main.o
net.cpp -> net.o
util.cpp -> util.o
Conditions
if() has its own little language. Its strangest rule: an unquoted word that is the name of a variable is replaced by its value. That is why you write if(enabled), not if(${enabled}).
cat > cond.cmake <<'CM'
set(level 3)
set(flag ON)
set(build_type "Release")
if(flag) # true for ON, YES, TRUE, Y, non-zero numbers
message("flag is on")
endif()
if(level GREATER 2 AND NOT build_type STREQUAL "Debug")
message("level > 2 in a non-debug build")
endif()
if(DEFINED missing)
message("missing is defined")
else()
message("missing is not defined")
endif()
if("4.4.4" VERSION_GREATER_EQUAL "3.25")
message("version comparison works on dotted numbers")
endif()
if("libfoo.so" MATCHES "^lib(.*)\\.soquot;)
message("regex capture: ${CMAKE_MATCH_1}")
endif()
foreach(v IN ITEMS ON OFF 0 1 NO "" NOTFOUND foo-NOTFOUND)
if(v)
message("'${v}' is true")
else()
message("'${v}' is false")
endif()
endforeach()
CM
cmake -P cond.cmakeflag is on
level > 2 in a non-debug build
missing is not defined
version comparison works on dotted numbers
regex capture: foo
'ON' is true
'OFF' is false
'0' is false
'1' is true
'NO' is false
'' is false
'NOTFOUND' is false
'foo-NOTFOUND' is false
The false constants are 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, and anything ending in -NOTFOUND. That last rule is what makes if(FOO_LIBRARY) work after a failed find_library. (Inside a foreach the loop variable is a real variable, so if(v) tests its value.)
Strings and math
cat > str.cmake <<'CM'
set(version "4.4.4")
string(REPLACE "." ";" parts "${version}")
list(GET parts 0 major)
math(EXPR next "${major} + 1")
message("major ${major}, next major ${next}")
string(TOUPPER "release" up)
string(LENGTH "${up}" len)
message("${up} has ${len} characters")
string(REGEX REPLACE "([a-z]+)-([0-9]+)" "\\2-\\1" swapped "build-42")
message("swapped: ${swapped}")
string(SHA256 digest "hello")
string(SUBSTRING "${digest}" 0 12 short)
message("sha256(hello) starts with ${short}")
string(JSON city GET [[{"office": {"city": "Hanoi"}}]] office city)
message("city from JSON: ${city}")
CM
cmake -P str.cmakemajor 4, next major 5
RELEASE has 7 characters
swapped: 42-build
sha256(hello) starts with 2cf24dba5fb0
city from JSON: Hanoi
message() levels
message() takes an optional mode. It controls where the text goes and whether the configure fails:
| Mode | Effect |
|---|---|
(none) / NOTICE |
printed to stderr |
STATUS |
printed with -- (hidden by --log-level=NOTICE) |
VERBOSE, DEBUG, TRACE |
only with --log-level=VERBOSE (etc.) |
WARNING / AUTHOR_WARNING / DEPRECATION |
a warning with the file and line |
SEND_ERROR |
an error; processing continues but nothing is generated |
FATAL_ERROR |
an error; processing stops immediately |
CHECK_START / CHECK_PASS / CHECK_FAIL |
the "Looking for X - found" style |
cat > msg.cmake <<'CM'
message(STATUS "a status line")
message(VERBOSE "only shown with --log-level=VERBOSE")
message(WARNING "something looks odd")
message(FATAL_ERROR "stopping here")
message("never printed")
CM
cmake -P msg.cmake
echo "exit code: $?"-- a status line
CMake Warning at msg.cmake:3 (message):
something looks odd
CMake Error at msg.cmake:4 (message):
stopping here
exit code: 1
A runnable model of list expansion
The "unquoted lists become several arguments" rule causes many bugs. This model splits a command line the way CMake does (simplified: no escapes, no nested brackets):
function expand(argText, vars) {
const args = [];
// Quoted arguments stay one argument; unquoted ones are split on ';' after expansion.
for (const m of argText.matchAll(/"([^"]*)"|(\S+)/g)) {
const quoted = m[1] !== undefined;
const text = (quoted ? m[1] : m[2]).replace(/\$\{(\w+)\}/g, (_, v) => vars[v] ?? '');
if (quoted) args.push(text);
else args.push(...text.split(';').filter((s) => s !== ''));
}
return args;
}
const vars = { srcs: 'a.cpp;b.cpp', empty: '' };
for (const call of ['${srcs}', '"${srcs}"', 'x ${empty} y', 'x "${empty}" y']) {
console.log(call.padEnd(16), '->', JSON.stringify(expand(call, vars)));
}${srcs} -> ["a.cpp","b.cpp"]
"${srcs}" -> ["a.cpp;b.cpp"]
x ${empty} y -> ["x","y"]
x "${empty}" y -> ["x","","y"]
Unquoted, an empty variable disappears from the argument list; quoted, it stays as an empty argument. This is why if(${var} STREQUAL "x") breaks when var is empty, and why if(var STREQUAL "x") is correct.
Test yourself
set(srcs a.cpp b.cpp). How is srcs stored?
- As two variables
- As the string
a.cpp;b.cpp - As
a.cpp b.cpp - As an array object
Which of these values is false in if()?
ON1foo-NOTFOUNDYES
What does message(SEND_ERROR ...) do compared to FATAL_ERROR?
- Nothing different
- It reports an error but keeps processing (no build files are generated); FATAL_ERROR stops immediately
- It only warns
- It sends an e-mail