Preprocessor Directives
The preprocessor is the first step in the compilation pipeline. It acts as a text substitution tool, parsing all directives starting with the pound (#) symbol.
1 Macros & Header Guards
Common preprocessor directives include:
- #define: Creates text substitution macros.
- #include: Injects the content of specified header files directly into your source code.
- Conditional Compilation (#ifndef, #define, #endif): Prevents compiler errors caused by double function declarations. Often used as **Header Guards** in header files:
#ifndef MY_HEADER_H #define MY_HEADER_H // declarations go here #endif
2 Declaring Macros and Conditional Compilation
Let's run a program defining macro constants, function macros, and checking conditions:
C — Preprocessor directives
▶ Run Code
#include <stdio.h>
// Macro constant
#define PI 3.14159
// Inline functional macro (parentheses prevent order of operation bugs)
#define SQUARE(x) ((x) * (x))
int main() {
printf("Value of PI: %f\n", PI);
printf("Square of (5 + 1): %d\n", SQUARE(5 + 1)); // ((5+1)*(5+1)) = 36
// Conditional compilation checks
#ifdef PI
printf("PI macro is declared!\n");
#else
printf("PI macro is not declared!\n");
#endif
return 0;
}
3 Code Challenge
Challenge: Define a function macro called `MAX(x, y)` using the ternary conditional operator. Write code inside `main()` to test it by comparing two integer values, and print out the maximum value.