macro.rst 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. macro
  2. -----
  3. Start recording a macro for later invocation as a command::
  4. macro(<name> [arg1 [arg2 [arg3 ...]]])
  5. COMMAND1(ARGS ...)
  6. COMMAND2(ARGS ...)
  7. ...
  8. endmacro(<name>)
  9. Define a macro named ``<name>`` that takes arguments named ``arg1``,
  10. ``arg2``, ``arg3``, (...).
  11. Commands listed after macro, but before the matching
  12. :command:`endmacro()`, are not invoked until the macro is invoked.
  13. When it is invoked, the commands recorded in the macro are first
  14. modified by replacing formal parameters (``${arg1}``) with the arguments
  15. passed, and then invoked as normal commands.
  16. In addition to referencing the formal parameters you can reference the
  17. values ``${ARGC}`` which will be set to the number of arguments passed
  18. into the function as well as ``${ARGV0}``, ``${ARGV1}``, ``${ARGV2}``,
  19. ... which will have the actual values of the arguments passed in.
  20. This facilitates creating macros with optional arguments.
  21. Additionally ``${ARGV}`` holds the list of all arguments given to the
  22. macro and ``${ARGN}`` holds the list of arguments past the last expected
  23. argument.
  24. See the :command:`cmake_policy()` command documentation for the behavior
  25. of policies inside macros.
  26. Macro Argument Caveats
  27. ^^^^^^^^^^^^^^^^^^^^^^
  28. Note that the parameters to a macro and values such as ``ARGN`` are
  29. not variables in the usual CMake sense. They are string
  30. replacements much like the C preprocessor would do with a macro.
  31. Therefore you will NOT be able to use commands like::
  32. if(ARGV1) # ARGV1 is not a variable
  33. foreach(loop_var IN LISTS ARGN) # ARGN is not a variable
  34. In the first case you can use ``if(${ARGV1})``, in the second case, you can
  35. use ``foreach(loop_var ${ARGN})`` but this will skip empty arguments.
  36. If you need to include them, you can use::
  37. set(list_var "${ARGN}")
  38. foreach(loop_var IN LISTS list_var)
  39. Note that if you have a variable with the same name in the scope from
  40. which the macro is called, using unreferenced names will use the
  41. existing variable instead of the arguments. For example::
  42. macro(_BAR)
  43. foreach(arg IN LISTS ARGN)
  44. [...]
  45. endforeach()
  46. endmacro()
  47. function(_FOO)
  48. _bar(x y z)
  49. endfunction()
  50. _foo(a b c)
  51. Will loop over ``a;b;c`` and not over ``x;y;z`` as one might be expecting.
  52. If you want true CMake variables and/or better CMake scope control you
  53. should look at the function command.