function.rst 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. and so on. However, it is strongly recommended to stay with the
  33. case chosen in the function definition. Typically functions use
  34. all-lowercase names.
  35. Arguments
  36. ^^^^^^^^^
  37. When the function is invoked, the recorded ``<commands>`` are first
  38. modified by replacing formal parameters (``${arg1}``, ...) with the
  39. arguments passed, and then invoked as normal commands.
  40. In addition to referencing the formal parameters you can reference the
  41. ``ARGC`` variable which will be set to the number of arguments passed
  42. into the function as well as ``ARGV0``, ``ARGV1``, ``ARGV2``, ... which
  43. will have the actual values of the arguments passed in. This facilitates
  44. creating functions with optional arguments.
  45. Furthermore, ``ARGV`` holds the list of all arguments given to the
  46. function and ``ARGN`` holds the list of arguments past the last expected
  47. argument. Referencing to ``ARGV#`` arguments beyond ``ARGC`` have
  48. undefined behavior. Checking that ``ARGC`` is greater than ``#`` is
  49. the only way to ensure that ``ARGV#`` was passed to the function as an
  50. extra argument.