Home C Preprocessor Conditional Compilation C Conditional Compilation Definition
What Is Conditional Compilation? Conditional compilation keeps or removes blocks of source before compilation. #ifdef / #ifndef test whether a macro exists; #if tests a constant expression and works with defined(NAME), #elif, and #else. Use it for debug code, platform differences, and feature switches.
#if defined(DEBUG) && LEVEL >= 2
/* ... */
#elif defined(DEBUG)
/* ... */
#else
/* ... */
#endif Reference
Cheat Sheet Keep these facts handy while you work with Conditional Compilation in C.
Topic Detail #ifdef Macro is defined #if Constant integer expression defined(X) Works inside #if Command line -DMODE=2
Code
C Examples Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Header Guards .
1. Select code by a mode macro Example 1 — Select code by a mode macro Change MODE and only one branch stays in the program.
#include <stdio.h>
#define MODE 2
int main(void) {
#if MODE == 1
printf("mode 1: quiet\n");
#elif MODE == 2
printf("mode 2: verbose\n");
#else
printf("unknown mode\n");
#endif
return 0;
} How It Works #if MODE == 1 is false and #elif MODE == 2 is true.Only the second printf is compiled. You can override MODE with gcc -DMODE=1 if you guard the #define with #ifndef. Edge Cases & Pitfalls Check these before relying on Conditional Compilation in real programs.
sizeof Using sizeof or casts in #if The preprocessor cannot evaluate sizeof or casts; use integer constants and macros only.
nest Unbalanced #endif Every #if needs a matching #endif. Indent nested directives for readability.
Remember
Key Takeaways One line: Conditional compilation keeps or removes blocks of source before compilation.
Frequently Asked Questions What is conditional compilation used for? It builds different versions of a program from one source: debug versus release, per-platform code, and optional features.
What is the difference between #if and #ifdef? #ifdef only checks whether a macro is defined. #if evaluates an integer expression and can combine tests with &&, ||, and defined().
What should I learn after Conditional Compilation? Continue with "C Header Guards" next. Prevent a header from being included more than once. The C Preprocessor hub lists every topic in order.
Next: Header Guards Prevent a header from being included more than once.
Continue → CODETOFUN NEWS
Stay Ahead in Tech Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful
Helpful Share Copy link Suggestion