cmake-language.7.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. .. cmake-manual-description: CMake Language Reference
  2. cmake-language(7)
  3. *****************
  4. .. only:: html
  5. .. contents::
  6. Organization
  7. ============
  8. CMake input files are written in the "CMake Language" in source files
  9. named ``CMakeLists.txt`` or ending in a ``.cmake`` file name extension.
  10. CMake Language source files in a project are organized into:
  11. * `Directories`_ (``CMakeLists.txt``),
  12. * `Scripts`_ (``<script>.cmake``), and
  13. * `Modules`_ (``<module>.cmake``).
  14. Directories
  15. -----------
  16. When CMake processes a project source tree, the entry point is
  17. a source file called ``CMakeLists.txt`` in the top-level source
  18. directory. This file may contain the entire build specification
  19. or use the :command:`add_subdirectory` command to add subdirectories
  20. to the build. Each subdirectory added by the command must also
  21. contain a ``CMakeLists.txt`` file as the entry point to that
  22. directory. For each source directory whose ``CMakeLists.txt`` file
  23. is processed CMake generates a corresponding directory in the build
  24. tree to act as the default working and output directory.
  25. Scripts
  26. -------
  27. An individual ``<script>.cmake`` source file may be processed
  28. in *script mode* by using the :manual:`cmake(1)` command-line tool
  29. with the ``-P`` option. Script mode simply runs the commands in
  30. the given CMake Language source file and does not generate a
  31. build system. It does not allow CMake commands that define build
  32. targets or actions.
  33. Modules
  34. -------
  35. CMake Language code in either `Directories`_ or `Scripts`_ may
  36. use the :command:`include` command to load a ``<module>.cmake``
  37. source file in the scope of the including context.
  38. See the :manual:`cmake-modules(7)` manual page for documentation
  39. of modules included with the CMake distribution.
  40. Project source trees may also provide their own modules and
  41. specify their location(s) in the :variable:`CMAKE_MODULE_PATH`
  42. variable.
  43. Syntax
  44. ======
  45. .. _`CMake Language Encoding`:
  46. Encoding
  47. --------
  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``
  51. as input files are read.
  52. Note that the implementation is 8-bit clean so source files may
  53. be encoded as UTF-8 on platforms with system APIs supporting this
  54. encoding. In addition, CMake 3.2 and above support source files
  55. encoded in UTF-8 on Windows (using UTF-16 to call system APIs).
  56. Furthermore, CMake 3.0 and above allow a leading UTF-8
  57. `Byte-Order Mark`_ in source files.
  58. .. _`Byte-Order Mark`: http://en.wikipedia.org/wiki/Byte_order_mark
  59. Source Files
  60. ------------
  61. A CMake Language source file consists of zero or more
  62. `Command Invocations`_ separated by newlines and optionally
  63. spaces and `Comments`_:
  64. .. raw:: latex
  65. \begin{small}
  66. .. productionlist::
  67. file: `file_element`*
  68. file_element: `command_invocation` `line_ending` |
  69. : (`bracket_comment`|`space`)* `line_ending`
  70. line_ending: `line_comment`? `newline`
  71. space: <match '[ \t]+'>
  72. newline: <match '\n'>
  73. .. raw:: latex
  74. \end{small}
  75. Note that any source file line not inside `Command Arguments`_ or
  76. a `Bracket Comment`_ can end in a `Line Comment`_.
  77. .. _`Command Invocations`:
  78. Command Invocations
  79. -------------------
  80. A *command invocation* is a name followed by paren-enclosed arguments
  81. separated by whitespace:
  82. .. raw:: latex
  83. \begin{small}
  84. .. productionlist::
  85. command_invocation: `space`* `identifier` `space`* '(' `arguments` ')'
  86. identifier: <match '[A-Za-z_][A-Za-z0-9_]*'>
  87. arguments: `argument`? `separated_arguments`*
  88. separated_arguments: `separation`+ `argument`? |
  89. : `separation`* '(' `arguments` ')'
  90. separation: `space` | `line_ending`
  91. .. raw:: latex
  92. \end{small}
  93. For example:
  94. .. code-block:: cmake
  95. add_executable(hello world.c)
  96. Command names are case-insensitive.
  97. Nested unquoted parentheses in the arguments must balance.
  98. Each ``(`` or ``)`` is given to the command invocation as
  99. a literal `Unquoted Argument`_. This may be used in calls
  100. to the :command:`if` command to enclose conditions.
  101. For example:
  102. .. code-block:: cmake
  103. if(FALSE AND (FALSE OR TRUE)) # evaluates to FALSE
  104. .. note::
  105. CMake versions prior to 3.0 require command name identifiers
  106. to be at least 2 characters.
  107. CMake versions prior to 2.8.12 silently accept an `Unquoted Argument`_
  108. or a `Quoted Argument`_ immediately following a `Quoted Argument`_ and
  109. not separated by any whitespace. For compatibility, CMake 2.8.12 and
  110. higher accept such code but produce a warning.
  111. Command Arguments
  112. -----------------
  113. There are three types of arguments within `Command Invocations`_:
  114. .. raw:: latex
  115. \begin{small}
  116. .. productionlist::
  117. argument: `bracket_argument` | `quoted_argument` | `unquoted_argument`
  118. .. raw:: latex
  119. \end{small}
  120. .. _`Bracket Argument`:
  121. Bracket Argument
  122. ^^^^^^^^^^^^^^^^
  123. A *bracket argument*, inspired by `Lua`_ long bracket syntax,
  124. encloses content between opening and closing "brackets" of the
  125. same length:
  126. .. raw:: latex
  127. \begin{small}
  128. .. productionlist::
  129. bracket_argument: `bracket_open` `bracket_content` `bracket_close`
  130. bracket_open: '[' '='* '['
  131. bracket_content: <any text not containing a `bracket_close` with
  132. : the same number of '=' as the `bracket_open`>
  133. bracket_close: ']' '='* ']'
  134. .. raw:: latex
  135. \end{small}
  136. An opening bracket is written ``[`` followed by zero or more ``=`` followed
  137. by ``[``. The corresponding closing bracket is written ``]`` followed
  138. by the same number of ``=`` followed by ``]``.
  139. Brackets do not nest. A unique length may always be chosen
  140. for the opening and closing brackets to contain closing brackets
  141. of other lengths.
  142. Bracket argument content consists of all text between the opening
  143. and closing brackets, except that one newline immediately following
  144. the opening bracket, if any, is ignored. No evaluation of the
  145. enclosed content, such as `Escape Sequences`_ or `Variable References`_,
  146. is performed. A bracket argument is always given to the command
  147. invocation as exactly one argument.
  148. .. No code-block syntax highlighting in the following example
  149. (long string literal not supported by our cmake.py)
  150. For example::
  151. message([=[
  152. This is the first line in a bracket argument with bracket length 1.
  153. No \-escape sequences or ${variable} references are evaluated.
  154. This is always one argument even though it contains a ; character.
  155. The text does not end on a closing bracket of length 0 like ]].
  156. It does end in a closing bracket of length 1.
  157. ]=])
  158. .. note::
  159. CMake versions prior to 3.0 do not support bracket arguments.
  160. They interpret the opening bracket as the start of an
  161. `Unquoted Argument`_.
  162. .. _`Lua`: http://www.lua.org/
  163. .. _`Quoted Argument`:
  164. Quoted Argument
  165. ^^^^^^^^^^^^^^^
  166. A *quoted argument* encloses content between opening and closing
  167. double-quote characters:
  168. .. raw:: latex
  169. \begin{small}
  170. .. productionlist::
  171. quoted_argument: '"' `quoted_element`* '"'
  172. quoted_element: <any character except '\' or '"'> |
  173. : `escape_sequence` |
  174. : `quoted_continuation`
  175. quoted_continuation: '\' `newline`
  176. .. raw:: latex
  177. \end{small}
  178. Quoted argument content consists of all text between opening and
  179. closing quotes. Both `Escape Sequences`_ and `Variable References`_
  180. are evaluated. A quoted argument is always given to the command
  181. invocation as exactly one argument.
  182. .. No code-block syntax highlighting in the following example
  183. (escape \" not supported by our cmake.py)
  184. For example:
  185. .. code-block:: cmake
  186. message("This is a quoted argument containing multiple lines.
  187. This is always one argument even though it contains a ; character.
  188. Both \\-escape sequences and ${variable} references are evaluated.
  189. The text does not end on an escaped double-quote like \".
  190. It does end in an unescaped double quote.
  191. ")
  192. .. No code-block syntax highlighting in the following example
  193. (for conformity with the two above examples)
  194. The final ``\`` on any line ending in an odd number of backslashes
  195. is treated as a line continuation and ignored along with the
  196. immediately following newline character. For example:
  197. .. code-block:: cmake
  198. message("\
  199. This is the first line of a quoted argument. \
  200. In fact it is the only line but since it is long \
  201. the source code uses line continuation.\
  202. ")
  203. .. note::
  204. CMake versions prior to 3.0 do not support continuation with ``\``.
  205. They report errors in quoted arguments containing lines ending in
  206. an odd number of ``\`` characters.
  207. .. _`Unquoted Argument`:
  208. Unquoted Argument
  209. ^^^^^^^^^^^^^^^^^
  210. An *unquoted argument* is not enclosed by any quoting syntax.
  211. It may not contain any whitespace, ``(``, ``)``, ``#``, ``"``, or ``\``
  212. except when escaped by a backslash:
  213. .. raw:: latex
  214. \begin{small}
  215. .. productionlist::
  216. unquoted_argument: `unquoted_element`+ | `unquoted_legacy`
  217. unquoted_element: <any character except whitespace or one of '()#"\'> |
  218. : `escape_sequence`
  219. unquoted_legacy: <see note in text>
  220. .. raw:: latex
  221. \end{small}
  222. Unquoted argument content consists of all text in a contiguous block
  223. of allowed or escaped characters. Both `Escape Sequences`_ and
  224. `Variable References`_ are evaluated. The resulting value is divided
  225. in the same way `Lists`_ divide into elements. Each non-empty element
  226. is given to the command invocation as an argument. Therefore an
  227. unquoted argument may be given to a command invocation as zero or
  228. more arguments.
  229. For example:
  230. .. code-block:: cmake
  231. foreach(arg
  232. NoSpace
  233. Escaped\ Space
  234. This;Divides;Into;Five;Arguments
  235. Escaped\;Semicolon
  236. )
  237. message("${arg}")
  238. endforeach()
  239. .. note::
  240. To support legacy CMake code, unquoted arguments may also contain
  241. double-quoted strings (``"..."``, possibly enclosing horizontal
  242. whitespace), and make-style variable references (``$(MAKEVAR)``).
  243. Unescaped double-quotes must balance, may not appear at the
  244. beginning of an unquoted argument, and are treated as part of the
  245. content. For example, the unquoted arguments ``-Da="b c"``,
  246. ``-Da=$(v)``, and ``a" "b"c"d`` are each interpreted literally.
  247. They may instead be written as quoted arguments ``"-Da=\"b c\""``,
  248. ``"-Da=$(v)"``, and ``"a\" \"b\"c\"d"``, respectively.
  249. Make-style references are treated literally as part of the content
  250. and do not undergo variable expansion. They are treated as part
  251. of a single argument (rather than as separate ``$``, ``(``,
  252. ``MAKEVAR``, and ``)`` arguments).
  253. The above "unquoted_legacy" production represents such arguments.
  254. We do not recommend using legacy unquoted arguments in new code.
  255. Instead use a `Quoted Argument`_ or a `Bracket Argument`_ to
  256. represent the content.
  257. .. _`Escape Sequences`:
  258. Escape Sequences
  259. ----------------
  260. An *escape sequence* is a ``\`` followed by one character:
  261. .. raw:: latex
  262. \begin{small}
  263. .. productionlist::
  264. escape_sequence: `escape_identity` | `escape_encoded` | `escape_semicolon`
  265. escape_identity: '\' <match '[^A-Za-z0-9;]'>
  266. escape_encoded: '\t' | '\r' | '\n'
  267. escape_semicolon: '\;'
  268. .. raw:: latex
  269. \end{small}
  270. A ``\`` followed by a non-alphanumeric character simply encodes the literal
  271. character without interpreting it as syntax. A ``\t``, ``\r``, or ``\n``
  272. encodes a tab, carriage return, or newline character, respectively. A ``\;``
  273. outside of any `Variable References`_ encodes itself but may be used in an
  274. `Unquoted Argument`_ to encode the ``;`` without dividing the argument
  275. value on it. A ``\;`` inside `Variable References`_ encodes the literal
  276. ``;`` character. (See also policy :policy:`CMP0053` documentation for
  277. historical considerations.)
  278. .. _`Variable References`:
  279. Variable References
  280. -------------------
  281. A *variable reference* has the form ``${variable_name}`` and is
  282. evaluated inside a `Quoted Argument`_ or an `Unquoted Argument`_.
  283. A variable reference is replaced by the value of the variable,
  284. or by the empty string if the variable is not set.
  285. Variable references can nest and are evaluated from the
  286. inside out, e.g. ``${outer_${inner_variable}_variable}``.
  287. Literal variable references may consist of alphanumeric characters,
  288. the characters ``/_.+-``, and `Escape Sequences`_. Nested references
  289. may be used to evaluate variables of any name. See also policy
  290. :policy:`CMP0053` documentation for historical considerations and reasons why
  291. the ``$`` is also technically permitted but is discouraged.
  292. The `Variables`_ section documents the scope of variable names
  293. and how their values are set.
  294. An *environment variable reference* has the form ``$ENV{VAR}``.
  295. See :variable:`ENV` for more information.
  296. A *cache variable reference* has the form ``$CACHE{VAR}``.
  297. See :variable:`CACHE` for more information.
  298. Comments
  299. --------
  300. A comment starts with a ``#`` character that is not inside a
  301. `Bracket Argument`_, `Quoted Argument`_, or escaped with ``\``
  302. as part of an `Unquoted Argument`_. There are two types of
  303. comments: a `Bracket Comment`_ and a `Line Comment`_.
  304. .. _`Bracket Comment`:
  305. Bracket Comment
  306. ^^^^^^^^^^^^^^^
  307. A ``#`` immediately followed by a `Bracket Argument`_ forms a
  308. *bracket comment* consisting of the entire bracket enclosure:
  309. .. raw:: latex
  310. \begin{small}
  311. .. productionlist::
  312. bracket_comment: '#' `bracket_argument`
  313. .. raw:: latex
  314. \end{small}
  315. For example:
  316. ::
  317. #[[This is a bracket comment.
  318. It runs until the close bracket.]]
  319. message("First Argument\n" #[[Bracket Comment]] "Second Argument")
  320. .. note::
  321. CMake versions prior to 3.0 do not support bracket comments.
  322. They interpret the opening ``#`` as the start of a `Line Comment`_.
  323. .. _`Line Comment`:
  324. Line Comment
  325. ^^^^^^^^^^^^
  326. A ``#`` not immediately followed by a `Bracket Argument`_ forms a
  327. *line comment* that runs until the end of the line:
  328. .. raw:: latex
  329. \begin{small}
  330. .. productionlist::
  331. line_comment: '#' <any text not starting in a `bracket_argument`
  332. : and not containing a `newline`>
  333. .. raw:: latex
  334. \end{small}
  335. For example:
  336. .. code-block:: cmake
  337. # This is a line comment.
  338. message("First Argument\n" # This is a line comment :)
  339. "Second Argument") # This is a line comment.
  340. Control Structures
  341. ==================
  342. Conditional Blocks
  343. ------------------
  344. The :command:`if`/:command:`elseif`/:command:`else`/:command:`endif`
  345. commands delimit code blocks to be executed conditionally.
  346. Loops
  347. -----
  348. The :command:`foreach`/:command:`endforeach` and
  349. :command:`while`/:command:`endwhile` commands delimit code
  350. blocks to be executed in a loop. Inside such blocks the
  351. :command:`break` command may be used to terminate the loop
  352. early whereas the :command:`continue` command may be used
  353. to start with the next iteration immediately.
  354. Command Definitions
  355. -------------------
  356. The :command:`macro`/:command:`endmacro`, and
  357. :command:`function`/:command:`endfunction` commands delimit
  358. code blocks to be recorded for later invocation as commands.
  359. .. _`CMake Language Variables`:
  360. Variables
  361. =========
  362. Variables are the basic unit of storage in the CMake Language.
  363. Their values are always of string type, though some commands may
  364. interpret the strings as values of other types.
  365. The :command:`set` and :command:`unset` commands explicitly
  366. set or unset a variable, but other commands have semantics
  367. that modify variables as well.
  368. Variable names are case-sensitive and may consist of almost
  369. any text, but we recommend sticking to names consisting only
  370. of alphanumeric characters plus ``_`` and ``-``.
  371. Variables have dynamic scope. Each variable "set" or "unset"
  372. creates a binding in the current scope:
  373. Function Scope
  374. `Command Definitions`_ created by the :command:`function` command
  375. create commands that, when invoked, process the recorded commands
  376. in a new variable binding scope. A variable "set" or "unset"
  377. binds in this scope and is visible for the current function and
  378. any nested calls within it, but not after the function returns.
  379. Directory Scope
  380. Each of the `Directories`_ in a source tree has its own variable
  381. bindings. Before processing the ``CMakeLists.txt`` file for a
  382. directory, CMake copies all variable bindings currently defined
  383. in the parent directory, if any, to initialize the new directory
  384. scope. CMake `Scripts`_, when processed with ``cmake -P``, bind
  385. variables in one "directory" scope.
  386. A variable "set" or "unset" not inside a function call binds
  387. to the current directory scope.
  388. Persistent Cache
  389. CMake stores a separate set of "cache" variables, or "cache entries",
  390. whose values persist across multiple runs within a project build
  391. tree. Cache entries have an isolated binding scope modified only
  392. by explicit request, such as by the ``CACHE`` option of the
  393. :command:`set` and :command:`unset` commands.
  394. When evaluating `Variable References`_, CMake first searches the
  395. function call stack, if any, for a binding and then falls back
  396. to the binding in the current directory scope, if any. If a
  397. "set" binding is found, its value is used. If an "unset" binding
  398. is found, or no binding is found, CMake then searches for a
  399. cache entry. If a cache entry is found, its value is used.
  400. Otherwise, the variable reference evaluates to an empty string.
  401. The ``$CACHE{VAR}`` syntax can be used to do direct cache entry
  402. lookups.
  403. The :manual:`cmake-variables(7)` manual documents many variables
  404. that are provided by CMake or have meaning to CMake when set
  405. by project code.
  406. .. _`CMake Language Lists`:
  407. Lists
  408. =====
  409. Although all values in CMake are stored as strings, a string
  410. may be treated as a list in certain contexts, such as during
  411. evaluation of an `Unquoted Argument`_. In such contexts, a string
  412. is divided into list elements by splitting on ``;`` characters not
  413. following an unequal number of ``[`` and ``]`` characters and not
  414. immediately preceded by a ``\``. The sequence ``\;`` does not
  415. divide a value but is replaced by ``;`` in the resulting element.
  416. A list of elements is represented as a string by concatenating
  417. the elements separated by ``;``. For example, the :command:`set`
  418. command stores multiple values into the destination variable
  419. as a list:
  420. .. code-block:: cmake
  421. set(srcs a.c b.c c.c) # sets "srcs" to "a.c;b.c;c.c"
  422. Lists are meant for simple use cases such as a list of source
  423. files and should not be used for complex data processing tasks.
  424. Most commands that construct lists do not escape ``;`` characters
  425. in list elements, thus flattening nested lists:
  426. .. code-block:: cmake
  427. set(x a "b;c") # sets "x" to "a;b;c", not "a;b\;c"