1 .. cmake-manual-description: CMake Language Reference
13 CMake input files are written in the "CMake Language" in source files
14 named ``CMakeLists.txt`` or ending in a ``.cmake`` file name extension.
16 CMake Language source files in a project are organized into:
18 * `Directories`_ (``CMakeLists.txt``),
19 * `Scripts`_ (``<script>.cmake``), and
20 * `Modules`_ (``<module>.cmake``).
25 When CMake processes a project source tree, the entry point is
26 a source file called ``CMakeLists.txt`` in the top-level source
27 directory. This file may contain the entire build specification
28 or use the :command:`add_subdirectory` command to add subdirectories
29 to the build. Each subdirectory added by the command must also
30 contain a ``CMakeLists.txt`` file as the entry point to that
31 directory. For each source directory whose ``CMakeLists.txt`` file
32 is processed CMake generates a corresponding directory in the build
33 tree to act as the default working and output directory.
38 An individual ``<script>.cmake`` source file may be processed
39 in *script mode* by using the :manual:`cmake(1)` command-line tool
40 with the ``-P`` option. Script mode simply runs the commands in
41 the given CMake Language source file and does not generate a
42 build system. It does not allow CMake commands that define build
48 CMake Language code in either `Directories`_ or `Scripts`_ may
49 use the :command:`include` command to load a ``<module>.cmake``
50 source file in the scope of the including context.
51 See the :manual:`cmake-modules(7)` manual page for documentation
52 of modules included with the CMake distribution.
53 Project source trees may also provide their own modules and
54 specify their location(s) in the :variable:`CMAKE_MODULE_PATH`
60 .. _`CMake Language Encoding`:
65 A CMake Language source file may be written in 7-bit ASCII text for
66 maximum portability across all supported platforms. Newlines may be
67 encoded as either ``\n`` or ``\r\n`` but will be converted to ``\n``
68 as input files are read.
70 Note that the implementation is 8-bit clean so source files may
71 be encoded as UTF-8 on platforms with system APIs supporting this
72 encoding. In addition, CMake 3.2 and above support source files
73 encoded in UTF-8 on Windows (using UTF-16 to call system APIs).
74 Furthermore, CMake 3.0 and above allow a leading UTF-8
75 `Byte-Order Mark`_ in source files.
77 .. _`Byte-Order Mark`: http://en.wikipedia.org/wiki/Byte_order_mark
82 A CMake Language source file consists of zero or more
83 `Command Invocations`_ separated by newlines and optionally
84 spaces and `Comments`_:
92 file_element: `command_invocation` `line_ending` |
93 : (`bracket_comment`|`space`)* `line_ending`
94 line_ending: `line_comment`? `newline`
95 space: <match '[ \t]+'>
102 Note that any source file line not inside `Command Arguments`_ or
103 a `Bracket Comment`_ can end in a `Line Comment`_.
105 .. _`Command Invocations`:
110 A *command invocation* is a name followed by paren-enclosed arguments
111 separated by whitespace:
118 command_invocation: `space`* `identifier` `space`* '(' `arguments` ')'
119 identifier: <match '[A-Za-z_][A-Za-z0-9_]*'>
120 arguments: `argument`? `separated_arguments`*
121 separated_arguments: `separation`+ `argument`? |
122 : `separation`* '(' `arguments` ')'
123 separation: `space` | `line_ending`
131 .. code-block:: cmake
133 add_executable(hello world.c)
135 Command names are case-insensitive.
136 Nested unquoted parentheses in the arguments must balance.
137 Each ``(`` or ``)`` is given to the command invocation as
138 a literal `Unquoted Argument`_. This may be used in calls
139 to the :command:`if` command to enclose conditions.
142 .. code-block:: cmake
144 if(FALSE AND (FALSE OR TRUE)) # evaluates to FALSE
147 CMake versions prior to 3.0 require command name identifiers
148 to be at least 2 characters.
150 CMake versions prior to 2.8.12 silently accept an `Unquoted Argument`_
151 or a `Quoted Argument`_ immediately following a `Quoted Argument`_ and
152 not separated by any whitespace. For compatibility, CMake 2.8.12 and
153 higher accept such code but produce a warning.
158 There are three types of arguments within `Command Invocations`_:
165 argument: `bracket_argument` | `quoted_argument` | `unquoted_argument`
171 .. _`Bracket Argument`:
176 A *bracket argument*, inspired by `Lua`_ long bracket syntax,
177 encloses content between opening and closing "brackets" of the
185 bracket_argument: `bracket_open` `bracket_content` `bracket_close`
186 bracket_open: '[' '='* '['
187 bracket_content: <any text not containing a `bracket_close` with
188 : the same number of '=' as the `bracket_open`>
189 bracket_close: ']' '='* ']'
195 An opening bracket is written ``[`` followed by zero or more ``=`` followed
196 by ``[``. The corresponding closing bracket is written ``]`` followed
197 by the same number of ``=`` followed by ``]``.
198 Brackets do not nest. A unique length may always be chosen
199 for the opening and closing brackets to contain closing brackets
202 Bracket argument content consists of all text between the opening
203 and closing brackets, except that one newline immediately following
204 the opening bracket, if any, is ignored. No evaluation of the
205 enclosed content, such as `Escape Sequences`_ or `Variable References`_,
206 is performed. A bracket argument is always given to the command
207 invocation as exactly one argument.
209 .. No code-block syntax highlighting in the following example
210 (long string literal not supported by our cmake.py)
215 This is the first line in a bracket argument with bracket length 1.
216 No \-escape sequences or ${variable} references are evaluated.
217 This is always one argument even though it contains a ; character.
218 The text does not end on a closing bracket of length 0 like ]].
219 It does end in a closing bracket of length 1.
223 CMake versions prior to 3.0 do not support bracket arguments.
224 They interpret the opening bracket as the start of an
225 `Unquoted Argument`_.
227 .. _`Lua`: http://www.lua.org/
229 .. _`Quoted Argument`:
234 A *quoted argument* encloses content between opening and closing
235 double-quote characters:
242 quoted_argument: '"' `quoted_element`* '"'
243 quoted_element: <any character except '\' or '"'> |
244 : `escape_sequence` |
245 : `quoted_continuation`
246 quoted_continuation: '\' `newline`
252 Quoted argument content consists of all text between opening and
253 closing quotes. Both `Escape Sequences`_ and `Variable References`_
254 are evaluated. A quoted argument is always given to the command
255 invocation as exactly one argument.
257 .. No code-block syntax highlighting in the following example
258 (escape \" not supported by our cmake.py)
262 .. code-block:: cmake
264 message("This is a quoted argument containing multiple lines.
265 This is always one argument even though it contains a ; character.
266 Both \\-escape sequences and ${variable} references are evaluated.
267 The text does not end on an escaped double-quote like \".
268 It does end in an unescaped double quote.
271 .. No code-block syntax highlighting in the following example
272 (for conformity with the two above examples)
274 The final ``\`` on any line ending in an odd number of backslashes
275 is treated as a line continuation and ignored along with the
276 immediately following newline character. For example:
278 .. code-block:: cmake
281 This is the first line of a quoted argument. \
282 In fact it is the only line but since it is long \
283 the source code uses line continuation.\
287 CMake versions prior to 3.0 do not support continuation with ``\``.
288 They report errors in quoted arguments containing lines ending in
289 an odd number of ``\`` characters.
291 .. _`Unquoted Argument`:
296 An *unquoted argument* is not enclosed by any quoting syntax.
297 It may not contain any whitespace, ``(``, ``)``, ``#``, ``"``, or ``\``
298 except when escaped by a backslash:
305 unquoted_argument: `unquoted_element`+ | `unquoted_legacy`
306 unquoted_element: <any character except whitespace or one of '()#"\'> |
308 unquoted_legacy: <see note in text>
314 Unquoted argument content consists of all text in a contiguous block
315 of allowed or escaped characters. Both `Escape Sequences`_ and
316 `Variable References`_ are evaluated. The resulting value is divided
317 in the same way `Lists`_ divide into elements. Each non-empty element
318 is given to the command invocation as an argument. Therefore an
319 unquoted argument may be given to a command invocation as zero or
324 .. code-block:: cmake
329 This;Divides;Into;Five;Arguments
336 To support legacy CMake code, unquoted arguments may also contain
337 double-quoted strings (``"..."``, possibly enclosing horizontal
338 whitespace), and make-style variable references (``$(MAKEVAR)``).
340 Unescaped double-quotes must balance, may not appear at the
341 beginning of an unquoted argument, and are treated as part of the
342 content. For example, the unquoted arguments ``-Da="b c"``,
343 ``-Da=$(v)``, and ``a" "b"c"d`` are each interpreted literally.
344 They may instead be written as quoted arguments ``"-Da=\"b c\""``,
345 ``"-Da=$(v)"``, and ``"a\" \"b\"c\"d"``, respectively.
347 Make-style references are treated literally as part of the content
348 and do not undergo variable expansion. They are treated as part
349 of a single argument (rather than as separate ``$``, ``(``,
350 ``MAKEVAR``, and ``)`` arguments).
352 The above "unquoted_legacy" production represents such arguments.
353 We do not recommend using legacy unquoted arguments in new code.
354 Instead use a `Quoted Argument`_ or a `Bracket Argument`_ to
355 represent the content.
357 .. _`Escape Sequences`:
362 An *escape sequence* is a ``\`` followed by one character:
369 escape_sequence: `escape_identity` | `escape_encoded` | `escape_semicolon`
370 escape_identity: '\' <match '[^A-Za-z0-9;]'>
371 escape_encoded: '\t' | '\r' | '\n'
372 escape_semicolon: '\;'
378 A ``\`` followed by a non-alphanumeric character simply encodes the literal
379 character without interpreting it as syntax. A ``\t``, ``\r``, or ``\n``
380 encodes a tab, carriage return, or newline character, respectively. A ``\;``
381 outside of any `Variable References`_ encodes itself but may be used in an
382 `Unquoted Argument`_ to encode the ``;`` without dividing the argument
383 value on it. A ``\;`` inside `Variable References`_ encodes the literal
384 ``;`` character. (See also policy :policy:`CMP0053` documentation for
385 historical considerations.)
387 .. _`Variable References`:
392 A *variable reference* has the form ``${<variable>}`` and is
393 evaluated inside a `Quoted Argument`_ or an `Unquoted Argument`_.
394 A variable reference is replaced by the value of the specified
395 variable or cache entry, or if neither is set, by the empty string.
396 Variable references can nest and are evaluated from the
397 inside out, e.g. ``${outer_${inner_variable}_variable}``.
399 Literal variable references may consist of alphanumeric characters,
400 the characters ``/_.+-``, and `Escape Sequences`_. Nested references
401 may be used to evaluate variables of any name. See also policy
402 :policy:`CMP0053` documentation for historical considerations and reasons why
403 the ``$`` is also technically permitted but is discouraged.
405 The `Variables`_ section documents the scope of variable names
406 and how their values are set.
408 An *environment variable reference* has the form ``$ENV{<variable>}``.
409 See the `Environment Variables`_ section for more information.
411 A *cache variable reference* has the form ``$CACHE{<variable>}``,
412 and is replaced by the value of the specified cache entry without
413 checking for a normal variable of the same name. If the cache
414 entry does not exist, it is replaced by the empty string.
415 See :variable:`CACHE` for more information.
417 The :command:`if` command has a special condition syntax that
418 allows for variable references in the short form ``<variable>``
419 instead of ``${<variable>}``. However, environment variables
420 always need to be referenced as ``$ENV{<variable>}``.
425 A comment starts with a ``#`` character that is not inside a
426 `Bracket Argument`_, `Quoted Argument`_, or escaped with ``\``
427 as part of an `Unquoted Argument`_. There are two types of
428 comments: a `Bracket Comment`_ and a `Line Comment`_.
430 .. _`Bracket Comment`:
435 A ``#`` immediately followed by a :token:`bracket_open` forms a
436 *bracket comment* consisting of the entire bracket enclosure:
443 bracket_comment: '#' `bracket_argument`
453 #[[This is a bracket comment.
454 It runs until the close bracket.]]
455 message("First Argument\n" #[[Bracket Comment]] "Second Argument")
458 CMake versions prior to 3.0 do not support bracket comments.
459 They interpret the opening ``#`` as the start of a `Line Comment`_.
466 A ``#`` not immediately followed by a :token:`bracket_open` forms a
467 *line comment* that runs until the end of the line:
474 line_comment: '#' <any text not starting in a `bracket_open`
475 : and not containing a `newline`>
483 .. code-block:: cmake
485 # This is a line comment.
486 message("First Argument\n" # This is a line comment :)
487 "Second Argument") # This is a line comment.
495 The :command:`if`/:command:`elseif`/:command:`else`/:command:`endif`
496 commands delimit code blocks to be executed conditionally.
501 The :command:`foreach`/:command:`endforeach` and
502 :command:`while`/:command:`endwhile` commands delimit code
503 blocks to be executed in a loop. Inside such blocks the
504 :command:`break` command may be used to terminate the loop
505 early whereas the :command:`continue` command may be used
506 to start with the next iteration immediately.
511 The :command:`macro`/:command:`endmacro`, and
512 :command:`function`/:command:`endfunction` commands delimit
513 code blocks to be recorded for later invocation as commands.
515 .. _`CMake Language Variables`:
520 Variables are the basic unit of storage in the CMake Language.
521 Their values are always of string type, though some commands may
522 interpret the strings as values of other types.
523 The :command:`set` and :command:`unset` commands explicitly
524 set or unset a variable, but other commands have semantics
525 that modify variables as well.
526 Variable names are case-sensitive and may consist of almost
527 any text, but we recommend sticking to names consisting only
528 of alphanumeric characters plus ``_`` and ``-``.
530 Variables have dynamic scope. Each variable "set" or "unset"
531 creates a binding in the current scope:
534 `Command Definitions`_ created by the :command:`function` command
535 create commands that, when invoked, process the recorded commands
536 in a new variable binding scope. A variable "set" or "unset"
537 binds in this scope and is visible for the current function and
538 any nested calls within it, but not after the function returns.
541 Each of the `Directories`_ in a source tree has its own variable
542 bindings. Before processing the ``CMakeLists.txt`` file for a
543 directory, CMake copies all variable bindings currently defined
544 in the parent directory, if any, to initialize the new directory
545 scope. CMake `Scripts`_, when processed with ``cmake -P``, bind
546 variables in one "directory" scope.
548 A variable "set" or "unset" not inside a function call binds
549 to the current directory scope.
552 CMake stores a separate set of "cache" variables, or "cache entries",
553 whose values persist across multiple runs within a project build
554 tree. Cache entries have an isolated binding scope modified only
555 by explicit request, such as by the ``CACHE`` option of the
556 :command:`set` and :command:`unset` commands.
558 When evaluating `Variable References`_, CMake first searches the
559 function call stack, if any, for a binding and then falls back
560 to the binding in the current directory scope, if any. If a
561 "set" binding is found, its value is used. If an "unset" binding
562 is found, or no binding is found, CMake then searches for a
563 cache entry. If a cache entry is found, its value is used.
564 Otherwise, the variable reference evaluates to an empty string.
565 The ``$CACHE{VAR}`` syntax can be used to do direct cache entry
568 The :manual:`cmake-variables(7)` manual documents the many variables
569 that are provided by CMake or have meaning to CMake when set
572 .. include:: ID_RESERVE.txt
574 .. _`CMake Language Environment Variables`:
576 Environment Variables
577 =====================
579 Environment Variables are like ordinary `Variables`_, with the
580 following differences:
583 Environment variables have global scope in a CMake process.
584 They are never cached.
587 `Variable References`_ have the form ``$ENV{<variable>}``, using the
588 :variable:`ENV` operator.
591 Initial values of the CMake environment variables are those of
593 Values can be changed using the :command:`set` and :command:`unset`
595 These commands only affect the running CMake process,
596 not the system environment at large.
597 Changed values are not written back to the calling process,
598 and they are not seen by subsequent build or test processes.
600 See the :ref:`cmake -E env <Run a Command-Line Tool>` command-line
601 tool to run a command in a modified environment.
604 See the :ref:`cmake -E environment <Run a Command-Line Tool>` command-line
605 tool to display all current environment variables.
607 The :manual:`cmake-env-variables(7)` manual documents environment
608 variables that have special meaning to CMake.
610 .. _`CMake Language Lists`:
615 Although all values in CMake are stored as strings, a string
616 may be treated as a list in certain contexts, such as during
617 evaluation of an `Unquoted Argument`_. In such contexts, a string
618 is divided into list elements by splitting on ``;`` characters not
619 following an unequal number of ``[`` and ``]`` characters and not
620 immediately preceded by a ``\``. The sequence ``\;`` does not
621 divide a value but is replaced by ``;`` in the resulting element.
623 A list of elements is represented as a string by concatenating
624 the elements separated by ``;``. For example, the :command:`set`
625 command stores multiple values into the destination variable
628 .. code-block:: cmake
630 set(srcs a.c b.c c.c) # sets "srcs" to "a.c;b.c;c.c"
632 Lists are meant for simple use cases such as a list of source
633 files and should not be used for complex data processing tasks.
634 Most commands that construct lists do not escape ``;`` characters
635 in list elements, thus flattening nested lists:
637 .. code-block:: cmake
639 set(x a "b;c") # sets "x" to "a;b;c", not "a;b\;c"
641 In general, lists do not support elements containing ``;`` characters.
642 To avoid problems, consider the following advice:
644 * The interfaces of many CMake commands, variables, and properties accept
645 semicolon-separated lists. Avoid passing lists with elements containing
646 semicolons to these interfaces unless they document either direct support
647 or some way to escape or encode semicolons.
649 * When constructing a list, substitute an otherwise-unused placeholder
650 for ``;`` in elements when. Then substitute ``;`` for the placeholder
651 when processing list elements.
652 For example, the following code uses ``|`` in place of ``;`` characters:
654 .. code-block:: cmake
657 foreach(entry IN LISTS mylist)
658 string(REPLACE "|" ";" entry "${entry}")
659 # use "${entry}" normally
662 The :module:`ExternalProject` module's ``LIST_SEPARATOR`` option is an
663 example of an interface built using this approach.
665 * In lists of :manual:`generator expressions <cmake-generator-expressions(7)>`,
666 use the :genex:`$<SEMICOLON>` generator expression.
668 * In command calls, use `Quoted Argument`_ syntax whenever possible.
669 The called command will receive the content of the argument with
670 semicolons preserved. An `Unquoted Argument`_ will be split on
673 * In :command:`function` implementations, avoid ``ARGV`` and ``ARGN``,
674 which do not distinguish semicolons in values from those separating values.
675 Instead, prefer using named positional arguments and the ``ARGC`` and
677 When using :command:`cmake_parse_arguments` to parse arguments, prefer
678 its ``PARSE_ARGV`` signature, which uses the ``ARGV#`` variables.
680 Note that this approach does not apply to :command:`macro` implementations
681 because they reference arguments using placeholders, not real variables.