0
0
Cprogramming~5 mins

Conditional compilation

Choose your learning style9 modes available
Introduction

Conditional compilation lets you include or skip parts of your code when you build your program. This helps make your program work differently in different situations without changing the code every time.

You want to make your program work on different computers or systems.
You want to turn on or off debugging messages without deleting code.
You want to include special features only when needed.
You want to avoid compiling code that is not ready or not needed.
You want to test different versions of your code easily.
Syntax
C
#ifdef MACRO_NAME
// code here
#endif

#ifndef MACRO_NAME
// code here
#endif

#if EXPRESSION
// code here
#else
// alternative code
#endif

#ifdef checks if a macro is defined.

#ifndef checks if a macro is NOT defined.

Examples
This code prints a message only if DEBUG is defined.
C
#define DEBUG

#ifdef DEBUG
printf("Debugging is ON\n");
#endif
This code runs only if RELEASE is NOT defined.
C
#ifndef RELEASE
printf("Not in release mode\n");
#endif
This code chooses what to print based on the value of VERSION.
C
#if VERSION >= 2
printf("Version 2 or higher\n");
#else
printf("Version less than 2\n");
#endif
Sample Program

This program uses conditional compilation to print messages based on defined macros. It shows how #ifdef, #if, and #ifndef work.

C
#include <stdio.h>

#define DEBUG
#define VERSION 3

int main() {
    #ifdef DEBUG
    printf("Debug mode is active\n");
    #endif

    #if VERSION >= 2
    printf("Version is 2 or higher\n");
    #else
    printf("Version is less than 2\n");
    #endif

    #ifndef RELEASE
    printf("Release mode is OFF\n");
    #endif

    return 0;
}
OutputSuccess
Important Notes

Macros used in conditional compilation are usually defined with #define or passed as compiler options.

Conditional compilation happens before the program runs, during the build process.

Use conditional compilation to keep your code clean and flexible.

Summary

Conditional compilation lets you include or exclude code when building your program.

Use #ifdef, #ifndef, and #if to check conditions.

This helps make your program adaptable to different needs without changing the source code each time.