function.rst 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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
  9. named ``<arg1>``, ...
  10. The ``<commands>`` in the function definition are recorded;
  11. they are not invoked until the function is invoked. When
  12. the function is invoked, the recorded ``<commands>`` are first
  13. modified by replacing formal parameters (``${arg1}``, ...)
  14. with the arguments passed, and then invoked as normal commands.
  15. In addition to referencing the formal parameters you can reference the
  16. ``ARGC`` variable which will be set to the number of arguments passed
  17. into the function as well as ``ARGV0``, ``ARGV1``, ``ARGV2``, ... which
  18. will have the actual values of the arguments passed in.
  19. This facilitates creating functions with optional arguments.
  20. Furthermore, ``ARGV`` holds the list of all arguments given to the
  21. function and ``ARGN`` holds the list of arguments past the last expected
  22. argument.
  23. Referencing to ``ARGV#`` arguments beyond ``ARGC`` have undefined
  24. behavior. Checking that ``ARGC`` is greater than ``#`` is the only way
  25. to ensure that ``ARGV#`` was passed to the function as an extra
  26. argument.
  27. Per legacy, the :command:`endfunction` command admits an optional
  28. ``<name>`` argument. If used, it must be a verbatim repeat of the
  29. argument of the opening ``function`` command.
  30. A function opens a new scope: see :command:`set(var PARENT_SCOPE)` for
  31. details.
  32. See the :command:`cmake_policy()` command documentation for the behavior
  33. of policies inside functions.