C: The Preprocessor
The preprocessor is like reviewing blueprints before construction — before actual compilation begins, it expands macros, inserts header files, and prunes conditional branches, then hands the result to the compiler.
1. Preprocessing Pipeline
The C compilation process: source file → preprocessing → compilation → assembly → linking. The preprocessor runs before compilation, handling all directives that start with #.
You can use the -E flag to see only the preprocessed output:
gcc -E hello.c -o hello.i
2. #include Header Files
#include inserts the contents of the specified file verbatim at the current position.
(1) Two Forms
#include <stdio.h>
#include "myheader.h"
< >searches in system directories" "searches the current directory first, then system directories
" " for your own headers and < > for standard library headers — this is the convention.
(2) Common Standard Headers
| Header | Main Content |
|---|---|
stdio.h |
Input/output functions |
stdlib.h |
Memory allocation, type conversion, random numbers |
string.h |
String operations |
math.h |
Math functions |
ctype.h |
Character classification |
assert.h |
Assert macro |
3. #define Macro Definitions
(1) Object-Like Macros
Define named constants:
// Preprocessor directive
#define PI 3.14159265
// Preprocessor directive
#define MAX_SIZE 100
// Preprocessor directive
#define AUTHOR "WebTutorial"
// Variable declaration
double area = PI * 10 * 10;
int arr[MAX_SIZE];
// I/O operation
printf("Author: %s\n", AUTHOR);
(2) Function-Like Macros
Macros with parameters look like functions but are text substitutions:
// Preprocessor directive
#define SQUARE(x) ((x) * (x))
// Preprocessor directive
#define MAX(a, b) ((a) > (b) ? (a) : (b))
// Variable declaration
int s = SQUARE(5);
// Variable declaration
int m = MAX(10, 20);
25
20
4. Macro Pitfalls and Parentheses
(1) Pitfall 1: Missing Parentheses Cause Precedence Errors
// Preprocessor directive
#define DOUBLE(x) x + x
int result = DOUBLE(3) * 2;
After expansion this becomes 3 + 3 * 2, which yields 9 instead of the expected 12. Correct version:
// Preprocessor directive
#define DOUBLE(x) ((x) + (x))
(2) Pitfall 2: Parameters with Side Effects
// Preprocessor directive
#define SQUARE(x) ((x) * (x))
// Variable declaration
int n = 3;
// Variable declaration
int s = SQUARE(n++);
After expansion this becomes ((n++) * (n++)), incrementing n twice — undefined behavior.
i++, func()) as macro arguments. Use inline functions or real functions instead.
(3) Pitfall 3: Macros in if-else Branches
// Preprocessor directive
#define CHECK(cond) if (cond) printf("yes\n")
// Conditional check
if (flag)
CHECK(x);
// Else branch
else
do_something();
After expansion, the else matches the macro's inner if, not the outer one — the classic dangling else problem. Wrap with do { ... } while(0):
// Preprocessor directive
#define CHECK(cond) do { if (cond) printf("yes\n"); } while(0)
▶ Example
▶ Try it Yourselfmax: 20
square: 25
after swap: x=20 y=10
double max: 3.5
5. Conditional Compilation
Conditional compilation lets the same source code produce different compiled output under different conditions. It's widely used for cross-platform support, debug switches, and feature trimming.
(1) #if / #elif / #else / #endif
// Preprocessor directive
#define PLATFORM 2
#if PLATFORM == 1
const char *os = "Windows";
#elif PLATFORM == 2
const char *os = "Linux";
#else
const char *os = "Unknown";
// Preprocessor directive
#endif
// I/O operation
printf("Platform: %s\n", os);
Platform: Linux
(2) #ifdef / #ifndef
#ifdef checks whether a macro is defined; #ifndef checks whether it is not defined.
// Preprocessor directive
#define DEBUG
// Preprocessor directive
#ifdef DEBUG
// I/O operation
printf("Debug mode: x=%d\n", x);
// Preprocessor directive
#endif
// Preprocessor directive
#ifndef BUFFER_SIZE
// Preprocessor directive
#define BUFFER_SIZE 256
// Preprocessor directive
#endif
#ifdef DEBUG is equivalent to #if defined(DEBUG), and #ifndef is equivalent to #if !defined(...).
(3) Debug Switch
// Preprocessor directive
#ifdef DEBUG
// Preprocessor directive
#define LOG(msg) printf("[DEBUG] %s:%d %s\n", __FILE__, __LINE__, msg)
#else
// Preprocessor directive
#define LOG(msg)
// Preprocessor directive
#endif
LOG("Variable initialized");
Compile with -DDEBUG to enable logging; without it, the program stays silent:
gcc -DDEBUG -o myapp myapp.c
▶ Example
▶ Try it YourselfAdvanced features enabled
Concise output mode
6. Predefined Macros
The C standard predefines several useful macros:
| Macro | Meaning |
|---|---|
__FILE__ |
Current source file name |
__LINE__ |
Current line number |
__DATE__ |
Compilation date |
__TIME__ |
Compilation time |
__func__ |
Current function name (C99) |
__STDC__ |
Whether conforming to ANSI C standard |
// I/O operation
printf("File: %s\n", __FILE__);
// I/O operation
printf("Line: %d\n", __LINE__);
// I/O operation
printf("Date: %s\n", __DATE__);
// I/O operation
printf("Time: %s\n", __TIME__);
// I/O operation
printf("Function: %s\n", __func__);
File: main.c
Line: 5
Date: Jun 25 2026
Time: 14:30:00
Function: main
7. #undef to Cancel a Macro
#undef cancels a previous macro definition:
// Preprocessor directive
#define MAX_SIZE 100
// I/O operation
printf("%d\n", MAX_SIZE);
#undef MAX_SIZE
After #undef, MAX_SIZE is no longer a macro and can be redefined or used as a normal identifier.
▶ Example 3: Conditional Compilation with Include Guards
▶ Try it Yourself// main.c — compile with -DDEBUG to see LOG output
#include <stdio.h>
#include "math_utils.h"
int main() {
int x = 10, y = 20;
LOG("Starting program");
printf("MAX(%d, %d) = %d\n", x, y, MAX(x, y));
printf("MIN(%d, %d) = %d\n", x, y, MIN(x, y));
LOG("Done");
return 0;
}
编译(带 DEBUG):
gcc -DDEBUG main.c -o main && ./main输出:TEXT[DEBUG] Starting program MAX(10, 20) = 20 MIN(10, 20) = 10 [DEBUG] Done
❓ FAQ
#ifndef HEADER_NAME, #define HEADER_NAME, code, then #endif. This is absolutely required for compile correctness.do { ... } while(0) macro can be used as a single statement inside if (cond) MACRO(); else ... without breaking. The if (1) { ... } else trick also makes the macro behave like a single statement. Both are hacks for C's lack of statement-expression guarantees.__builtin_expect intrinsic, which tells the compiler which branch is expected to be taken more often. likely(x) = __builtin_expect(!!(x), 1) tells the compiler x is probably true, optimizing instruction layout for the common case. This is purely a hint — no runtime branch prediction change.#include <file.h> searches system/include paths first (where standard library headers live). #include "file.h" searches the current file's directory first, then falls back to system paths. Use <> for standard library and third-party headers; use "" for your own project headers.#define FOO(x) bar(x); would expand to bar(42);; (double semicolon) or worse, break if used inside if (cond) FOO(x); else.... The do-while(0) pattern mentioned earlier solves this elegantly.#if defined(FOO) is more flexible because it supports logical operators: #if defined(FOO) && !defined(BAR). #ifdef can only check a single macro name. Use #if defined for anything beyond a simple single-check.📖 Summary
#includeinserts header file contents into the source;< >searches system directories," "searches the current directory#definedefines object-like macros (constant substitution) and function-like macros (parameterized text substitution)- Macro parameters must be parenthesized, and the entire macro expression should be parenthesized too, to avoid precedence traps
- Never pass expressions with side effects as macro arguments
- Conditional compilation with
#if/#ifdef/#ifndefenables cross-platform support, debug switches, and feature trimming - Predefined macros like
__FILE__,__LINE__,__DATE__are useful for logging and debugging
📝 Exercises
- Define two versions of a SQUARE macro — one with parentheses and one without. Test both with
SQUARE(2+3)and observe the result difference - Use
#ifdef DEBUGto implement a logging macroLOG(fmt, ...)that outputs the file name and line number in DEBUG mode and produces no output otherwise - Use conditional compilation to implement cross-platform printing: print "Windows platform" on Windows, "Linux platform" on Linux, using
#if defined(_WIN32)to detect the platform