3d25aa45f05acd000c6ae8e1d75633de8e9b42d1
[platform/upstream/cmake.git] / Help / command / function.rst
1 function
2 --------
3
4 Start recording a function for later invocation as a command.
5
6 .. code-block:: cmake
7
8   function(<name> [<arg1> ...])
9     <commands>
10   endfunction()
11
12 Defines a function named ``<name>`` that takes arguments named
13 ``<arg1>``, ...  The ``<commands>`` in the function definition
14 are recorded; they are not executed until the function is invoked.
15
16 Per legacy, the :command:`endfunction` command admits an optional
17 ``<name>`` argument. If used, it must be a verbatim repeat of the
18 argument of the opening ``function`` command.
19
20 A function opens a new scope: see :command:`set(var PARENT_SCOPE)` for
21 details.
22
23 See the :command:`cmake_policy()` command documentation for the behavior
24 of policies inside functions.
25
26 See the :command:`macro()` command documentation for differences
27 between CMake functions and macros.
28
29 Invocation
30 ^^^^^^^^^^
31
32 The function invocation is case-insensitive. A function defined as
33
34 .. code-block:: cmake
35
36   function(foo)
37     <commands>
38   endfunction()
39
40 can be invoked through any of
41
42 .. code-block:: cmake
43
44   foo()
45   Foo()
46   FOO()
47   cmake_language(CALL foo)
48
49 and so on. However, it is strongly recommended to stay with the
50 case chosen in the function definition. Typically functions use
51 all-lowercase names.
52
53 .. versionadded:: 3.18
54   The :command:`cmake_language(CALL ...)` command can also be used to
55   invoke the function.
56
57 Arguments
58 ^^^^^^^^^
59
60 When the function is invoked, the recorded ``<commands>`` are first
61 modified by replacing formal parameters (``${arg1}``, ...) with the
62 arguments passed, and then invoked as normal commands.
63
64 In addition to referencing the formal parameters you can reference the
65 ``ARGC`` variable which will be set to the number of arguments passed
66 into the function as well as ``ARGV0``, ``ARGV1``, ``ARGV2``, ...  which
67 will have the actual values of the arguments passed in.  This facilitates
68 creating functions with optional arguments.
69
70 Furthermore, ``ARGV`` holds the list of all arguments given to the
71 function and ``ARGN`` holds the list of arguments past the last expected
72 argument.  Referencing to ``ARGV#`` arguments beyond ``ARGC`` have
73 undefined behavior.  Checking that ``ARGC`` is greater than ``#`` is
74 the only way to ensure that ``ARGV#`` was passed to the function as an
75 extra argument.