CMakePrimer.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. ============
  2. CMake Primer
  3. ============
  4. .. contents::
  5. :local:
  6. .. warning::
  7. Disclaimer: This documentation is written by LLVM project contributors `not`
  8. anyone affiliated with the CMake project. This document may contain
  9. inaccurate terminology, phrasing, or technical details. It is provided with
  10. the best intentions.
  11. Introduction
  12. ============
  13. The LLVM project and many of the core projects built on LLVM build using CMake.
  14. This document aims to provide a brief overview of CMake for developers modifying
  15. LLVM projects or building their own projects on top of LLVM.
  16. The official CMake language references is available in the cmake-language
  17. manpage and `cmake-language online documentation
  18. <https://cmake.org/cmake/help/v3.4/manual/cmake-language.7.html>`_.
  19. 10,000 ft View
  20. ==============
  21. CMake is a tool that reads script files in its own language that describe how a
  22. software project builds. As CMake evaluates the scripts it constructs an
  23. internal representation of the software project. Once the scripts have been
  24. fully processed, if there are no errors, CMake will generate build files to
  25. actually build the project. CMake supports generating build files for a variety
  26. of command line build tools as well as for popular IDEs.
  27. When a user runs CMake it performs a variety of checks similar to how autoconf
  28. worked historically. During the checks and the evaluation of the build
  29. description scripts CMake caches values into the CMakeCache. This is useful
  30. because it allows the build system to skip long-running checks during
  31. incremental development. CMake caching also has some drawbacks, but that will be
  32. discussed later.
  33. Scripting Overview
  34. ==================
  35. CMake's scripting language has a very simple grammar. Every language construct
  36. is a command that matches the pattern _name_(_args_). Commands come in three
  37. primary types: language-defined (commands implemented in C++ in CMake), defined
  38. functions, and defined macros. The CMake distribution also contains a suite of
  39. CMake modules that contain definitions for useful functionality.
  40. The example below is the full CMake build for building a C++ "Hello World"
  41. program. The example uses only CMake language-defined functions.
  42. .. code-block:: cmake
  43. cmake_minimum_required(VERSION 3.2)
  44. project(HelloWorld)
  45. add_executable(HelloWorld HelloWorld.cpp)
  46. The CMake language provides control flow constructs in the form of foreach loops
  47. and if blocks. To make the example above more complicated you could add an if
  48. block to define "APPLE" when targeting Apple platforms:
  49. .. code-block:: cmake
  50. cmake_minimum_required(VERSION 3.2)
  51. project(HelloWorld)
  52. add_executable(HelloWorld HelloWorld.cpp)
  53. if(APPLE)
  54. target_compile_definitions(HelloWorld PUBLIC APPLE)
  55. endif()
  56. Variables, Types, and Scope
  57. ===========================
  58. Dereferencing
  59. -------------
  60. In CMake variables are "stringly" typed. All variables are represented as
  61. strings throughout evaluation. Wrapping a variable in ``${}`` dereferences it
  62. and results in a literal substitution of the name for the value. CMake refers to
  63. this as "variable evaluation" in their documentation. Dereferences are performed
  64. *before* the command being called receives the arguments. This means
  65. dereferencing a list results in multiple separate arguments being passed to the
  66. command.
  67. Variable dereferences can be nested and be used to model complex data. For
  68. example:
  69. .. code-block:: cmake
  70. set(var_name var1)
  71. set(${var_name} foo) # same as "set(var1 foo)"
  72. set(${${var_name}}_var bar) # same as "set(foo_var bar)"
  73. Dereferencing an unset variable results in an empty expansion. It is a common
  74. pattern in CMake to conditionally set variables knowing that it will be used in
  75. code paths that the variable isn't set. There are examples of this throughout
  76. the LLVM CMake build system.
  77. An example of variable empty expansion is:
  78. .. code-block:: cmake
  79. if(APPLE)
  80. set(extra_sources Apple.cpp)
  81. endif()
  82. add_executable(HelloWorld HelloWorld.cpp ${extra_sources})
  83. In this example the ``extra_sources`` variable is only defined if you're
  84. targeting an Apple platform. For all other targets the ``extra_sources`` will be
  85. evaluated as empty before add_executable is given its arguments.
  86. Lists
  87. -----
  88. In CMake lists are semi-colon delimited strings, and it is strongly advised that
  89. you avoid using semi-colons in lists; it doesn't go smoothly. A few examples of
  90. defining lists:
  91. .. code-block:: cmake
  92. # Creates a list with members a, b, c, and d
  93. set(my_list a b c d)
  94. set(my_list "a;b;c;d")
  95. # Creates a string "a b c d"
  96. set(my_string "a b c d")
  97. Lists of Lists
  98. --------------
  99. One of the more complicated patterns in CMake is lists of lists. Because a list
  100. cannot contain an element with a semi-colon to construct a list of lists you
  101. make a list of variable names that refer to other lists. For example:
  102. .. code-block:: cmake
  103. set(list_of_lists a b c)
  104. set(a 1 2 3)
  105. set(b 4 5 6)
  106. set(c 7 8 9)
  107. With this layout you can iterate through the list of lists printing each value
  108. with the following code:
  109. .. code-block:: cmake
  110. foreach(list_name IN LISTS list_of_lists)
  111. foreach(value IN LISTS ${list_name})
  112. message(${value})
  113. endforeach()
  114. endforeach()
  115. You'll notice that the inner foreach loop's list is doubly dereferenced. This is
  116. because the first dereference turns ``list_name`` into the name of the sub-list
  117. (a, b, or c in the example), then the second dereference is to get the value of
  118. the list.
  119. This pattern is used throughout CMake, the most common example is the compiler
  120. flags options, which CMake refers to using the following variable expansions:
  121. CMAKE_${LANGUAGE}_FLAGS and CMAKE_${LANGUAGE}_FLAGS_${CMAKE_BUILD_TYPE}.
  122. Other Types
  123. -----------
  124. Variables that are cached or specified on the command line can have types
  125. associated with them. The variable's type is used by CMake's UI tool to display
  126. the right input field. A variable's type generally doesn't impact evaluation,
  127. however CMake does have special handling for some variables such as PATH.
  128. You can read more about the special handling in `CMake's set documentation
  129. <https://cmake.org/cmake/help/v3.5/command/set.html#set-cache-entry>`_.
  130. Scope
  131. -----
  132. CMake inherently has a directory-based scoping. Setting a variable in a
  133. CMakeLists file, will set the variable for that file, and all subdirectories.
  134. Variables set in a CMake module that is included in a CMakeLists file will be
  135. set in the scope they are included from, and all subdirectories.
  136. When a variable that is already set is set again in a subdirectory it overrides
  137. the value in that scope and any deeper subdirectories.
  138. The CMake set command provides two scope-related options. PARENT_SCOPE sets a
  139. variable into the parent scope, and not the current scope. The CACHE option sets
  140. the variable in the CMakeCache, which results in it being set in all scopes. The
  141. CACHE option will not set a variable that already exists in the CACHE unless the
  142. FORCE option is specified.
  143. In addition to directory-based scope, CMake functions also have their own scope.
  144. This means variables set inside functions do not bleed into the parent scope.
  145. This is not true of macros, and it is for this reason LLVM prefers functions
  146. over macros whenever reasonable.
  147. .. note::
  148. Unlike C-based languages, CMake's loop and control flow blocks do not have
  149. their own scopes.
  150. Control Flow
  151. ============
  152. CMake features the same basic control flow constructs you would expect in any
  153. scripting language, but there are a few quirks because, as with everything in
  154. CMake, control flow constructs are commands.
  155. If, ElseIf, Else
  156. ----------------
  157. .. note::
  158. For the full documentation on the CMake if command go
  159. `here <https://cmake.org/cmake/help/v3.4/command/if.html>`_. That resource is
  160. far more complete.
  161. In general CMake if blocks work the way you'd expect:
  162. .. code-block:: cmake
  163. if(<condition>)
  164. message("do stuff")
  165. elseif(<condition>)
  166. message("do other stuff")
  167. else()
  168. message("do other other stuff")
  169. endif()
  170. The single most important thing to know about CMake's if blocks coming from a C
  171. background is that they do not have their own scope. Variables set inside
  172. conditional blocks persist after the ``endif()``.
  173. Loops
  174. -----
  175. The most common form of the CMake ``foreach`` block is:
  176. .. code-block:: cmake
  177. foreach(var ...)
  178. message("do stuff")
  179. endforeach()
  180. The variable argument portion of the ``foreach`` block can contain dereferenced
  181. lists, values to iterate, or a mix of both:
  182. .. code-block:: cmake
  183. foreach(var foo bar baz)
  184. message(${var})
  185. endforeach()
  186. # prints:
  187. # foo
  188. # bar
  189. # baz
  190. set(my_list 1 2 3)
  191. foreach(var ${my_list})
  192. message(${var})
  193. endforeach()
  194. # prints:
  195. # 1
  196. # 2
  197. # 3
  198. foreach(var ${my_list} out_of_bounds)
  199. message(${var})
  200. endforeach()
  201. # prints:
  202. # 1
  203. # 2
  204. # 3
  205. # out_of_bounds
  206. There is also a more modern CMake foreach syntax. The code below is equivalent
  207. to the code above:
  208. .. code-block:: cmake
  209. foreach(var IN ITEMS foo bar baz)
  210. message(${var})
  211. endforeach()
  212. # prints:
  213. # foo
  214. # bar
  215. # baz
  216. set(my_list 1 2 3)
  217. foreach(var IN LISTS my_list)
  218. message(${var})
  219. endforeach()
  220. # prints:
  221. # 1
  222. # 2
  223. # 3
  224. foreach(var IN LISTS my_list ITEMS out_of_bounds)
  225. message(${var})
  226. endforeach()
  227. # prints:
  228. # 1
  229. # 2
  230. # 3
  231. # out_of_bounds
  232. Similar to the conditional statements, these generally behave how you would
  233. expect, and they do not have their own scope.
  234. CMake also supports ``while`` loops, although they are not widely used in LLVM.
  235. Modules, Functions and Macros
  236. =============================
  237. Modules
  238. -------
  239. Modules are CMake's vehicle for enabling code reuse. CMake modules are just
  240. CMake script files. They can contain code to execute on include as well as
  241. definitions for commands.
  242. In CMake macros and functions are universally referred to as commands, and they
  243. are the primary method of defining code that can be called multiple times.
  244. In LLVM we have several CMake modules that are included as part of our
  245. distribution for developers who don't build our project from source. Those
  246. modules are the fundamental pieces needed to build LLVM-based projects with
  247. CMake. We also rely on modules as a way of organizing the build system's
  248. functionality for maintainability and re-use within LLVM projects.
  249. Argument Handling
  250. -----------------
  251. When defining a CMake command handling arguments is very useful. The examples
  252. in this section will all use the CMake ``function`` block, but this all applies
  253. to the ``macro`` block as well.
  254. CMake commands can have named arguments that are requried at every call site. In
  255. addition, all commands will implicitly accept a variable number of extra
  256. arguments (In C parlance, all commands are varargs functions). When a command is
  257. invoked with extra arguments (beyond the named ones) CMake will store the full
  258. list of arguments (both named and unnamed) in a list named ``ARGV``, and the
  259. sublist of unnamed arguments in ``ARGN``. Below is a trivial example of
  260. providing a wrapper function for CMake's built in function ``add_dependencies``.
  261. .. code-block:: cmake
  262. function(add_deps target)
  263. add_dependencies(${target} ${ARGN})
  264. endfunction()
  265. This example defines a new macro named ``add_deps`` which takes a required first
  266. argument, and just calls another function passing through the first argument and
  267. all trailing arguments.
  268. CMake provides a module ``CMakeParseArguments`` which provides an implementation
  269. of advanced argument parsing. We use this all over LLVM, and it is recommended
  270. for any function that has complex argument-based behaviors or optional
  271. arguments. CMake's official documentation for the module is in the
  272. ``cmake-modules`` manpage, and is also available at the
  273. `cmake-modules online documentation
  274. <https://cmake.org/cmake/help/v3.4/module/CMakeParseArguments.html>`_.
  275. .. note::
  276. As of CMake 3.5 the cmake_parse_arguments command has become a native command
  277. and the CMakeParseArguments module is empty and only left around for
  278. compatibility.
  279. Functions Vs Macros
  280. -------------------
  281. Functions and Macros look very similar in how they are used, but there is one
  282. fundamental difference between the two. Functions have their own scope, and
  283. macros don't. This means variables set in macros will bleed out into the calling
  284. scope. That makes macros suitable for defining very small bits of functionality
  285. only.
  286. The other difference between CMake functions and macros is how arguments are
  287. passed. Arguments to macros are not set as variables, instead dereferences to
  288. the parameters are resolved across the macro before executing it. This can
  289. result in some unexpected behavior if using unreferenced variables. For example:
  290. .. code-block:: cmake
  291. macro(print_list my_list)
  292. foreach(var IN LISTS my_list)
  293. message("${var}")
  294. endforeach()
  295. endmacro()
  296. set(my_list a b c d)
  297. set(my_list_of_numbers 1 2 3 4)
  298. print_list(my_list_of_numbers)
  299. # prints:
  300. # a
  301. # b
  302. # c
  303. # d
  304. Generally speaking this issue is uncommon because it requires using
  305. non-dereferenced variables with names that overlap in the parent scope, but it
  306. is important to be aware of because it can lead to subtle bugs.
  307. LLVM Project Wrappers
  308. =====================
  309. LLVM projects provide lots of wrappers around critical CMake built-in commands.
  310. We use these wrappers to provide consistent behaviors across LLVM components
  311. and to reduce code duplication.
  312. We generally (but not always) follow the convention that commands prefaced with
  313. ``llvm_`` are intended to be used only as building blocks for other commands.
  314. Wrapper commands that are intended for direct use are generally named following
  315. with the project in the middle of the command name (i.e. ``add_llvm_executable``
  316. is the wrapper for ``add_executable``). The LLVM ``add_*`` wrapper functions are
  317. all defined in ``AddLLVM.cmake`` which is installed as part of the LLVM
  318. distribution. It can be included and used by any LLVM sub-project that requires
  319. LLVM.
  320. .. note::
  321. Not all LLVM projects require LLVM for all use cases. For example compiler-rt
  322. can be built without LLVM, and the compiler-rt sanitizer libraries are used
  323. with GCC.
  324. Useful Built-in Commands
  325. ========================
  326. CMake has a bunch of useful built-in commands. This document isn't going to
  327. go into details about them because The CMake project has excellent
  328. documentation. To highlight a few useful functions see:
  329. * `add_custom_command <https://cmake.org/cmake/help/v3.4/command/add_custom_command.html>`_
  330. * `add_custom_target <https://cmake.org/cmake/help/v3.4/command/add_custom_target.html>`_
  331. * `file <https://cmake.org/cmake/help/v3.4/command/file.html>`_
  332. * `list <https://cmake.org/cmake/help/v3.4/command/list.html>`_
  333. * `math <https://cmake.org/cmake/help/v3.4/command/math.html>`_
  334. * `string <https://cmake.org/cmake/help/v3.4/command/string.html>`_
  335. The full documentation for CMake commands is in the ``cmake-commands`` manpage
  336. and available on `CMake's website <https://cmake.org/cmake/help/v3.4/manual/cmake-commands.7.html>`_