← Preprocessor and CompilationC PROGRAMMING 1.6.B

Conditional Compilation

#ifdef/#ifndef/#if and platform-guarded code.

StatusCollected
NotesChapter test: 4/5 (retry)

Compiling different code depending on what's defined — the mechanism behind cross-platform source and debug-only builds.

#ifdef DEBUG
    printf("debug: entering function\n");
#endif

#if defined(__linux__)
    /* linux-specific code */
#elif defined(_WIN32)
    /* windows-specific code */
#else
    #error "unsupported platform"
#endif

#ifdef X just checks whether X is defined at all, regardless of its value — even #define X with nothing after it counts. #if is the more general form, actually evaluating an expression, which is what makes #elif/platform-detection chains like the one above possible.

Notes from readers

Comments — via GitHub