Home / Learn Embedded C / The C Preprocessor and Macros
The C Preprocessor and Macros
#define, #include and conditional compilation — code that runs before the compiler sees your code.
How to think about this
In plain terms
The preprocessor is a text-substitution pass that runs before compilation: #include pastes in a header file's contents, and #define creates text macros that get substituted everywhere they appear.
Why we use it
Embedded code uses #define constantly for register addresses, bit masks and feature flags, and #ifdef/#ifndef to compile different code for different chips or build configurations from the same source file.
Under the hood
The preprocessor does pure text substitution — it does not understand C syntax or types, which is exactly why macros can behave surprisingly if you are not careful (see the next lesson's warning).
Real-world use
- Register addresses
- Feature flags
- Multi-chip codebases
Try it
MAX_RETRIES is substituted as plain text before compilation even starts — the compiler never even sees the name MAX_RETRIES, only the number 3.
| Directive | What it does |
|---|---|
| #include | Paste in a system header file's contents |
| #define NAME value | Replace NAME with value, everywhere, before compiling |
| #ifdef / #ifndef | Compile a block of code only if a macro is (or is not) defined |
#include <stdio.h>
#define MAX_RETRIES 3
int main() {
printf("this build allows %d retries\n", MAX_RETRIES);
#ifdef DEBUG_BUILD
printf("(debug build)\n");
#endif
return 0;
}Try it: a function-like macro
Parentheses around both the parameter and the whole expression keep SQUARE(2 + 3) from expanding incorrectly -- function-like macros need careful parenthesization since they are pure text substitution.
Quick quiz
1. What does the preprocessor understand about your C code?
The preprocessor is a dumb text-substitution pass; it has no concept of C types or syntax.