function.rst 2.2 KB

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