macro.rst 2.2 KB

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