C Preprocessor & Macros
Before the compiler proper sees your code, a separate step called the preprocessor runs over it. The preprocessor handles every line that starts with #. It does not understand C — it works on text: pasting in files, replacing names, and keeping or removing blocks of code. You have used it since your first program, in #include <stdio.h>.
| Directive | Purpose |
|---|---|
#include |
insert the contents of another file |
#define / #undef |
define / remove a macro |
#if, #ifdef, #ifndef, #elif, #else, #endif |
conditional compilation |
#error |
stop compilation with a message |
#pragma |
compiler-specific instructions (e.g. #pragma once) |
#include
#include copies a whole file into the current one. Angle brackets search the system's include directories; double quotes search the current project first:
#include <stdio.h> // standard library header
#include "student.h" // your own headerObject-like macros
#define NAME replacement replaces every later occurrence of NAME with replacement. It is commonly used for constants:
#include <stdio.h>
#define MAX_STUDENTS 30
#define SCHOOL "Riverside High"
#define TAX_RATE 0.08
int main(void) {
int enrolled = 27;
printf("%s: %d/%d students\n", SCHOOL, enrolled, MAX_STUDENTS);
printf("Places left: %d\n", MAX_STUDENTS - enrolled);
printf("Tax on 250: %.2f\n", 250 * TAX_RATE);
return 0;
}Riverside High: 27/30 students
Places left: 3
Tax on 250: 20.00
Function-like macros
A macro can take parameters. It still works by text substitution, which is why the parameters and the whole body should be wrapped in parentheses:
#include <stdio.h>
#define SQUARE_BAD(x) x * x
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define ARRAY_LEN(arr) (sizeof(arr) / sizeof((arr)[0]))
int main(void) {
printf("SQUARE_BAD(2 + 3) = %d\n", SQUARE_BAD(2 + 3)); // 2 + 3 * 2 + 3
printf("SQUARE(2 + 3) = %d\n", SQUARE(2 + 3)); // ((2 + 3) * (2 + 3))
printf("MAX(4, 9) = %d\n", MAX(4, 9));
printf("MAX(2.5, 1.5) = %.1f\n", MAX(2.5, 1.5)); // works for any type
int data[] = {5, 8, 13, 21};
printf("ARRAY_LEN(data) = %zu\n", ARRAY_LEN(data));
return 0;
}SQUARE_BAD(2 + 3) = 11
SQUARE(2 + 3) = 25
MAX(4, 9) = 9
MAX(2.5, 1.5) = 2.5
ARRAY_LEN(data) = 4
SQUARE_BAD(2 + 3) expands to 2 + 3 * 2 + 3, which is 11 because of operator precedence. The parenthesised version is correct. Even so, macro arguments can be evaluated more than once (MAX(i++, j) increments i twice), so for typed helpers an inline function is often the better choice (see C Inline Functions).
Stringizing and token pasting
Two special operators work only inside macros:
#paramturns an argument into a string literal.a ## bglues two tokens together into one.
#include <stdio.h>
#define SHOW(expr) printf("%s = %d\n", #expr, (expr))
#define MAKE_VAR(name, n) int name##n = n
int main(void) {
int width = 6, height = 4;
SHOW(width * height);
SHOW(width + height * 2);
MAKE_VAR(level, 3); // becomes: int level3 = 3;
printf("level3 = %d\n", level3);
return 0;
}width * height = 24
width + height * 2 = 14
level3 = 3
SHOW is a handy debugging helper: it prints the expression's source text next to its value.
Predefined macros
The compiler defines some macros for you:
#include <stdio.h>
void report(void) {
printf("in function %s\n", __func__);
}
int main(void) {
printf("line %d\n", __LINE__);
printf("C standard: %ld\n", __STDC_VERSION__);
report();
return 0;
}line 8
C standard: 201710
in function report
__LINE__ is the current line number and __STDC_VERSION__ identifies the C standard (201710 means C17). __func__ is technically a predefined identifier rather than a macro, but it is used the same way. Other useful ones are __FILE__ (the source file name), __DATE__ and __TIME__ (when the program was compiled — so they change every build).
Conditional compilation
#if, #ifdef and friends include or remove code before compilation. This is used for debug output, platform-specific code and feature switches:
#include <stdio.h>
#define DEBUG 1
#define VERSION 3
int main(void) {
int total = 0;
for (int i = 1; i <= 4; i++) {
total += i * i;
#if DEBUG
printf("[debug] i=%d total=%d\n", i, total);
#endif
}
printf("total = %d\n", total);
#if VERSION >= 3
printf("new report format\n");
#else
printf("old report format\n");
#endif
#ifdef _WIN32
printf("Windows build\n");
#else
printf("non-Windows build\n");
#endif
return 0;
}[debug] i=1 total=1
[debug] i=2 total=5
[debug] i=3 total=14
[debug] i=4 total=30
total = 30
new report format
non-Windows build
Change DEBUG to 0 and the debug lines are not just skipped — they are not even compiled. Macros can also be defined from the command line: gcc -DDEBUG=1 prog.c.
Include guards
If a header is included twice (often indirectly), its declarations would appear twice and could cause errors. An include guard makes the second inclusion empty:
// point.h
#ifndef POINT_H
#define POINT_H
typedef struct { int x, y; } Point;
Point point_add(Point a, Point b);
#endifThe first time, POINT_H is not defined, so the contents are kept and POINT_H gets defined. Every later #include "point.h" finds it defined and skips everything. Most compilers also support the shorter, non-standard #pragma once.
Tip: To see what the preprocessor produces, run
gcc -E prog.c. It prints the code exactly as the compiler receives it — great for debugging confusing macros.
Test yourself
When does the preprocessor run?
- After linking
- Before the compiler translates the code
- While the program runs
- Only in debug builds
With #define DOUBLE(x) x + x, what is DOUBLE(3) * 2?
- 12
- 9
- 6
- 18
What is the purpose of an include guard (#ifndef X_H / #define X_H / #endif)?
- To speed up the program
- To prevent a header's contents from being processed twice
- To hide functions from other files
- To mark the header as optional