Skip to content
StudyFame

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)
CheckedBefore compilationWhile the program runs
Condition can useMacros and constants onlyVariables, function results, anything
False branchRemoved; not in the program at allCompiled; just not executed
Ends with#endifA 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

  1. VERSION is 2, so #if VERSION == 1 is false and the Basic lines are removed.
  2. #elif VERSION == 2 is true, so the Plus lines are kept. The remaining #elif and #else parts are removed, just like an else-if ladder.
  3. If someone sets VERSION to 7, the #else branch runs #error and the build stops with the message "VERSION must be 1, 2 or 3".
  4. #if VERSION >= 2 shows that conditions can use comparison operators, so the Plus and Pro versions both get cloud backup.
  5. Only the kept lines reach the compiler. The Basic and Pro printf calls 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 DEBUG defines the macro without a value. That is enough for #ifdef.
  • With DEBUG defined, LOG(msg) becomes a printf. Without it, LOG(msg) becomes nothing, so release builds have zero debug cost.
  • #if defined(DEBUG) && LOG_LEVEL > 1 combines two conditions; #ifdef can test only one name.
  • RELEASE is never defined here, so #ifndef RELEASE keeps the "development" line.

Important Points to Remember

  • Conditional compilation happens before compilation; false branches are not compiled.
  • #if needs a constant expression: macros and literals only, no variables.
  • #ifdef X = #if defined(X); #ifndef X = #if !defined(X).
  • Every #if, #ifdef and #ifndef needs its own #endif.
  • Use -DNAME or -DNAME=value to define macros at compile time.
  • Main uses: debug code, include guards, versions/features and platform-specific code.

Common Mistakes Beginners Make

MistakeWhat happensFix
#if count > 5 with a variablecount is unknown to the preprocessor and treated as 0Use 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 DEBUGStill true: DEBUG is definedUse #if DEBUG to test the value
Writing #elseifUnknown directive errorThe correct spelling is #elif

Conditional Compilation Practice Questions

  1. What is conditional compilation? Name its directives.
  2. What is the difference between #if and an if statement?
  3. What is the difference between #ifdef DEBUG and #if DEBUG?
  4. How can you define a macro from the gcc command line?
  5. What does #error do?
Show answers
  1. Including or excluding code before compilation based on conditions; #if, #elif, #else, #endif, #ifdef, #ifndef (and defined).
  2. #if is decided before compilation using constants and removes the false part; if is decided at run time and both parts are compiled.
  3. #ifdef DEBUG is true if DEBUG exists with any value (even 0); #if DEBUG is true only if its value is non-zero.
  4. gcc -DNAME file.c or gcc -DNAME=value file.c.
  5. 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)

  1. Which directive ends an #if block?

    A) #end   B) #endif   C) #fi   D) #stop

  2. #ifndef X is the same as:

    A) #if X   B) #if defined(X)   C) #if !defined(X)   D) #undef X

  3. The condition of #if can contain:

    A) Variables   B) Function calls   C) Constant expressions of macros and literals   D) Strings only

  4. Which gcc option defines a macro?

    A) -o   B) -c   C) -D   D) -E

  5. Code inside a false #if branch is:

    A) Compiled but not executed   B) Removed before compilation   C) Executed once   D) Turned into comments in the output file

Show answers
  1. B: #endif.
  2. C: #if !defined(X).
  3. C: constant expressions of macros and literals.
  4. C: -D.
  5. 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 compilationKeep/remove code before compilation
Directives#if #elif #else #endif #ifdef #ifndef
#if conditionConstant expression only
#ifdef X= #if defined(X)
#ifndef X= #if !defined(X)
-DNAMEDefine a macro from the command line
#errorStops 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.