typestar

Conditional compilation in C

The preprocessor can include or drop whole regions based on what is defined.

#include <stdio.h>

#define FEATURE_LEVEL 2

void report(void) {
#if defined(__linux__)
    printf("linux\n");
#elif defined(_WIN32)
    printf("windows\n");
#else
    printf("somewhere else\n");
#endif

#if FEATURE_LEVEL >= 2
    printf("extended features\n");
#endif

#if __STDC_VERSION__ >= 201112L
    printf("C11 or newer\n");
#endif
}

How it works

  1. #ifdef tests whether a macro exists at all.
  2. #if evaluates an integer constant expression.
  3. Predefined macros identify the platform and the standard.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
320
Tokens
68
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 41 seconds.

Type this snippet

Step 2 of 2 in Headers & conditions, step 9 of 12 in Preprocessor & headers.

← Previous Next →