Skip to content
StudyFame

Preprocessor Directives in C

Before your C program is compiled, a helper program called the preprocessor reads it first. It pastes in header files, replaces names like PI with their values and removes code you don't want. The lines that give it orders start with # and are called preprocessor directives.

In this lesson you will learn what the preprocessor does, every common directive (#include, #define, #undef, #if, #ifdef, #error, #pragma) and how to see the preprocessed code yourself.

What You Will Learn

  • What the C preprocessor is and when it runs.
  • The rules every directive follows.
  • The list of preprocessor directives and what each one does.
  • How #define, #undef, #if and #ifdef change your program.
  • How to view the preprocessed output with gcc -E.
  • Common mistakes with directives.

Preprocessor Directives in C Explained

Exam definition: The C preprocessor is a program that processes the source code before compilation. A preprocessor directive is a line that begins with # and gives an instruction to the preprocessor, such as including a file (#include), defining a macro (#define) or compiling code only when a condition is true (#if). Directives are not C statements, so they do not end with a semicolon.

Memory trick: Think of the preprocessor as an editor who prepares your essay before the teacher (the compiler) reads it. The editor pastes in chapters (#include), replaces short forms with full words (#define) and cuts paragraphs you marked "not needed" (#if). The teacher only sees the edited copy.

Rules for writing directives

  • A directive starts with # as the first non-space character of the line.
  • One directive per line. To continue a long directive, end the line with a backslash \.
  • No semicolon at the end (a semicolon would become part of the replacement text).
  • Directives can appear anywhere in the file, but they are usually written at the top.

Syntax: List of Preprocessor Directives in C

#include <stdio.h>        /* paste a system header file          */
#include "myfile.h"       /* paste your own header file          */
#define NAME value        /* define a macro                      */
#undef NAME               /* remove a macro definition           */
#if expression            /* compile the next part if true       */
#elif expression          /* else-if                             */
#else                     /* otherwise                           */
#endif                    /* end of the #if block                */
#ifdef NAME               /* compile if NAME is defined          */
#ifndef NAME              /* compile if NAME is NOT defined      */
#error message            /* stop compilation with a message     */
#pragma name              /* compiler-specific instruction       */
DirectiveCategoryWhat it does
#includeFile inclusionCopies the contents of a header file into your program
#defineMacro definitionGives a name to a value or a piece of code
#undefMacro definitionRemoves a macro so the name can be reused
#if, #elif, #else, #endifConditional compilationKeeps or removes code based on a constant expression
#ifdef, #ifndefConditional compilationKeeps code depending on whether a macro exists
#errorDiagnosticStops compilation and prints a message
#pragmaCompiler controlSpecial instructions, e.g. #pragma once
#lineCompiler controlChanges the line number and file name reported in errors

Example 1: #include, #define and #if Together

#include <stdio.h>

#define PI 3.14159
#define SITE "StudyFame"
#define AREA(r) (PI * (r) * (r))
#define DEBUG 1

int main(void)
{
    double r = 2.0;

    printf("Welcome to %s\n", SITE);
    printf("Area of circle with r = %.1f is %.2f\n", r, AREA(r));

#if DEBUG
    printf("[debug] r = %.1f\n", r);
#else
    printf("Debug messages are off\n");
#endif

    return 0;
}

Output

Welcome to StudyFame
Area of circle with r = 2.0 is 12.57
[debug] r = 2.0

Code Explanation

  1. #include <stdio.h> pastes the declarations of printf and friends into the file.
  2. #define PI 3.14159 tells the preprocessor: wherever you see PI, write 3.14159.
  3. #define AREA(r) (PI * (r) * (r)) is a function-like macro. AREA(r) becomes (3.14159 * (r) * (r)), so the area is 3.14159 × 4 = 12.57.
  4. #if DEBUG is true because DEBUG is 1, so only the debug printf stays. The #else part is removed before compilation; it is not even compiled.
  5. Change #define DEBUG 1 to 0 and the program prints "Debug messages are off" instead.

How the Preprocessor Works

Building a C program has four stages. The preprocessor is the first one:

program.c  --(1) preprocessor-->  program.i   (pure C, no # lines)
program.i  --(2) compiler    -->  program.s   (assembly code)
program.s  --(3) assembler   -->  program.o   (machine code)
program.o  --(4) linker      -->  program     (executable)

You can stop after stage 1 and look at the result with gcc -E program.c. For Example 1, the end of the output looks like this (the thousands of lines from stdio.h are skipped):

int main(void)
{
    double r = 2.0;

    printf("Welcome to %s\n", "StudyFame");
    printf("Area of circle with r = %.1f is %.2f\n", r, (3.14159 * (r) * (r)));

    printf("[debug] r = %.1f\n", r);

    return 0;
}

Notice: every macro name is replaced, the #else branch is gone and no # line is left. This is the code the compiler really sees.

Example 2: #ifndef, #undef and #ifdef

#include <stdio.h>

#ifndef MAX_STUDENTS          /* give a default only if not already set */
#define MAX_STUDENTS 3
#endif

#define GREETING "Hello"

int main(void)
{
    int marks[MAX_STUDENTS] = {78, 91, 66};
    int i, total = 0;

    printf("%s! Class size: %d\n", GREETING, MAX_STUDENTS);
    for (i = 0; i < MAX_STUDENTS; i++)
        total += marks[i];
    printf("Average: %.2f\n", total / (double)MAX_STUDENTS);

#undef GREETING
#ifdef GREETING
    printf("GREETING is still defined\n");
#else
    printf("GREETING was removed with #undef\n");
#endif

    return 0;
}

Output

Hello! Class size: 3
Average: 78.33
GREETING was removed with #undef
  • #ifndef MAX_STUDENTS defines a default value. You can override it while compiling: gcc -DMAX_STUDENTS=5 prog.c (then change the array values too).
  • A macro can be used as an array size because it is replaced by the constant 3 before compilation.
  • #undef GREETING deletes the macro, so #ifdef GREETING is false and the #else part is compiled.

Important Points to Remember

  • The preprocessor runs before the compiler and works on text, not on C values or types.
  • Every directive starts with # and needs no semicolon.
  • <file.h> searches system folders; "file.h" searches your project folder first.
  • Code removed by #if is never compiled, so it adds nothing to the program.
  • gcc -E file.c shows the code after preprocessing.
  • -DNAME=value on the gcc command line works like #define NAME value.

Common Mistakes Beginners Make

MistakeWhat happensFix
#define PI 3.14;The semicolon is pasted too: x = PI * 2; becomes x = 3.14; * 2;Never end a #define with a semicolon
#define MAX = 10MAX becomes = 10Write #define MAX 10
Missing #endifError: unterminated #ifClose every #if, #ifdef and #ifndef
Space before the bracket: #define AREA (r) ...Becomes an object macro named AREANo space between the name and (
Using a variable in #ifThe preprocessor doesn't know variables; it treats the name as 0Use only macros and constants in #if

Preprocessor Directives Practice Questions

  1. What is the C preprocessor, and when does it run?
  2. Why don't preprocessor directives end with a semicolon?
  3. What is the difference between #include <stdio.h> and #include "stdio.h"?
  4. Which directive removes a macro definition?
  5. Which gcc option shows the preprocessed output?
Show answers
  1. It is a program that processes source code (includes, macros, conditions) before compilation; it runs first in the build.
  2. They are instructions to the preprocessor, not C statements; a semicolon would become part of the text.
  3. Angle brackets search the system include folders; quotes search the current/project folder first, then the system folders.
  4. #undef.
  5. gcc -E.

Coding Exercise

Define macros APP_NAME ("Marks Calculator"), PASS_MARK (40) and IS_PASS(m) that gives 1 if m is at least PASS_MARK. Print the app name, then check the marks 35, 40 and 72. Add a #ifndef VERSION block that defines VERSION as 1 and print it.

Show solution
#include <stdio.h>

#define APP_NAME "Marks Calculator"
#define PASS_MARK 40
#define IS_PASS(m) ((m) >= PASS_MARK)

#ifndef VERSION
#define VERSION 1
#endif

int main(void)
{
    int marks[] = {35, 40, 72};
    int i;

    printf("%s v%d\n", APP_NAME, VERSION);
    for (i = 0; i < 3; i++)
        printf("%d: %s\n", marks[i], IS_PASS(marks[i]) ? "Pass" : "Fail");
    return 0;
}
Marks Calculator v1
35: Fail
40: Pass
72: Pass

Quick Quiz: Preprocessor Directives (MCQ)

  1. When does the preprocessor run?

    A) After linking   B) Before compilation   C) While the program runs   D) After compilation

  2. Every preprocessor directive begins with:

    A) $   B) @   C) #   D) //

  3. Which directive stops compilation with a message?

    A) #pragma   B) #error   C) #undef   D) #line

  4. What does gcc -E prog.c do?

    A) Runs the program   B) Shows only errors   C) Shows the preprocessed code   D) Creates an object file

  5. #ifndef X means:

    A) If X is defined   B) If X is not defined   C) If X is zero   D) Define X

Show answers
  1. B: before compilation.
  2. C: #.
  3. B: #error.
  4. C: it shows the preprocessed code.
  5. B: if X is not defined.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

PreprocessorRuns before compilation, works on text
DirectiveLine starting with #, no semicolon
#includePastes a header file
#define / #undefCreate / remove a macro
#if, #ifdef, #ifndefConditional compilation
#errorStops compilation with a message
gcc -EShows preprocessed output

Frequently asked questions

What is a preprocessor directive in C?
A line starting with # that tells the preprocessor to do something before compilation, like including a file or defining a macro.
Is #include a C statement?
No. It is a preprocessor directive, so it has no semicolon and is handled before the compiler sees the code.
Name four types of preprocessor directives.
File inclusion (#include), macro definition (#define), conditional compilation (#if) and others (#error, #pragma, #line).

Remember

  • Preprocessor = the editor: paste, replace, cut.
  • No semicolon after a directive.

Next Topic

Next lesson: Macros in C. You will learn object-like and function-like macros, multi-line macros and the # and ## operators.