Loops

Let's learn about the while and foreach loops in CMake.

Loops in CMake are fairly straightforward – we can use either while() or foreach() to repeatedly execute the same set of commands. Both of these commands support loop control mechanisms:

  • The break() loop stops the execution of the remaining block and breaks from the enclosing loop.

  • The continue() loop stops the execution of the current iteration and starts at the top of the next one.

The while() loop

The loop block is opened with a while() command and closed with an endwhile() command. Any enclosed commands will be executed as long as the <condition> expression provided in while() is true. The syntax for phrasing the condition is the same as for the if() command:

Get hands-on with 1400+ tech skills courses.