16917ffd6da7e7ef37f682c85459da8b6189a769
[platform/upstream/cmake.git] / Help / manual / cmake-language.7.rst
1 .. cmake-manual-description: CMake Language Reference
2
3 cmake-language(7)
4 *****************
5
6 .. only:: html
7
8    .. contents::
9
10 Organization
11 ============
12
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.
15
16 CMake Language source files in a project are organized into:
17
18 * `Directories`_ (``CMakeLists.txt``),
19 * `Scripts`_ (``<script>.cmake``), and
20 * `Modules`_ (``<module>.cmake``).
21
22 Directories
23 -----------
24
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.
34
35 Scripts
36 -------
37
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
43 targets or actions.
44
45 Modules
46 -------
47
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`
55 variable.
56
57 Syntax
58 ======
59
60 .. _`CMake Language Encoding`:
61
62 Encoding
63 --------
64
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.
69
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.
76
77 .. _`Byte-Order Mark`: http://en.wikipedia.org/wiki/Byte_order_mark
78
79 Source Files
80 ------------
81
82 A CMake Language source file consists of zero or more
83 `Command Invocations`_ separated by newlines and optionally
84 spaces and `Comments`_:
85
86 .. raw:: latex
87
88    \begin{small}
89
90 .. productionlist::
91  file: `file_element`*
92  file_element: `command_invocation` `line_ending` |
93              : (`bracket_comment`|`space`)* `line_ending`
94  line_ending: `line_comment`? `newline`
95  space: <match '[ \t]+'>
96  newline: <match '\n'>
97
98 .. raw:: latex
99
100    \end{small}
101
102 Note that any source file line not inside `Command Arguments`_ or
103 a `Bracket Comment`_ can end in a `Line Comment`_.
104
105 .. _`Command Invocations`:
106
107 Command Invocations
108 -------------------
109
110 A *command invocation* is a name followed by paren-enclosed arguments
111 separated by whitespace:
112
113 .. raw:: latex
114
115    \begin{small}
116
117 .. productionlist::
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`
124
125 .. raw:: latex
126
127    \end{small}
128
129 For example:
130
131 .. code-block:: cmake
132
133  add_executable(hello world.c)
134
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.
140 For example:
141
142 .. code-block:: cmake
143
144  if(FALSE AND (FALSE OR TRUE)) # evaluates to FALSE
145
146 .. note::
147  CMake versions prior to 3.0 require command name identifiers
148  to be at least 2 characters.
149
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.
154
155 Command Arguments
156 -----------------
157
158 There are three types of arguments within `Command Invocations`_:
159
160 .. raw:: latex
161
162    \begin{small}
163
164 .. productionlist::
165  argument: `bracket_argument` | `quoted_argument` | `unquoted_argument`
166
167 .. raw:: latex
168
169    \end{small}
170
171 .. _`Bracket Argument`:
172
173 Bracket Argument
174 ^^^^^^^^^^^^^^^^
175
176 A *bracket argument*, inspired by `Lua`_ long bracket syntax,
177 encloses content between opening and closing "brackets" of the
178 same length:
179
180 .. raw:: latex
181
182    \begin{small}
183
184 .. productionlist::
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: ']' '='* ']'
190
191 .. raw:: latex
192
193    \end{small}
194
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
200 of other lengths.
201
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.
208
209 .. No code-block syntax highlighting in the following example
210    (long string literal not supported by our cmake.py)
211
212 For example::
213
214  message([=[
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.
220  ]=])
221
222 .. note::
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`_.
226
227 .. _`Lua`: http://www.lua.org/
228
229 .. _`Quoted Argument`:
230
231 Quoted Argument
232 ^^^^^^^^^^^^^^^
233
234 A *quoted argument* encloses content between opening and closing
235 double-quote characters:
236
237 .. raw:: latex
238
239    \begin{small}
240
241 .. productionlist::
242  quoted_argument: '"' `quoted_element`* '"'
243  quoted_element: <any character except '\' or '"'> |
244                  : `escape_sequence` |
245                  : `quoted_continuation`
246  quoted_continuation: '\' `newline`
247
248 .. raw:: latex
249
250    \end{small}
251
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.
256
257 .. No code-block syntax highlighting in the following example
258    (escape \" not supported by our cmake.py)
259
260 For example:
261
262 .. code-block:: cmake
263
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.
269   ")
270
271 .. No code-block syntax highlighting in the following example
272    (for conformity with the two above examples)
273
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:
277
278 .. code-block:: cmake
279
280   message("\
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.\
284   ")
285
286 .. note::
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.
290
291 .. _`Unquoted Argument`:
292
293 Unquoted Argument
294 ^^^^^^^^^^^^^^^^^
295
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:
299
300 .. raw:: latex
301
302    \begin{small}
303
304 .. productionlist::
305  unquoted_argument: `unquoted_element`+ | `unquoted_legacy`
306  unquoted_element: <any character except whitespace or one of '()#"\'> |
307                  : `escape_sequence`
308  unquoted_legacy: <see note in text>
309
310 .. raw:: latex
311
312    \end{small}
313
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
320 more arguments.
321
322 For example:
323
324 .. code-block:: cmake
325
326  foreach(arg
327      NoSpace
328      Escaped\ Space
329      This;Divides;Into;Five;Arguments
330      Escaped\;Semicolon
331      )
332    message("${arg}")
333  endforeach()
334
335 .. note::
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)``).
339
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.
346
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).
351
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.
356
357 .. _`Escape Sequences`:
358
359 Escape Sequences
360 ----------------
361
362 An *escape sequence* is a ``\`` followed by one character:
363
364 .. raw:: latex
365
366    \begin{small}
367
368 .. productionlist::
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: '\;'
373
374 .. raw:: latex
375
376    \end{small}
377
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.)
386
387 .. _`Variable References`:
388
389 Variable References
390 -------------------
391
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}``.
398
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.
404
405 The `Variables`_ section documents the scope of variable names
406 and how their values are set.
407
408 An *environment variable reference* has the form ``$ENV{<variable>}``.
409 See the `Environment Variables`_ section for more information.
410
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.
416
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>}``.
421
422 Comments
423 --------
424
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`_.
429
430 .. _`Bracket Comment`:
431
432 Bracket Comment
433 ^^^^^^^^^^^^^^^
434
435 A ``#`` immediately followed by a :token:`bracket_open` forms a
436 *bracket comment* consisting of the entire bracket enclosure:
437
438 .. raw:: latex
439
440    \begin{small}
441
442 .. productionlist::
443  bracket_comment: '#' `bracket_argument`
444
445 .. raw:: latex
446
447    \end{small}
448
449 For example:
450
451 ::
452
453  #[[This is a bracket comment.
454  It runs until the close bracket.]]
455  message("First Argument\n" #[[Bracket Comment]] "Second Argument")
456
457 .. note::
458  CMake versions prior to 3.0 do not support bracket comments.
459  They interpret the opening ``#`` as the start of a `Line Comment`_.
460
461 .. _`Line Comment`:
462
463 Line Comment
464 ^^^^^^^^^^^^
465
466 A ``#`` not immediately followed by a :token:`bracket_open` forms a
467 *line comment* that runs until the end of the line:
468
469 .. raw:: latex
470
471    \begin{small}
472
473 .. productionlist::
474  line_comment: '#' <any text not starting in a `bracket_open`
475              :      and not containing a `newline`>
476
477 .. raw:: latex
478
479    \end{small}
480
481 For example:
482
483 .. code-block:: cmake
484
485  # This is a line comment.
486  message("First Argument\n" # This is a line comment :)
487          "Second Argument") # This is a line comment.
488
489 Control Structures
490 ==================
491
492 Conditional Blocks
493 ------------------
494
495 The :command:`if`/:command:`elseif`/:command:`else`/:command:`endif`
496 commands delimit code blocks to be executed conditionally.
497
498 Loops
499 -----
500
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.
507
508 Command Definitions
509 -------------------
510
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.
514
515 .. _`CMake Language Variables`:
516
517 Variables
518 =========
519
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 ``-``.
529
530 Variables have dynamic scope.  Each variable "set" or "unset"
531 creates a binding in the current scope:
532
533 Function 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.
539
540 Directory Scope
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.
547
548  A variable "set" or "unset" not inside a function call binds
549  to the current directory scope.
550
551 Persistent Cache
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.
557
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
566 lookups.
567
568 The :manual:`cmake-variables(7)` manual documents the many variables
569 that are provided by CMake or have meaning to CMake when set
570 by project code.
571
572 .. include:: ID_RESERVE.txt
573
574 .. _`CMake Language Environment Variables`:
575
576 Environment Variables
577 =====================
578
579 Environment Variables are like ordinary `Variables`_, with the
580 following differences:
581
582 Scope
583  Environment variables have global scope in a CMake process.
584  They are never cached.
585
586 References
587  `Variable References`_ have the form ``$ENV{<variable>}``, using the
588  :variable:`ENV` operator.
589
590 Initialization
591  Initial values of the CMake environment variables are those of
592  the calling process.
593  Values can be changed using the :command:`set` and :command:`unset`
594  commands.
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.
599
600  See the :ref:`cmake -E env <Run a Command-Line Tool>` command-line
601  tool to run a command in a modified environment.
602
603 Inspection
604  See the :ref:`cmake -E environment <Run a Command-Line Tool>` command-line
605  tool to display all current environment variables.
606
607 The :manual:`cmake-env-variables(7)` manual documents environment
608 variables that have special meaning to CMake.
609
610 .. _`CMake Language Lists`:
611
612 Lists
613 =====
614
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.
622
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
626 as a list:
627
628 .. code-block:: cmake
629
630  set(srcs a.c b.c c.c) # sets "srcs" to "a.c;b.c;c.c"
631
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:
636
637 .. code-block:: cmake
638
639  set(x a "b;c") # sets "x" to "a;b;c", not "a;b\;c"
640
641 In general, lists do not support elements containing ``;`` characters.
642 To avoid problems, consider the following advice:
643
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.
648
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:
653
654   .. code-block:: cmake
655
656     set(mylist a "b|c")
657     foreach(entry IN LISTS mylist)
658       string(REPLACE "|" ";" entry "${entry}")
659       # use "${entry}" normally
660     endforeach()
661
662   The :module:`ExternalProject` module's ``LIST_SEPARATOR`` option is an
663   example of an interface built using this approach.
664
665 * In lists of :manual:`generator expressions <cmake-generator-expressions(7)>`,
666   use the :genex:`$<SEMICOLON>` generator expression.
667
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
671   semicolons.
672
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
676   ``ARGV#`` variables.
677   When using :command:`cmake_parse_arguments` to parse arguments, prefer
678   its ``PARSE_ARGV`` signature, which uses the ``ARGV#`` variables.
679
680   Note that this approach does not apply to :command:`macro` implementations
681   because they reference arguments using placeholders, not real variables.