Control flow

Filename: CMakeLists.txt

cmake_minimum_required(VERSION 3.31)

project(control-flow LANGUAGES C)

foreach(varname IN ITEMS WIN32 UNIX APPLE)
    if("${${varname}}") # Double expansion. "${WIN32}" or similar.
        add_executable("${varname}-only" "./src/bin/${varname}-only.c")
    endif()
endforeach()

Filename: src/bin/UNIX-only.c

#include <stdio.h>

int main() {
    printf("Hello, %s!\n", "UNIX");
    return 0;
}

Filename: src/bin/APPLE-only.c

#include <stdio.h>

int main() {
    printf("Hello, %s!\n", "APPLE");
    return 0;
}

Filename: src/bin/WIN32-only.c

#include <stdio.h>

int main() {
    printf("Hello, %s!\n", "WIN32");
    return 0;
}
$ cmake -B ./build/
-- The C compiler identification is GNU 9.4.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Configuring done (0.3s)
-- Generating done (0.0s)
-- Build files have been written to: /workspaces/cmakebyexample.jcbhmr.com/listings/04-control-flow/build
$ cmake --build ./build/
[ 50%] Building C object CMakeFiles/UNIX-only.dir/src/bin/UNIX-only.c.o
[100%] Linking C executable UNIX-only
[100%] Built target UNIX-only
$ ./build/UNIX-only
Hello, UNIX!