Back to course

Advanced Preprocessor Directives (Conditional Compilation)

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 53: Advanced Preprocessor Directives (Conditional Compilation)

Conditional compilation allows the programmer to include or exclude specific blocks of code based on predefined conditions (macros). This is crucial for portability, debugging, and managing different build configurations.

1. #ifdef and #ifndef

  • #ifdef identifier: Checks if a macro identifier has been defined.
  • #ifndef identifier: Checks if a macro identifier has not been defined.

Example: Debugging Toggle

c #include <stdio.h>

#define DEBUG // Define DEBUG globally (e.g., via compiler flag -DDEBUG)

int main() { int data = 42; printf("Program running.\n");

#ifdef DEBUG
    // This code only exists if DEBUG is defined
    printf("[DEBUG] Data value is: %d\n", data);
#endif

printf("Program finished.\n");
return 0;

}

2. #if, #elif, and #else

Checks if a constant integer expression evaluates to true (non-zero).

c #define OS_TYPE 1 // 1 for Linux, 2 for Windows

#if OS_TYPE == 1 #include <unistd.h> #define SYSTEM_NAME "Linux" #elif OS_TYPE == 2 #include <windows.h> #define SYSTEM_NAME "Windows" #else #define SYSTEM_NAME "Unknown" #endif

int main() { printf("Compiling for %s\n", SYSTEM_NAME); return 0; }

3. Header Guards (Preventing Multiple Inclusion)

Conditional compilation is used in header files to ensure that the file contents are only included once, preventing redefinition errors.

c // In myheader.h #ifndef MYHEADER_H #define MYHEADER_H

// Content of the header

#endif // MYHEADER_H