C Preprocessor Introduction
In this page:
What is the Preprocessor?
This is a purely textual process -- the preprocessor has no understanding of C syntax or semantics, it just performs pattern-based find-and-replace and file-inclusion operations before the real compiler ever sees the code.
Example: What is the Preprocessor?
#include <stdio.h>
#define GREETING "Hello"
int main() {
printf(GREETING);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Header Expansion
This is effectively a copy-paste operation: the entire target header file's text is inserted in place of the #include line, which is why including the same header twice (without protection) can cause duplicate-definition errors.
Example: Header Expansion
#include <stdio.h>
int main() {
printf("stdio.h contents are copied in before compiling");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Macro Substitution
Because this is pure text substitution rather than a function call, macros have no type checking and can behave unexpectedly with complex arguments -- this is a common source of subtle bugs compared to using an actual function.
Example: Macro Substitution
#include <stdio.h>
#define PI 3.14
int main() {
printf("%.2f", PI);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Conditional Preparation
This lets you compile different versions of the same source file for different platforms or configurations, without maintaining separate copies of the code, by defining or omitting certain macros at compile time.
Example: Conditional Preparation
#include <stdio.h>
#define DEBUG 1
int main() {
#if DEBUG
printf("Debug mode");
#endif
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The Compilation Flow
This intermediate expanded output (sometimes visible with a compiler flag like -E) contains no macros, comments, or conditional blocks left -- just plain C code ready for the compiler's lexer and parser to process.
Example: The Compilation Flow
#include <stdio.h>
#define VALUE 5
int main() {
printf("%d", VALUE);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: