Reading history

C Preprocessor: #define, #include, #if and Macros

8 min read 4 views

See what the C preprocessor does before compiling: #define, macros, #include, header guards, #if switches, and the # and ## operators.

Every line in C that begins with # is an order for a helper program called the preprocessor, not for the compiler. The preprocessor runs first and acts like an automatic copy-editor: it copies header files into your code, swaps names for the values you gave them, and deletes any block you told it to skip. Knowing what it does explains many puzzling bugs.

In this lesson you will learn

  • What the preprocessor does and how to see its output
  • How to define constants and function-like macros with #define
  • Why macros need extra brackets
  • How #include and header guards work
  • How to switch code on and off with #if and #ifdef
  • The # and ## operators, and built-in macros like __LINE__

What Happens Before Compiling

Building a C program happens in stages: preprocess, compile, assemble and link (see C compilation process). The preprocessor works on plain text. It knows nothing about types or variables. It simply follows its directives and hands the edited text to the compiler.

You can stop after this first stage with gcc -E and read what the compiler will actually receive. Here is a small file and the command that shows its preprocessed form:

#define VAT_RATE 15
#define PRICE_WITH_VAT(p) ((p) + (p) * VAT_RATE / 100)

int final_price = PRICE_WITH_VAT(200);   /* the compiler never sees the macro */
gcc -E -P shop.c

Output

int final_price = ((200) + (200) * 15 / 100);

The macro names have disappeared. The compiler only ever sees the expanded text. (The -P option hides the line-number markers the preprocessor normally adds.) When a macro misbehaves, gcc -E is the fastest way to see why.

DirectiveWhat it does
#includePastes in the contents of another file
#define / #undefCreates or removes a macro
#if, #elif, #else, #endifKeeps or drops code based on a condition
#ifdef, #ifndefChecks whether a macro has been defined
#errorStops the build with a message
#pragmaPasses a special instruction to the compiler
#lineChanges the line number reported in errors (mainly for code generators)

#define for Named Constants

The simplest macro gives a value a name. Every later use of the name is replaced by the value, word for word.

#include <stdio.h>

#define MAX_STUDENTS 40
#define SCHOOL "Rajshahi Model School"

int main(void) {
    int marks[MAX_STUDENTS];
    printf("%s keeps marks for up to %d students\n", SCHOOL, MAX_STUDENTS);
    printf("The array uses %zu bytes\n", sizeof marks);
    return 0;
}

Output

Rajshahi Model School keeps marks for up to 40 students
The array uses 160 bytes

By convention, macro names use CAPITALS so readers can tell them apart from variables. Note that there is no = and no semicolon. Writing #define MAX_STUDENTS 40; would paste the semicolon into every place the name is used.

#define or const?

A const int has a type, obeys scope rules and shows up in the debugger, so it is often the safer choice. #define is still needed for array sizes in older C code, for values used in #if, and for text pasted into strings. See Constants in C for a full comparison.

Function-Like Macros and Why They Need Brackets

A macro can take arguments, like a function. But it is still only text replacement, and that causes surprises.

#include <stdio.h>

#define SQUARE_BAD(x)  x * x
#define SQUARE(x)      ((x) * (x))

int main(void) {
    printf("SQUARE_BAD(2 + 3) = %d\n", SQUARE_BAD(2 + 3));
    printf("SQUARE(2 + 3)     = %d\n", SQUARE(2 + 3));
    printf("100 / SQUARE_BAD(5) = %d\n", 100 / SQUARE_BAD(5));
    printf("100 / SQUARE(5)     = %d\n", 100 / SQUARE(5));
    return 0;
}

Output

SQUARE_BAD(2 + 3) = 11
SQUARE(2 + 3)     = 25
100 / SQUARE_BAD(5) = 100
100 / SQUARE(5)     = 4

SQUARE_BAD(2 + 3) expands to 2 + 3 * 2 + 3, which is 11, not 25. And 100 / SQUARE_BAD(5) becomes 100 / 5 * 5, which C reads as (100 / 5) * 5 = 100. The fixed version wraps each argument and the whole body in brackets.

Brackets cannot fix one more problem: an argument with a side effect is evaluated as many times as it appears. SQUARE(i++) expands to ((i++) * (i++)), which changes i twice in one expression. That is undefined behaviour in C, and the result can differ between compilers. If an argument might have side effects, use a static inline function instead of a macro.

#include and Header Guards

#include copies a whole file into yours at that spot.

  • #include <stdio.h> with angle brackets searches the system’s include folders. Use it for standard library headers.
  • #include "student.h" with quotes searches your project folder first. Use it for your own headers.

If two files both include student.h, its contents could be pasted twice, causing “redefinition” errors. A header guard prevents this:

/* student.h */
#ifndef STUDENT_H
#define STUDENT_H

struct student {
    char name[50];
    int roll;
};

void print_student(const struct student *s);

#endif /* STUDENT_H */

The first time the file is included, STUDENT_H is not defined, so the contents are kept and the name gets defined. Any later include skips everything up to #endif. Most compilers also accept the shorter #pragma once, though it is not part of the C standard. More in Header Files in C.

