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