Conditional Compilation — #ifdef
Conditional compilation directives let you include or exclude parts of the code before compilation, based on whether a macro is defined or a condition is true. This is useful for platform-specific code, debug builds, and feature flags.
#ifdef — If Defined
Compiles the block only if the macro has been defined:
DEBUG is defined, the printf is compiled. If not, it’s completely removed.
#ifndef — If Not Defined
Compiles the block only if the macro has NOT been defined (most commonly used as include guards):
#if, #elif, #else, #endif
More powerful: evaluate a constant expression, not just whether a macro exists.
Complete Example: Debug vs Release Build
DEBUG_MODE defined:
DEBUG_MODE:
Platform-Specific Code
Summary of Conditional Directives
| Directive | Meaning |
|---|---|
#ifdef NAME | Compile if NAME is defined |
#ifndef NAME | Compile if NAME is NOT defined |
#if expr | Compile if expression is non-zero |
#elif expr | Else-if branch |
#else | Else branch |
#endif | End of conditional block |
#undef NAME | Undefine a macro |