Conditional if/else
Inevitably you'll need to use if()
condition checks to test if some condition is met. Common pre-defined variables to check include: WIN32
, UNIX
, APPLE
, and CYGWIN
. There are also a number of enum-like operators that can be used for comparisons. You can view the complete rundown on the if | CMake Documentation page.
cmake_minimum_required(VERSION 3.28)
project(m-yproject)
if(WIN32)
add_executable(my-app main_windows.c)
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
add_executable(my-app main_linux.c)
else()
add_executable(my-app main.c)
endif()
cmake -B build
cmake --build build
./build/my-app
Notice how the elseif()
block uses the STREQUAL
operator instead of a more common idiom like ==
to check if the CMAKE_SYSTEM_NAME
variable is equal to "Linux"
.
Other common string operators include STRLESS
, STRGREATER
, STREQUAL
, STRLESS_EQUAL
, and STRGREATER_EQUAL
. There's also a bunch of number operators like LESS
, GREATER
, EQUAL
, LESS_EQUAL
, and GREATER_EQUAL
. There's even some for comparison semver specifiers! Check out the full list at if | CMake Documentation.