foreach.rst 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. foreach
  2. -------
  3. Evaluate a group of commands for each value in a list.
  4. .. code-block:: cmake
  5. foreach(<loop_var> <items>)
  6. <commands>
  7. endforeach()
  8. where ``<items>`` is a list of items that are separated by
  9. semicolon or whitespace.
  10. All commands between ``foreach`` and the matching ``endforeach`` are recorded
  11. without being invoked. Once the ``endforeach`` is evaluated, the recorded
  12. list of commands is invoked once for each item in ``<items>``.
  13. At the beginning of each iteration the variable ``loop_var`` will be set
  14. to the value of the current item.
  15. The commands :command:`break` and :command:`continue` provide means to
  16. escape from the normal control flow.
  17. Per legacy, the :command:`endforeach` command admits
  18. an optional ``<loop_var>`` argument.
  19. If used, it must be a verbatim
  20. repeat of the argument of the opening
  21. ``foreach`` command.
  22. .. code-block:: cmake
  23. foreach(<loop_var> RANGE <stop>)
  24. In this variant, ``foreach`` iterates over the numbers
  25. 0, 1, ... up to (and including) the nonnegative integer ``<stop>``.
  26. .. code-block:: cmake
  27. foreach(<loop_var> RANGE <start> <stop> [<step>])
  28. In this variant, ``foreach`` iterates over the numbers from
  29. ``<start>`` up to at most ``<stop>`` in steps of ``<step>``.
  30. If ``<step>`` is not specified, then the step size is 1.
  31. The three arguments ``<start>`` ``<stop>`` ``<step>`` must
  32. all be nonnegative integers, and ``<stop>`` must not be
  33. smaller than ``<start>``; otherwise you enter the danger zone
  34. of undocumented behavior that may change in future releases.
  35. .. code-block:: cmake
  36. foreach(loop_var IN [LISTS [<lists>]] [ITEMS [<items>]])
  37. In this variant, ``<lists>`` is a whitespace or semicolon
  38. separated list of list-valued variables. The ``foreach``
  39. command iterates over each item in each given list.
  40. The ``<items>`` following the ``ITEMS`` keyword are processed
  41. as in the first variant of the ``foreach`` command.
  42. The forms ``LISTS A`` and ``ITEMS ${A}`` are
  43. equivalent.
  44. The following example shows how the ``LISTS`` option is
  45. processed:
  46. .. code-block:: cmake
  47. set(A 0;1)
  48. set(B 2 3)
  49. set(C "4 5")
  50. set(D 6;7 8)
  51. set(E "")
  52. foreach(X IN LISTS A B C D E)
  53. message(STATUS "X=${X}")
  54. endforeach()
  55. yields
  56. ::
  57. -- X=0
  58. -- X=1
  59. -- X=2
  60. -- X=3
  61. -- X=4 5
  62. -- X=6
  63. -- X=7
  64. -- X=8