Preprocessor
The preprocessor is a text-processing stage that runs before the C compiler. It copies in headers, expands macros, and removes conditional branches, producing the expanded source the compiler actually reads.
Detailed Explanation
Before any C is compiled, your source passes through a program that knows almost nothing about C. It works on preprocessing tokens: identifiers, numbers, string literals, punctuation. It has no idea what a type is, what a function is, or where a block begins and ends. It reads lines that start with # as instructions and copies everything else through, substituting macro names as it goes.
That is the whole design, and both the usefulness and the sharp edges follow from it.
The directives are a short list:
| Directive | Purpose |
|---|---|
#include | replace this line with the contents of a file |
#define, #undef | create or remove a macro |
#if, #ifdef, #ifndef, #elif, #else, #endif | keep or discard a region of text |
#error, #warning | stop the build, or complain, with a message (#warning is a common extension, standard since C23) |
#line | rewrite the reported line number, used by code generators |
#pragma | pass an implementation-specific instruction to the compiler |
It exists because C has no module system and no compile-time evaluation of its own. Sharing a function's declaration between files needs a mechanism for pasting the same text into many files, and #include is that mechanism. Adapting one codebase to Linux, Windows and an embedded target needs a way to compile different code per platform, and #if is that. Before const and static inline existed, naming a constant or avoiding a call meant a macro.
The preprocessor also supplies predefined macros you will meet constantly: __FILE__, __LINE__, __func__ (technically a compiler-provided identifier, not a macro), __DATE__, and __STDC_VERSION__, which tells you which standard you are compiling against. Logging and assertion macros are built on these, because a function cannot know its caller's file and line while a macro expanded at the call site can.
Now the trouble. Because the preprocessor does not understand C, every guarantee you rely on in C is absent:
- It does not respect scope.
#define count 10renamescounteverywhere in the rest of the translation unit, including a local variable in an unrelated function and a struct member. - It does not respect types. A macro parameter is a chunk of text, not a value of a type, so nothing gets checked.
- It does not evaluate arguments once. The text is substituted wherever the parameter appears, so a macro that mentions its parameter twice evaluates the caller's expression twice.
- Its own arithmetic in
#ifis done in the widest integer types and treats any undefined identifier as0, so a misspelled macro name quietly makes a condition false instead of failing.
The modern habit is to keep the preprocessor to the jobs only it can do: including headers, guarding them, conditional compilation for platform differences, and macros that need __FILE__/__LINE__ or the #/## operators. Everything else is better as real C. Use enum or static const for constants, and static inline for small functions, because those get type checking, respect scope, and are visible to the debugger.
The cost is build time and debuggability. A 40-line file can preprocess into tens of thousands of lines, and an error inside a macro is reported at the expansion site with the macro already expanded. When a macro misbehaves, run cc -E and read the text the compiler is really getting.
Code Examples
/* seeing_the_phases.c
* Inspect the preprocessor's output:
* cc -E seeing_the_phases.c expanded source
* cc -dM -E - < /dev/null every predefined macro
*/
#include <stdio.h>
#define MAX_USERS 64 /* object-like macro: pure text substitution */
/* A macro earns its place here: only a macro can capture the caller's
file and line, because __FILE__ and __LINE__ expand at the call site. */
#define LOG(msg) \
fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, (msg))
int main(void)
{
printf("%d\n", MAX_USERS); /* compiler sees: printf("%d\n", 64); */
LOG("starting up"); /* prints e.g. seeing_the_phases.c:19: starting up */
#if __STDC_VERSION__ >= 201112L /* 201112L is C11 */
puts("compiled as C11 or later");
#else
puts("compiled as an older standard");
#endif
return 0;
}/* The preprocessor ignores scope, which is how "working" code breaks.
* Prefer real C for anything that does not need the preprocessor. */
#include <stdio.h>
#define count 10 /* renames every later use of the identifier */
struct Basket {
int count; /* becomes: int 10; -> syntax error */
};
int main(void)
{
int count = 3; /* becomes: int 10 = 3; -> syntax error */
printf("%d\n", count);
return 0;
}
/* The fix: give the constant a real type and obey scope. */
enum { MAX_COUNT = 10 }; /* integer constant, respects scope */
static const double TAX_RATE = 0.2; /* typed, visible in a debugger */Common Gotchas
A macro name pays no attention to scope
once defined it rewrites that identifier everywhere below it in the translation unit, including struct members and local variables. Reserve SHOUTY_CASE for macros so a reader can tell, and prefer `enum` or `static const` for constants.
`#if` treats an undefined identifier as zero
`#if ENABLE_CACHE` compiles the `#else` branch when you misspell the name or forget to include the header that defines it, with no diagnostic. Turn on `-Wundef`, and use `#if defined(ENABLE_CACHE)` when presence rather than value is the question.
Every macro argument is substituted as text, not as a value
so the argument's own side effects can run more than once, and an unparenthesized argument can bind to the wrong operator. See the macros entry for the parenthesization rules.
Preprocessing is a separate pass, so it cannot see anything the compiler knows
there is no way to ask "is this variable an `int`" or "does this type exist". `_Static_assert` (C11) is the tool for compile-time checks that need type information.