1CMAKE-LANGUAGE(7) CMake CMAKE-LANGUAGE(7)
2
3
4
6 cmake-language - CMake Language Reference
7
9 CMake input files are written in the "CMake Language" in source files
10 named CMakeLists.txt or ending in a .cmake file name extension.
11
12 CMake Language source files in a project are organized into:
13
14 • Directories (CMakeLists.txt),
15
16 • Scripts (<script>.cmake), and
17
18 • Modules (<module>.cmake).
19
20 Directories
21 When CMake processes a project source tree, the entry point is a source
22 file called CMakeLists.txt in the top-level source directory. This
23 file may contain the entire build specification or use the
24 add_subdirectory() command to add subdirectories to the build. Each
25 subdirectory added by the command must also contain a CMakeLists.txt
26 file as the entry point to that directory. For each source directory
27 whose CMakeLists.txt file is processed CMake generates a corresponding
28 directory in the build tree to act as the default working and output
29 directory.
30
31 Scripts
32 An individual <script>.cmake source file may be processed in script
33 mode by using the cmake(1) command-line tool with the -P option.
34 Script mode simply runs the commands in the given CMake Language source
35 file and does not generate a build system. It does not allow CMake
36 commands that define build targets or actions.
37
38 Modules
39 CMake Language code in either Directories or Scripts may use the
40 include() command to load a <module>.cmake source file in the scope of
41 the including context. See the cmake-modules(7) manual page for docu‐
42 mentation of modules included with the CMake distribution. Project
43 source trees may also provide their own modules and specify their loca‐
44 tion(s) in the CMAKE_MODULE_PATH variable.
45
47 Encoding
48 A CMake Language source file may be written in 7-bit ASCII text for
49 maximum portability across all supported platforms. Newlines may be
50 encoded as either \n or \r\n but will be converted to \n as input files
51 are read.
52
53 Note that the implementation is 8-bit clean so source files may be en‐
54 coded as UTF-8 on platforms with system APIs supporting this encoding.
55 In addition, CMake 3.2 and above support source files encoded in UTF-8
56 on Windows (using UTF-16 to call system APIs). Furthermore, CMake 3.0
57 and above allow a leading UTF-8 Byte-Order Mark in source files.
58
59 Source Files
60 A CMake Language source file consists of zero or more Command Invoca‐
61 tions separated by newlines and optionally spaces and Comments:
62
63 file ::= file_element*
64 file_element ::= command_invocation line_ending |
65 (bracket_comment|space)* line_ending
66 line_ending ::= line_comment? newline
67 space ::= <match '[ \t]+'>
68 newline ::= <match '\n'>
69
70
71 Note that any source file line not inside Command Arguments or a
72 Bracket Comment can end in a Line Comment.
73
74 Command Invocations
75 A command invocation is a name followed by paren-enclosed arguments
76 separated by whitespace:
77
78 command_invocation ::= space* identifier space* '(' arguments ')'
79 identifier ::= <match '[A-Za-z_][A-Za-z0-9_]*'>
80 arguments ::= argument? separated_arguments*
81 separated_arguments ::= separation+ argument? |
82 separation* '(' arguments ')'
83 separation ::= space | line_ending
84
85
86 For example:
87
88 add_executable(hello world.c)
89
90 Command names are case-insensitive. Nested unquoted parentheses in the
91 arguments must balance. Each ( or ) is given to the command invocation
92 as a literal Unquoted Argument. This may be used in calls to the if()
93 command to enclose conditions. For example:
94
95 if(FALSE AND (FALSE OR TRUE)) # evaluates to FALSE
96
97 NOTE:
98 CMake versions prior to 3.0 require command name identifiers to be
99 at least 2 characters.
100
101 CMake versions prior to 2.8.12 silently accept an Unquoted Argument
102 or a Quoted Argument immediately following a Quoted Argument and not
103 separated by any whitespace. For compatibility, CMake 2.8.12 and
104 higher accept such code but produce a warning.
105
106 Command Arguments
107 There are three types of arguments within Command Invocations:
108
109 argument ::= bracket_argument | quoted_argument | unquoted_argument
110
111
112 Bracket Argument
113 A bracket argument, inspired by Lua long bracket syntax, encloses con‐
114 tent between opening and closing "brackets" of the same length:
115
116 bracket_argument ::= bracket_open bracket_content bracket_close
117 bracket_open ::= '[' '='* '['
118 bracket_content ::= <any text not containing a bracket_close with
119 the same number of '=' as the bracket_open>
120 bracket_close ::= ']' '='* ']'
121
122
123 An opening bracket is written [ followed by zero or more = followed by
124 [. The corresponding closing bracket is written ] followed by the same
125 number of = followed by ]. Brackets do not nest. A unique length may
126 always be chosen for the opening and closing brackets to contain clos‐
127 ing brackets of other lengths.
128
129 Bracket argument content consists of all text between the opening and
130 closing brackets, except that one newline immediately following the
131 opening bracket, if any, is ignored. No evaluation of the enclosed
132 content, such as Escape Sequences or Variable References, is performed.
133 A bracket argument is always given to the command invocation as exactly
134 one argument.
135
136 For example:
137
138 message([=[
139 This is the first line in a bracket argument with bracket length 1.
140 No \-escape sequences or ${variable} references are evaluated.
141 This is always one argument even though it contains a ; character.
142 The text does not end on a closing bracket of length 0 like ]].
143 It does end in a closing bracket of length 1.
144 ]=])
145
146 NOTE:
147 CMake versions prior to 3.0 do not support bracket arguments. They
148 interpret the opening bracket as the start of an Unquoted Argument.
149
150 Quoted Argument
151 A quoted argument encloses content between opening and closing dou‐
152 ble-quote characters:
153
154 quoted_argument ::= '"' quoted_element* '"'
155 quoted_element ::= <any character except '\' or '"'> |
156 escape_sequence |
157 quoted_continuation
158 quoted_continuation ::= '\' newline
159
160
161 Quoted argument content consists of all text between opening and clos‐
162 ing quotes. Both Escape Sequences and Variable References are evalu‐
163 ated. A quoted argument is always given to the command invocation as
164 exactly one argument.
165
166 For example:
167
168 message("This is a quoted argument containing multiple lines.
169 This is always one argument even though it contains a ; character.
170 Both \\-escape sequences and ${variable} references are evaluated.
171 The text does not end on an escaped double-quote like \".
172 It does end in an unescaped double quote.
173 ")
174
175 The final \ on any line ending in an odd number of backslashes is
176 treated as a line continuation and ignored along with the immediately
177 following newline character. For example:
178
179 message("\
180 This is the first line of a quoted argument. \
181 In fact it is the only line but since it is long \
182 the source code uses line continuation.\
183 ")
184
185 NOTE:
186 CMake versions prior to 3.0 do not support continuation with \.
187 They report errors in quoted arguments containing lines ending in an
188 odd number of \ characters.
189
190 Unquoted Argument
191 An unquoted argument is not enclosed by any quoting syntax. It may not
192 contain any whitespace, (, ), #, ", or \ except when escaped by a back‐
193 slash:
194
195 unquoted_argument ::= unquoted_element+ | unquoted_legacy
196 unquoted_element ::= <any character except whitespace or one of '()#"\'> |
197 escape_sequence
198 unquoted_legacy ::= <see note in text>
199
200
201 Unquoted argument content consists of all text in a contiguous block of
202 allowed or escaped characters. Both Escape Sequences and Variable Ref‐
203 erences are evaluated. The resulting value is divided in the same way
204 Lists divide into elements. Each non-empty element is given to the
205 command invocation as an argument. Therefore an unquoted argument may
206 be given to a command invocation as zero or more arguments.
207
208 For example:
209
210 foreach(arg
211 NoSpace
212 Escaped\ Space
213 This;Divides;Into;Five;Arguments
214 Escaped\;Semicolon
215 )
216 message("${arg}")
217 endforeach()
218
219 NOTE:
220 To support legacy CMake code, unquoted arguments may also contain
221 double-quoted strings ("...", possibly enclosing horizontal white‐
222 space), and make-style variable references ($(MAKEVAR)).
223
224 Unescaped double-quotes must balance, may not appear at the begin‐
225 ning of an unquoted argument, and are treated as part of the con‐
226 tent. For example, the unquoted arguments -Da="b c", -Da=$(v), and
227 a" "b"c"d are each interpreted literally. They may instead be writ‐
228 ten as quoted arguments "-Da=\"b c\"", "-Da=$(v)", and "a\"
229 \"b\"c\"d", respectively.
230
231 Make-style references are treated literally as part of the content
232 and do not undergo variable expansion. They are treated as part of
233 a single argument (rather than as separate $, (, MAKEVAR, and ) ar‐
234 guments).
235
236 The above "unquoted_legacy" production represents such arguments.
237 We do not recommend using legacy unquoted arguments in new code.
238 Instead use a Quoted Argument or a Bracket Argument to represent the
239 content.
240
241 Escape Sequences
242 An escape sequence is a \ followed by one character:
243
244 escape_sequence ::= escape_identity | escape_encoded | escape_semicolon
245 escape_identity ::= '\' <match '[^A-Za-z0-9;]'>
246 escape_encoded ::= '\t' | '\r' | '\n'
247 escape_semicolon ::= '\;'
248
249
250 A \ followed by a non-alphanumeric character simply encodes the literal
251 character without interpreting it as syntax. A \t, \r, or \n encodes a
252 tab, carriage return, or newline character, respectively. A \; outside
253 of any Variable References encodes itself but may be used in an
254 Unquoted Argument to encode the ; without dividing the argument value
255 on it. A \; inside Variable References encodes the literal ; charac‐
256 ter. (See also policy CMP0053 documentation for historical considera‐
257 tions.)
258
259 Variable References
260 A variable reference has the form ${<variable>} and is evaluated inside
261 a Quoted Argument or an Unquoted Argument. A variable reference is re‐
262 placed by the value of the specified variable or cache entry, or if
263 neither is set, by the empty string. Variable references can nest and
264 are evaluated from the inside out, e.g. ${outer_${inner_variable}_vari‐
265 able}.
266
267 Literal variable references may consist of alphanumeric characters, the
268 characters /_.+-, and Escape Sequences. Nested references may be used
269 to evaluate variables of any name. See also policy CMP0053 documenta‐
270 tion for historical considerations and reasons why the $ is also tech‐
271 nically permitted but is discouraged.
272
273 The Variables section documents the scope of variable names and how
274 their values are set.
275
276 An environment variable reference has the form $ENV{<variable>}. See
277 the Environment Variables section for more information.
278
279 A cache variable reference has the form $CACHE{<variable>}, and is re‐
280 placed by the value of the specified cache entry without checking for a
281 normal variable of the same name. If the cache entry does not exist,
282 it is replaced by the empty string. See CACHE for more information.
283
284 The if() command has a special condition syntax that allows for vari‐
285 able references in the short form <variable> instead of ${<variable>}.
286 However, environment variables always need to be referenced as
287 $ENV{<variable>}.
288
289 Comments
290 A comment starts with a # character that is not inside a Bracket Argu‐
291 ment, Quoted Argument, or escaped with \ as part of an Unquoted Argu‐
292 ment. There are two types of comments: a Bracket Comment and a Line
293 Comment.
294
295 Bracket Comment
296 A # immediately followed by a bracket_open forms a bracket comment con‐
297 sisting of the entire bracket enclosure:
298
299 bracket_comment ::= '#' bracket_argument
300
301
302 For example:
303
304 #[[This is a bracket comment.
305 It runs until the close bracket.]]
306 message("First Argument\n" #[[Bracket Comment]] "Second Argument")
307
308 NOTE:
309 CMake versions prior to 3.0 do not support bracket comments. They
310 interpret the opening # as the start of a Line Comment.
311
312 Line Comment
313 A # not immediately followed by a bracket_open forms a line comment
314 that runs until the end of the line:
315
316 line_comment ::= '#' <any text not starting in a bracket_open
317 and not containing a newline>
318
319
320 For example:
321
322 # This is a line comment.
323 message("First Argument\n" # This is a line comment :)
324 "Second Argument") # This is a line comment.
325
327 Conditional Blocks
328 The if()/elseif()/else()/endif() commands delimit code blocks to be ex‐
329 ecuted conditionally.
330
331 Loops
332 The foreach()/endforeach() and while()/endwhile() commands delimit code
333 blocks to be executed in a loop. Inside such blocks the break() com‐
334 mand may be used to terminate the loop early whereas the continue()
335 command may be used to start with the next iteration immediately.
336
337 Command Definitions
338 The macro()/endmacro(), and function()/endfunction() commands delimit
339 code blocks to be recorded for later invocation as commands.
340
342 Variables are the basic unit of storage in the CMake Language. Their
343 values are always of string type, though some commands may interpret
344 the strings as values of other types. The set() and unset() commands
345 explicitly set or unset a variable, but other commands have semantics
346 that modify variables as well. Variable names are case-sensitive and
347 may consist of almost any text, but we recommend sticking to names con‐
348 sisting only of alphanumeric characters plus _ and -.
349
350 Variables have dynamic scope. Each variable "set" or "unset" creates a
351 binding in the current scope:
352
353 Block Scope
354 The block() command may create a new scope for variable bind‐
355 ings.
356
357 Function Scope
358 Command Definitions created by the function() command create
359 commands that, when invoked, process the recorded commands in a
360 new variable binding scope. A variable "set" or "unset" binds
361 in this scope and is visible for the current function and any
362 nested calls within it, but not after the function returns.
363
364 Directory Scope
365 Each of the Directories in a source tree has its own variable
366 bindings. Before processing the CMakeLists.txt file for a di‐
367 rectory, CMake copies all variable bindings currently defined in
368 the parent directory, if any, to initialize the new directory
369 scope. CMake Scripts, when processed with cmake -P, bind vari‐
370 ables in one "directory" scope.
371
372 A variable "set" or "unset" not inside a function call binds to
373 the current directory scope.
374
375 Persistent Cache
376 CMake stores a separate set of "cache" variables, or "cache en‐
377 tries", whose values persist across multiple runs within a
378 project build tree. Cache entries have an isolated binding
379 scope modified only by explicit request, such as by the CACHE
380 option of the set() and unset() commands.
381
382 When evaluating Variable References, CMake first searches the function
383 call stack, if any, for a binding and then falls back to the binding in
384 the current directory scope, if any. If a "set" binding is found, its
385 value is used. If an "unset" binding is found, or no binding is found,
386 CMake then searches for a cache entry. If a cache entry is found, its
387 value is used. Otherwise, the variable reference evaluates to an empty
388 string. The $CACHE{VAR} syntax can be used to do direct cache entry
389 lookups.
390
391 The cmake-variables(7) manual documents the many variables that are
392 provided by CMake or have meaning to CMake when set by project code.
393
394 NOTE:
395 CMake reserves identifiers that:
396
397 • begin with CMAKE_ (upper-, lower-, or mixed-case), or
398
399 • begin with _CMAKE_ (upper-, lower-, or mixed-case), or
400
401 • begin with _ followed by the name of any CMake Command.
402
404 Environment Variables are like ordinary Variables, with the following
405 differences:
406
407 Scope Environment variables have global scope in a CMake process.
408 They are never cached.
409
410 References
411 Variable References have the form $ENV{<variable>}, using the
412 ENV operator.
413
414 Initialization
415 Initial values of the CMake environment variables are those of
416 the calling process. Values can be changed using the set() and
417 unset() commands. These commands only affect the running CMake
418 process, not the system environment at large. Changed values
419 are not written back to the calling process, and they are not
420 seen by subsequent build or test processes.
421
422 See the cmake -E env command-line tool to run a command in a
423 modified environment.
424
425 Inspection
426 See the cmake -E environment command-line tool to display all
427 current environment variables.
428
429 The cmake-env-variables(7) manual documents environment variables that
430 have special meaning to CMake.
431
433 Although all values in CMake are stored as strings, a string may be
434 treated as a list in certain contexts, such as during evaluation of an
435 Unquoted Argument. In such contexts, a string is divided into list el‐
436 ements by splitting on ; characters not following an unequal number of
437 [ and ] characters and not immediately preceded by a \. The sequence
438 \; does not divide a value but is replaced by ; in the resulting ele‐
439 ment.
440
441 A list of elements is represented as a string by concatenating the ele‐
442 ments separated by ;. For example, the set() command stores multiple
443 values into the destination variable as a list:
444
445 set(srcs a.c b.c c.c) # sets "srcs" to "a.c;b.c;c.c"
446
447 Lists are meant for simple use cases such as a list of source files and
448 should not be used for complex data processing tasks. Most commands
449 that construct lists do not escape ; characters in list elements, thus
450 flattening nested lists:
451
452 set(x a "b;c") # sets "x" to "a;b;c", not "a;b\;c"
453
454 In general, lists do not support elements containing ; characters. To
455 avoid problems, consider the following advice:
456
457 • The interfaces of many CMake commands, variables, and properties ac‐
458 cept semicolon-separated lists. Avoid passing lists with elements
459 containing semicolons to these interfaces unless they document either
460 direct support or some way to escape or encode semicolons.
461
462 • When constructing a list, substitute an otherwise-unused placeholder
463 for ; in elements when. Then substitute ; for the placeholder when
464 processing list elements. For example, the following code uses | in
465 place of ; characters:
466
467 set(mylist a "b|c")
468 foreach(entry IN LISTS mylist)
469 string(REPLACE "|" ";" entry "${entry}")
470 # use "${entry}" normally
471 endforeach()
472
473 The ExternalProject module's LIST_SEPARATOR option is an example of
474 an interface built using this approach.
475
476 • In lists of generator expressions, use the $<SEMICOLON> generator ex‐
477 pression.
478
479 • In command calls, use Quoted Argument syntax whenever possible. The
480 called command will receive the content of the argument with semi‐
481 colons preserved. An Unquoted Argument will be split on semicolons.
482
483 • In function() implementations, avoid ARGV and ARGN, which do not dis‐
484 tinguish semicolons in values from those separating values. Instead,
485 prefer using named positional arguments and the ARGC and ARGV# vari‐
486 ables. When using cmake_parse_arguments() to parse arguments, prefer
487 its PARSE_ARGV signature, which uses the ARGV# variables.
488
489 Note that this approach does not apply to macro() implementations be‐
490 cause they reference arguments using placeholders, not real vari‐
491 ables.
492
494 2000-2023 Kitware, Inc. and Contributors
495
496
497
498
4993.27.7 Oct 07, 2023 CMAKE-LANGUAGE(7)