The Analogy: A Find-and-Replace Pass Before the Compiler Wakes Up
Before the compiler sees a single line of your code, a separate tool walks through it doing text substitution. It pastes in the contents of every #include, replaces every macro with its definition, and deletes the branches of #if blocks that do not apply. Only then does the real compiler start work, on a file that may look quite different from the one you wrote.
That tool is the preprocessor, and the important thing about it is what it does not know. It does not know about types, scopes, functions or statements. It moves tokens around. This is why a macro can do things no function can — refer to the file and line of its own call site, or compile itself out of existence entirely — and equally why a badly written macro fails in ways that make no sense until you look at the substituted text.
You can always look. gcc -E main.c prints exactly what the compiler receives, and it is the fastest way to end an argument about what a macro expanded to.
Syntax or Core Structure
#include <stdio.h>
#define MAX_USERS 100
#define PI 3.14159265358979
#define SQUARE(x) ((x) * (x))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define LOG(fmt, ...) printf("[log] " fmt "\n", __VA_ARGS__)
int main(void) {
printf("MAX_USERS = %d\n", MAX_USERS);
printf("area of r=2: %.4f\n", PI * SQUARE(2));
printf("SQUARE(3 + 1) = %d\n", SQUARE(3 + 1));
printf("MIN(7, 4) = %d\n", MIN(7, 4));
LOG("started with %d users", 3);
printf("%s line %d\n", __FILE__, __LINE__);
return 0;
}
Output:
MAX_USERS = 100
area of r=2: 12.5664
SQUARE(3 + 1) = 16
MIN(7, 4) = 4
[log] started with 3 users
main.c line 15
__FILE__ is the path exactly as it was handed to the compiler, and __LINE__ is 15 because that printf is the fifteenth line of the file. Neither could be produced by a function: a function only ever knows where it was written.
SQUARE(3 + 1) giving 16 rather than 7 is entirely down to those inner parentheses. ((x) * (x)) expands to ((3 + 1) * (3 + 1)); the naive x * x would expand to 3 + 1 * 3 + 1, which multiplication-before-addition turns into 7.
The directives worth knowing
| Directive | What it does |
|---|---|
#include "f.h" / <f.h> | pastes the file in; quotes search your project first, angle brackets the system paths |
#define / #undef | create or remove a macro |
#if / #elif / #else / #endif | keep one branch, delete the rest before compiling |
#ifdef X / #ifndef X | shorthand for #if defined(X) / #if !defined(X) |
#error "msg" | stop the build with a message |
#pragma | compiler-specific instruction, e.g. #pragma once |
Because #if runs before compilation, it can only see integer constants and other macros. It cannot evaluate sizeof, cannot see an enum constant, and treats any identifier it does not recognise as 0.
Technical Depth: Text Substitution and Its Consequences
Double evaluation: the flaw a function does not have
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int i = 5, j = 3;
int m = MAX(i++, j); /* expands to ((i++) > (j) ? (i++) : (j)) */
Whichever branch is taken, i++ appears twice in the expansion and may run twice. The macro is perfectly parenthesised and still wrong, because parentheses cannot stop an argument being duplicated. A function evaluates each argument exactly once:
static inline int max_int(int a, int b) { return a > b ? a : b; }
So the rule is: if a plain function will do, write a function. static inline in a header gives you the same absence of call overhead with type checking, single evaluation, and a name a debugger can show you.
| Need | Use |
|---|---|
| A named constant | enum for integers, const for anything else |
| A small computation | static inline function |
| The caller's file or line | macro (nothing else can) |
| Code that must vanish in release builds | macro plus #if |
| A wrapper that works for several types | macro, carefully |
Multi-statement macros need do { } while (0)
/* Broken: the else has nothing to attach to. */
#define RESET(p, n) (p)->count = 0; (p)->total = 0
if (full) RESET(box, 4);
else keep(box); /* error: unexpected else */
/* Correct: one statement, and the trailing semicolon at the call site is natural. */
#define RESET(p, n) \
do { \
(p)->count = 0; \
(p)->total = 0; \
} while (0)
The backslash at the end of each line joins it to the next before anything else happens — and it must be the very last character, since a single trailing space after it breaks the continuation with an error that points at the wrong line. do { ... } while (0) is a single statement that runs once, so it works in every position a statement can appear, including an unbraced if.
Stringify and paste
#define STR(x) #x /* # turns a token into a string literal */
#define XSTR(x) STR(x) /* extra layer expands x first */
#define CONCAT(a, b) a##b /* ## glues two tokens together */
#define VERSION 7
printf("%s %s\n", STR(VERSION), XSTR(VERSION)); /* prints: VERSION 7 */
int CONCAT(user, _count) = 3; /* declares user_count */
# freezes the argument text before expansion, which is why the double layer is needed to stringify a macro's value. Both operators are how test frameworks print the expression that failed, as assert does.
Include guards
#ifndef INVENTORY_H
#define INVENTORY_H
/* declarations */
#endif
Without this, a header included twice — directly and again through another header — defines every struct and typedef twice, which is an error. The guard makes the second inclusion expand to nothing. #pragma once does the same job in one line and is supported by every mainstream compiler, but it is not in the standard; the #ifndef form works everywhere.
Conditional compilation
#if defined(DEBUG) && DEBUG > 1
verify_invariants(state);
#elif defined(DEBUG)
check_bounds(state);
#else
/* nothing in release builds */
#endif
#if __STDC_VERSION__ < 199901L
# error "this code needs C99 or later"
#endif
Set these from the build line — gcc -DDEBUG=2 ... — so one source tree produces different builds. Code inside a false branch is deleted before compilation, so it costs nothing at run time; it is also never checked, which is why a rarely-enabled branch tends to stop compiling without anyone noticing.
Useful predefined names: __FILE__, __LINE__, __DATE__, __TIME__, __STDC_VERSION__, and NDEBUG which switches assert off. __func__ looks like a macro but is a predefined identifier holding the current function's name, so it works inside a function and nowhere else.
Real World Example: A Logging Header With Compile-Time Levels
This is the case where a macro is not a shortcut but the only option: the log has to report the file and line of the call site, and the disabled levels have to disappear from the binary entirely.
/* ---------- logging.h ---------- */
#ifndef LOGGING_H
#define LOGGING_H
#include <stdio.h>
#define LOG_LEVEL_NONE 0
#define LOG_LEVEL_ERROR 1
#define LOG_LEVEL_INFO 2
#define LOG_LEVEL_DEBUG 3
#ifndef LOG_LEVEL /* let the build line override it */
# define LOG_LEVEL LOG_LEVEL_INFO
#endif
#define LOG_AT(level, tag, fmt, ...) \
do { \
if ((level) <= LOG_LEVEL) \
fprintf(stderr, "[%-5s] %s:%d: " fmt "\n", \
tag, __FILE__, __LINE__, __VA_ARGS__); \
} while (0)
#define LOG_ERROR(fmt, ...) LOG_AT(LOG_LEVEL_ERROR, "error", fmt, __VA_ARGS__)
#define LOG_INFO(fmt, ...) LOG_AT(LOG_LEVEL_INFO, "info", fmt, __VA_ARGS__)
#define LOG_DEBUG(fmt, ...) LOG_AT(LOG_LEVEL_DEBUG, "debug", fmt, __VA_ARGS__)
#define ARRAY_LEN(a) (sizeof (a) / sizeof (a)[0])
#endif
/* ---------- main.c ---------- */
#include "logging.h"
int main(void) {
int codes[] = { 12, 7, 40, 3 };
LOG_INFO("checking %zu codes", ARRAY_LEN(codes));
for (size_t i = 0; i < ARRAY_LEN(codes); i++) {
LOG_DEBUG("codes[%zu] = %d", i, codes[i]);
if (codes[i] > 30)
LOG_ERROR("code %d out of range", codes[i]);
}
LOG_INFO("done with %d error(s)", 1);
return 0;
}
Built with no options, LOG_LEVEL defaults to LOG_LEVEL_INFO, so the debug lines are compiled out:
gcc -std=c17 -Wall -Wextra -o app main.c
Output:
[info ] main.c:6: checking 4 codes
[error] main.c:10: code 40 out of range
[info ] main.c:12: done with 1 error(s)
The same source, rebuilt with gcc -std=c17 -DLOG_LEVEL=3 -o app main.c:
Output:
[info ] main.c:6: checking 4 codes
[debug] main.c:8: codes[0] = 12
[debug] main.c:8: codes[1] = 7
[debug] main.c:8: codes[2] = 40
[error] main.c:10: code 40 out of range
[debug] main.c:8: codes[3] = 3
[info ] main.c:12: done with 1 error(s)
Every debug line reports 8 because that is where the call is written, and the error reports 10 — the line numbers come from the call sites, not from inside logging.h. With -DLOG_LEVEL=0 the program prints nothing at all.
Five details are doing real work here:
if ((level) <= LOG_LEVEL)compares two compile-time constants. Any optimiser deletes the whole branch, so a disabled log costs nothing — not even the test — while the source stays readable.do { ... } while (0)keeps it a single statement. Without it,if (x) LOG_ERROR(...); else ...would not compile, and theifinside the macro would silently steal the caller'selse.#ifndef LOG_LEVELgives a default without preventing an override. The build line wins; the header only fills the gap."[%-5s] %s:%d: " fmtrelies on adjacent string literals being joined. Becausefmtmust be a literal, the pieces merge into one format string at compile time — another thing a function could not do.ARRAY_LENis used at the call site, not passed a pointer. It works only where the real array is in scope; inside a function takingint *it would compute a pointer size divided by 4. That limitation is inherent to text substitution, and a comment in the header should say so.
One portability note: __VA_ARGS__ in C99 requires at least one variadic argument, so LOG_INFO("done") with no extra values is a syntax error. Pass a dummy value, add a separate LOG_INFO0, or use C23's __VA_OPT__(,) to make the comma conditional.
Common Mistakes
- Missing parentheses.
#define SQUARE(x) x * xmakesSQUARE(3 + 1)expand to3 + 1 * 3 + 1, which is 7. Wrap every parameter and the whole body:((x) * (x)). - A semicolon in the definition.
#define MAX_USERS 100;turnsint a[MAX_USERS];intoint a[100;];. Object-like macros never end in a semicolon. - Multi-statement macros without
do { } while (0). Two statements separated by a semicolon break any unbracedif, and anifinside a bare macro captures the caller'selse. - Arguments evaluated more than once.
MAX(i++, j)duplicatesi++in the expansion. Parentheses cannot fix this; use astatic inlinefunction instead. - Lowercase macro names that collide. A macro called
maxorminreplaces every occurrence of that word in every file that includes the header, including inside other libraries' declarations. UseSHOUTING_CASEand a project prefix. - A header with no include guard. Included twice — often indirectly — it redefines every struct and
typedef. Add the#ifndefguard to every header, without exception. - Expecting
#ifto understand C.#if sizeof(int) == 4does not work, and an unknown identifier in#ifquietly becomes0, so#if LOG_LEVELwithLOG_LEVELmisspelled reads as false with no warning. Compile with-Wundefto be told. - A typo in an
#ifdefname.#ifdef DEUBGdisables the entire block permanently and nothing complains, because a name that is simply not defined is a legitimate state.
Best Practices
- Reach for
static inlinefirst, and use a macro only when you need the call site's file and line, code that vanishes in release builds, or type-independent text substitution. - Prefer
enumfor related integer constants andconstfor everything else; both are visible to the debugger and obey scope. - Parenthesise every parameter and the full body of every function-like macro.
- Wrap multi-statement macros in
do { ... } while (0), with the backslash as the last character on each line. - Name macros in upper case with a project prefix, and mention in a comment when a macro evaluates an argument more than once.
- Guard every header, and keep
#defines that are only needed by one.cfile inside that file. - Drive conditional compilation from the build line with
-D, provide a default with#ifndef, and build the rarely-enabled configurations in CI so they do not rot. - When a macro misbehaves, run
gcc -Eand read the expansion instead of guessing.
Practice Exercises
- Break a macro and then fix it. Define
#define SQUARE(x) x * xand printSQUARE(3 + 1),SQUARE(2) * SQUARE(2)and10 / SQUARE(2). Predict each result before running, record what you actually get, then add the parentheses and repeat. Confirm your explanation againstgcc -Eoutput for all three expressions. - Demonstrate double evaluation. Write
MAX(a, b)as a macro andmax_intas astatic inlinefunction. Call each withi++whereistarts at 5, printiafterwards, and explain the difference. Then find a case where the macro version also produces the wrong result, not just a wrong side effect. - A three-level assert. Build
check.hwithCHECK(cond)that, whenCHECK_ENABLEDis non-zero, prints the failing condition as text using#, plus__FILE__,__LINE__and__func__, and returns-1from the calling function. Usedo { } while (0)and make it work inside an unbracedif. Verify that with-DCHECK_ENABLED=0the checks vanish, then compare your macro with whatassertfrom<assert.h>does under-DNDEBUG. - A guard, a paste, and a build matrix. Write
shapes.hwith an include guard, and include it twice frommain.cto prove the guard works — then comment the guard out and record the exact error. Add#define DECLARE_PAIR(type, name) type name##_min; type name##_max;and use it to declareint score_min; int score_max;, checking withgcc -Ethat the pasted names are what you intended. Finally build the file with-DLOG_LEVEL=0,=1and=3and confirm each produces the output you predicted.