Switching Code On and Off with #if

Conditional directives decide which lines reach the compiler at all. A common use is debugging output that you can remove with a single change.

#include <stdio.h>

#define DEBUG 1
#define VERSION_MAJOR 2

int main(void) {
    int total = 0;
    for (int day = 1; day <= 3; day++) {
        total += day * 100;
#if DEBUG
        printf("[debug] line %d: day %d, total %d\n", __LINE__, day, total);
#endif
    }
    printf("Total sales: %d taka\n", total);

#if VERSION_MAJOR >= 2
    printf("Using the new report format\n");
#else
    printf("Using the old report format\n");
#endif
    return 0;
}

Output

[debug] line 11: day 1, total 100
[debug] line 11: day 2, total 300
[debug] line 11: day 3, total 600
Total sales: 600 taka
Using the new report format

Change #define DEBUG 1 to 0 and the debug lines vanish from the compiled program; they cost nothing at run time. You can also set the value from the command line instead of editing the file: gcc -DDEBUG=0 sales.c.

  • #ifdef NAME is true if NAME is defined at all, even as 0.
  • #if NAME checks the value. Undefined names count as 0.
  • Platform checks such as #ifdef _WIN32 let one file build on Windows and Linux.

The # and ## Operators

Inside a macro, # turns an argument into a string, and ## glues two tokens into one name.

#include <stdio.h>

#define TO_TEXT(x)        #x
#define SHOW_INT(var)     printf(#var " = %d\n", var)
#define MAKE_NAME(a, b)   a##b

int main(void) {
    int MAKE_NAME(score, _2026) = 88;    /* creates a variable named score_2026 */
    int marks = 72;

    puts(TO_TEXT(Hello from the preprocessor));
    SHOW_INT(marks);
    SHOW_INT(score_2026);
    return 0;
}

Output

Hello from the preprocessor
marks = 72
score_2026 = 88

SHOW_INT(marks) prints both the variable’s name and its value, which is handy for quick debugging. MAKE_NAME(score, _2026) builds the identifier score_2026. Use ## sparingly: generated names are hard to search for.

Built-in Macros

MacroGives you
__LINE__The current line number (an int)
__FILE__The current file name (a string)
__DATE__, __TIME__When the file was compiled
__STDC_VERSION__The C standard in use, such as 201112L for C11

__func__, which gives the current function’s name, looks similar but is supplied by the compiler, not the preprocessor.

#error and #pragma

#if __STDC_VERSION__ < 201112L
#error "This program needs a C11 compiler"
#endif

#pragma once   /* header guard shortcut, supported by GCC, Clang and MSVC */

#error stops the build early with a clear message instead of a confusing error later. #pragma lines are compiler-specific; a compiler ignores pragmas it does not recognise.

Common Mistakes

  1. A semicolon at the end of #define. It gets pasted everywhere the macro is used.
  2. Missing brackets in function-like macros. Bracket every argument and the whole body.
  3. Arguments with side effects. MAX(a++, b) may increment a twice. Use an inline function.
  4. A space before the bracket. #define SQUARE (x) ... defines an object-like macro whose text starts with (x).
  5. Forgetting header guards. Leads to “redefinition” errors in multi-file projects.
  6. Using macros where a function would do. Functions have types, show up in the debugger and are evaluated once per argument.

Practice Exercises

Exercise 1. With #define DOUBLE(x) x + x, what does 3 * DOUBLE(4) give, and how do you fix the macro?

Show answer

It expands to 3 * 4 + 4 = 16, not 24. Fix it as #define DOUBLE(x) ((x) + (x)).

Exercise 2. Write a macro MAX(a, b) that returns the larger of two values safely bracketed.

Show answer
#define MAX(a, b) ((a) > (b) ? (a) : (b))

It still evaluates the larger argument twice, so do not pass expressions like i++.

Exercise 3. Which command shows your program after preprocessing, without compiling it?

Show answer

gcc -E program.c (add -P to hide line markers).

Frequently Asked Questions

Is the preprocessor part of the compiler?

It is the first stage of the build. GCC and Clang run it automatically, but it works on text only and could be used on files that are not C at all.

Do macros make programs faster?

Rarely today. Modern compilers inline small functions automatically, so a static inline function is usually as fast as a macro and much safer.

What is the difference between #if and #ifdef?

#ifdef X only checks whether X is defined. #if X checks its value, so #define X 0 passes #ifdef but fails #if.

Should I use #pragma once or header guards?

Both work with all major compilers. Classic #ifndef guards are part of the C standard, so they are the most portable choice.

Summary

  • The preprocessor edits your source text before compiling; gcc -E shows the result.
  • #define creates constants and macros by plain text replacement.
  • Bracket every macro argument and the whole body; avoid side-effect arguments.
  • #include pastes files; header guards stop double inclusion.
  • #if and #ifdef include or remove code at build time.
  • # makes a string from an argument, ## joins tokens.
Lessons are also marked complete when you click Next.