Conditional Compilation in C
Sometimes you want one source file to produce slightly different programs: a debug version that prints extra messages, a free and a pro version, or code for Windows and Linux. You don't need separate files for that. Conditional compilation lets the preprocessor keep some lines and throw others away before compiling.
In this lesson you will learn #if, #elif, #else, #endif, #ifdef, #ifndef, the defined operator and #error, with practical debug and version examples.
What You Will Learn
- What conditional compilation is and why it is useful.
- How #if, #elif, #else and #endif choose code.
- How #ifdef, #ifndef and defined() test for macros.
- How to switch debug messages on and off.
- How to set macros from the command line with
-D. - How #error stops a wrong build.
Conditional Compilation in C Explained
Exam definition: Conditional compilation is a preprocessor feature that includes or excludes parts of the source code before compilation, depending on conditions. It uses the directives #if, #elif, #else, #endif, #ifdef and #ifndef. The condition must be a constant integer expression made of macros and literals; code in a false branch is removed and never compiled.
Memory trick: Conditional compilation is a tailor cutting cloth before stitching. Marked pieces are cut off and thrown away before the machine (compiler) starts. An if statement is different: it is like a zip on a finished jacket, sewn in and opened or closed later while you wear it (at run time).
#if vs if statement
| Point | #if (preprocessor) | if (C statement) |
|---|---|---|
| Checked | Before compilation | While the program runs |
| Condition can use | Macros and constants only | Variables, function results, anything |
| False branch | Removed; not in the program at all | Compiled; just not executed |
| Ends with | #endif | A closing brace or statement |
Syntax of Conditional Compilation
#if CONSTANT_EXPRESSION
/* kept if the expression is non-zero */
#elif OTHER_EXPRESSION
/* kept if the first was 0 and this is non-zero */
#else
/* kept if all of the above were 0 */
#endif
#ifdef NAME /* same as #if defined(NAME) */
/* kept if NAME is defined (with any value) */
#endif
#ifndef NAME /* same as #if !defined(NAME) */
/* kept if NAME is not defined */
#endif
#if defined(A) && !defined(B)
/* combine tests with &&, || and ! */
#endif
#error message /* stop the build with this message */
Example 1: Choosing a Version with #if and #elif
#include <stdio.h>
#define VERSION 2 /* 1 = Basic, 2 = Plus, 3 = Pro */
int main(void)
{
printf("Notes App\n");
#if VERSION == 1
printf("Edition : Basic\n");
printf("Max notes: 10\n");
#elif VERSION == 2
printf("Edition : Plus\n");
printf("Max notes: 100\n");
#elif VERSION == 3
printf("Edition : Pro\n");
printf("Max notes: unlimited\n");
#else
#error "VERSION must be 1, 2 or 3"
#endif
#if VERSION >= 2
printf("Feature : cloud backup enabled\n");
#endif
return 0;
}
Output
Notes App Edition : Plus Max notes: 100 Feature : cloud backup enabled
Code Explanation
VERSIONis 2, so#if VERSION == 1is false and the Basic lines are removed.#elif VERSION == 2is true, so the Plus lines are kept. The remaining#elifand#elseparts are removed, just like an else-if ladder.- If someone sets
VERSIONto 7, the#elsebranch runs#errorand the build stops with the message "VERSION must be 1, 2 or 3". #if VERSION >= 2shows that conditions can use comparison operators, so the Plus and Pro versions both get cloud backup.- Only the kept lines reach the compiler. The Basic and Pro
printfcalls don't exist in this executable at all.
How Conditional Compilation Works
The preprocessor reads the file from top to bottom and acts like a gatekeeper:
#if condition -> evaluate using macro values (an unknown name counts as 0)
true : keep lines until #elif / #else / #endif
false : drop lines, try the next #elif, then #else
#endif -> the block ends; continue normally
You can also define macros without editing the file, from the command line:
gcc app.c -o app # DEBUG not defined
gcc -DDEBUG app.c -o app_debug # same as #define DEBUG 1
gcc -DVERSION=3 app.c -o app_pro # same as #define VERSION 3
This is how real projects build a debug version and a release version from the same code.
Example 2: Debug Messages with #ifdef
#include <stdio.h>
#define DEBUG /* delete this line for the release build */
#define LOG_LEVEL 2
#ifdef DEBUG
#define LOG(msg) printf("[debug] %s\n", msg)
#else
#define LOG(msg) /* expands to nothing */
#endif
int sum_array(const int a[], int n)
{
int i, s = 0;
LOG("sum_array started");
for (i = 0; i < n; i++)
s += a[i];
return s;
}
int main(void)
{
int marks[] = {45, 72, 88, 60};
LOG("program started");
printf("Total marks: %d\n", sum_array(marks, 4));
#if defined(DEBUG) && LOG_LEVEL > 1
printf("[debug] array has %d elements\n", (int)(sizeof marks / sizeof marks[0]));
#endif
#ifndef RELEASE
printf("Build type: development\n");
#endif
return 0;
}
Output
[debug] program started [debug] sum_array started Total marks: 265 [debug] array has 4 elements Build type: development
#define DEBUGdefines the macro without a value. That is enough for#ifdef.- With DEBUG defined,
LOG(msg)becomes aprintf. Without it,LOG(msg)becomes nothing, so release builds have zero debug cost. #if defined(DEBUG) && LOG_LEVEL > 1combines two conditions;#ifdefcan test only one name.RELEASEis never defined here, so#ifndef RELEASEkeeps the "development" line.
Important Points to Remember
- Conditional compilation happens before compilation; false branches are not compiled.
#ifneeds a constant expression: macros and literals only, no variables.#ifdef X=#if defined(X);#ifndef X=#if !defined(X).- Every
#if,#ifdefand#ifndefneeds its own#endif. - Use
-DNAMEor-DNAME=valueto define macros at compile time. - Main uses: debug code, include guards, versions/features and platform-specific code.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
#if count > 5 with a variable | count is unknown to the preprocessor and treated as 0 | Use a normal if for variables |
Missing #endif | "unterminated conditional directive" | Close each block; indent comments like #endif /* DEBUG */ |
#ifdef DEBUG && TEST | #ifdef takes only one name | #if defined(DEBUG) && defined(TEST) |
#define DEBUG 0 then #ifdef DEBUG | Still true: DEBUG is defined | Use #if DEBUG to test the value |
Writing #elseif | Unknown directive error | The correct spelling is #elif |
Conditional Compilation Practice Questions
- What is conditional compilation? Name its directives.
- What is the difference between
#ifand anifstatement? - What is the difference between
#ifdef DEBUGand#if DEBUG? - How can you define a macro from the gcc command line?
- What does
#errordo?
Show answers
- Including or excluding code before compilation based on conditions; #if, #elif, #else, #endif, #ifdef, #ifndef (and defined).
- #if is decided before compilation using constants and removes the false part;
ifis decided at run time and both parts are compiled. #ifdef DEBUGis true if DEBUG exists with any value (even 0);#if DEBUGis true only if its value is non-zero.gcc -DNAME file.corgcc -DNAME=value file.c.- Stops compilation and prints the given error message.
Coding Exercise
Write a program with a macro LANG: 1 = English, 2 = Hindi (in English letters), 3 = French. Use #if/#elif/#else to print "Hello" in the chosen language, and #error for any other value. Set LANG to 2.
Show solution
#include <stdio.h>
#ifndef LANG
#define LANG 2
#endif
int main(void)
{
#if LANG == 1
printf("Hello, student!\n");
#elif LANG == 2
printf("Namaste, vidyarthi!\n");
#elif LANG == 3
printf("Bonjour, etudiant!\n");
#else
#error "LANG must be 1, 2 or 3"
#endif
printf("Language code: %d\n", LANG);
return 0;
}
Namaste, vidyarthi! Language code: 2
Try gcc -DLANG=3 hello.c to get the French version without editing the file.
Quick Quiz: Conditional Compilation (MCQ)
-
Which directive ends an
#ifblock?A)
#endB)#endifC)#fiD)#stop -
#ifndef Xis the same as:A)
#if XB)#if defined(X)C)#if !defined(X)D)#undef X -
The condition of
#ifcan contain:A) Variables B) Function calls C) Constant expressions of macros and literals D) Strings only
-
Which gcc option defines a macro?
A)
-oB)-cC)-DD)-E -
Code inside a false
#ifbranch is:A) Compiled but not executed B) Removed before compilation C) Executed once D) Turned into comments in the output file
Show answers
- B:
#endif. - C:
#if !defined(X). - C: constant expressions of macros and literals.
- C:
-D. - B: removed before compilation.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Conditional compilation | Keep/remove code before compilation |
|---|---|
| Directives | #if #elif #else #endif #ifdef #ifndef |
| #if condition | Constant expression only |
| #ifdef X | = #if defined(X) |
| #ifndef X | = #if !defined(X) |
| -DNAME | Define a macro from the command line |
| #error | Stops the build with a message |
Frequently asked questions
- What is conditional compilation in C?
- A preprocessor feature that includes or excludes code before compilation using #if, #ifdef, #ifndef, #else and #endif.
- What is the difference between #ifdef and #if?
- #ifdef checks whether a macro is defined; #if checks whether an expression's value is non-zero.
- Where is conditional compilation used?
- In debug builds, include guards, version/feature flags and platform-specific code.
Remember
- #if = the tailor cuts before stitching; if = a zip used later.
- Every #if needs an #endif.
Next Topic
Next lesson: Predefined Macros in C. You will use the built-in macros __FILE__, __LINE__, __DATE__, __TIME__ and __func__ to write helpful log messages.