C Preprocessor
The C Preprocessor is a tool that processes the source code before compilation.
It handles tasks like file inclusion, macro processing, conditional compilation, and symbol substitution.
Every line beginning with # is processed by the preprocessor.
What Does the Preprocessor Do?
Before your C program is compiled, the preprocessor:
- Includes header files (
#include) - Defines constants & macros (
#define) - Conditionally compiles code (
#ifdef, #ifndef) - Removes comments
- Expands macros
Preprocessor Directives
Major preprocessor directives include:
- #include β include header files
- #define β define macros/constant values
- #undef β undefine macros
- #ifdef, #ifndef β conditional compilation
- #if, #else, #elif β compile based on conditions
- #pragma β compiler-specific instructions
1. #include Directive
Used to include header files into your program.
#include <stdio.h>β Standard header#include "myfile.h"β User-defined header
Example: #include
#include <stdio.h>
int main() {
printf("Hello Preprocessor!");
return 0;
}
2. #define Directive
- Used to create symbolic constants
- No memory is allocated
- Compiler replaces macro everywhere
#define PI 3.14 #define MAX 100
3. Macro with Arguments
#define SQUARE(x) (x * x)
#include <stdio.h>
int main() {
printf("%d", SQUARE(5));
return 0;
}
4. Conditional Compilation
Used to compile parts of code depending on conditions.
#include <stdio.h>
#define INDIA
int main() {
#ifdef INDIA
printf("Indian Version");
#else
printf("Global Version");
#endif
return 0;
}
5. #undef Directive
Used to delete a defined macro.
#define RATE 10 #undef RATE
6. #pragma Directive
Used for compiler-specific features.
#pragma startup myStart #pragma exit myEnd
β Note:
#pragma usage depends on compiler.
Some pragmas may not work in all compilers.
Practice Questions
- What is a preprocessor?
- Explain macro substitution with an example.
- Differentiate between #include <file.h> and "file.h".
- What is conditional compilation?
- What does #pragma do?
Practice Task
Write a program using macros that:
β Defines PI
β Computes area of a circle
β Uses conditional compilation to print either βSMALLβ or βLARGEβ based on radius