function.rst 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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_command(INVOKE 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. The :command:`cmake_command(INVOKE ...)` command can also be used to invoke the
  37. function.
  38. Arguments
  39. ^^^^^^^^^
  40. When the function is invoked, the recorded ``<commands>`` are first
  41. modified by replacing formal parameters (``${arg1}``, ...) with the
  42. arguments passed, and then invoked as normal commands.
  43. In addition to referencing the formal parameters you can reference the
  44. ``ARGC`` variable which will be set to the number of arguments passed
  45. into the function as well as ``ARGV0``, ``ARGV1``, ``ARGV2``, ... which
  46. will have the actual values of the arguments passed in. This facilitates
  47. creating functions with optional arguments.
  48. Furthermore, ``ARGV`` holds the list of all arguments given to the
  49. function and ``ARGN`` holds the list of arguments past the last expected
  50. argument. Referencing to ``ARGV#`` arguments beyond ``ARGC`` have
  51. undefined behavior. Checking that ``ARGC`` is greater than ``#`` is
  52. the only way to ensure that ``ARGV#`` was passed to the function as an
  53. extra argument.