Site Tools


wiki:cmake-conditionals-and-loops

Table of Contents

CMake Conditionals and Loops

if(condition)...endif() runs code conditionally. foreach(item IN LISTS mylist)...endforeach() loops over a list. Control flow in CMake is straightforward but the condition syntax is unusual.

Conditionals:

if(DEFINED MY_VAR)
  message(STATUS "MY_VAR is defined")
endif()
 
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
  target_compile_options(myapp PRIVATE -g)
endif()

Condition tests:

if(VAR)                      # true if VAR is not empty/false
if(NOT VAR)                  # true if VAR is empty/false
if(VAR EQUAL 5)              # numeric comparison
if(VAR STREQUAL "value")     # string comparison
if(VAR MATCHES "pattern")    # regex match
if(EXISTS /path/to/file)     # file exists
if(IS_DIRECTORY /path)       # directory exists
if(DEFINED VAR)              # variable is defined
if(TARGET mytarget)          # target exists

Multiple conditions:

if(VAR1 AND VAR2)
  # both true
endif()
 
if(VAR1 OR VAR2)
  # at least one true
endif()

Loops over lists:

set(ITEMS a b c)
foreach(item IN LISTS ITEMS)
  message(STATUS "Processing ${item}")
endforeach()
 
foreach(i RANGE 1 10)
  message("Iteration ${i}")
endforeach()

Looping over ranges:

foreach(i RANGE 10)         # i = 0, 1, ..., 10
foreach(i RANGE 5 15)       # i = 5, 6, ..., 15
foreach(i RANGE 0 10 2)     # i = 0, 2, 4, ..., 10 (step 2)

Looping over variables (not lists):

set(SOURCES main.cpp util.cpp)
foreach(src ${SOURCES})
  message("Source: ${src}")
endforeach()

Breaking and continuing:

break()         # exit loop
continue()      # skip to next iteration

Messages for debugging:

message(STATUS "Normal message")
message(WARNING "A warning")
message(FATAL_ERROR "Stop the build")

Use conditionals to enable/disable features, set compiler flags based on build type, or handle platform-specific logic. Use loops to process lists of files, configure multiple similar targets, or generate code.

wiki/cmake-conditionals-and-loops.md · Last modified: by 127.0.0.1