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.

Quick summary#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

A simple #define, substituted before compilingC: edit and run

MAX_RETRIES is substituted as plain text before compilation even starts — the compiler never even sees the name MAX_RETRIES, only the number 3.

Careful:This course's "Try it" sandbox has two specific quirks worth knowing: #define substitution here is naive and can also rewrite matching words inside string literals elsewhere in your code (prefer const for simple constants, as earlier lessons do), and #ifdef/#ifndef conditional compilation is not supported by this particular sandbox at all, so the listing below is reference-only. Real compilers do not have either limitation.
DirectiveWhat it does
#include Paste in a system header file's contents
#define NAME valueReplace NAME with value, everywhere, before compiling
#ifdef / #ifndefCompile a block of code only if a macro is (or is not) defined
Conditional compilation with #ifdef (reference only — not runnable in this sandbox)
#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

A function-like macroC: edit and run

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?