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