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 */
| Directive | Category | What it does |
|---|---|---|
#include | File inclusion | Copies the contents of a header file into your program |
#define | Macro definition | Gives a name to a value or a piece of code |
#undef | Macro definition | Removes a macro so the name can be reused |
#if, #elif, #else, #endif | Conditional compilation | Keeps or removes code based on a constant expression |
#ifdef, #ifndef | Conditional compilation | Keeps code depending on whether a macro exists |
#error | Diagnostic | Stops compilation and prints a message |
#pragma | Compiler control | Special instructions, e.g. #pragma once |
#line | Compiler control | Changes 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
#include <stdio.h>pastes the declarations ofprintfand friends into the file.#define PI 3.14159tells the preprocessor: wherever you seePI, write3.14159.#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.#if DEBUGis true becauseDEBUGis 1, so only the debugprintfstays. The#elsepart is removed before compilation; it is not even compiled.- Change
#define DEBUG 1to0and 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_STUDENTSdefines 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 GREETINGdeletes the macro, so#ifdef GREETINGis false and the#elsepart 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
#ifis never compiled, so it adds nothing to the program. gcc -E file.cshows the code after preprocessing.-DNAME=valueon the gcc command line works like#define NAME value.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
#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 = 10 | MAX becomes = 10 | Write #define MAX 10 |
Missing #endif | Error: unterminated #if | Close every #if, #ifdef and #ifndef |
Space before the bracket: #define AREA (r) ... | Becomes an object macro named AREA | No space between the name and ( |
Using a variable in #if | The preprocessor doesn't know variables; it treats the name as 0 | Use only macros and constants in #if |
Preprocessor Directives Practice Questions
- What is the C preprocessor, and when does it run?
- Why don't preprocessor directives end with a semicolon?
- What is the difference between
#include <stdio.h>and#include "stdio.h"? - Which directive removes a macro definition?
- Which gcc option shows the preprocessed output?
Show answers
- It is a program that processes source code (includes, macros, conditions) before compilation; it runs first in the build.
- They are instructions to the preprocessor, not C statements; a semicolon would become part of the text.
- Angle brackets search the system include folders; quotes search the current/project folder first, then the system folders.
#undef.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)
-
When does the preprocessor run?
A) After linking B) Before compilation C) While the program runs D) After compilation
-
Every preprocessor directive begins with:
A)
$B)@C)#D)// -
Which directive stops compilation with a message?
A)
#pragmaB)#errorC)#undefD)#line -
What does
gcc -E prog.cdo?A) Runs the program B) Shows only errors C) Shows the preprocessed code D) Creates an object file
-
#ifndef Xmeans:A) If X is defined B) If X is not defined C) If X is zero D) Define X
Show answers
- B: before compilation.
- C:
#. - B:
#error. - C: it shows the preprocessed code.
- 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
| Preprocessor | Runs before compilation, works on text |
|---|---|
| Directive | Line starting with #, no semicolon |
| #include | Pastes a header file |
| #define / #undef | Create / remove a macro |
| #if, #ifdef, #ifndef | Conditional compilation |
| #error | Stops compilation with a message |
| gcc -E | Shows 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.