Chapter 30 of 37

Preprocessor Directives

Before the C compiler actually compiles your program, another part of the compilation process called the preprocessor handles certain instructions.

These instructions are called preprocessor directives.

What is a Preprocessor Directive?

A preprocessor directive is an instruction beginning with # that is processed before the actual compilation of a C program.

For example:

#include <stdio.h>

Here, #include is a preprocessor directive.

It tells the preprocessor to include the contents of the stdio.h header file.


Common Preprocessor Directives

Some commonly used directives are:

Directive

Purpose

#include

Includes a header file

#define

Defines a macro

#undef

Removes a macro definition

#if

Conditional compilation

#ifdef

Checks whether a macro is defined

#ifndef

Checks whether a macro is not defined

#else

Alternative conditional block

#elif

Additional condition

#endif

Ends conditional compilation


#include

#include is used to include header files.

#include <stdio.h>

This gives us access to functions such as printf() and scanf().

We can also include our own header file:

#include "myheader.h"

#define

#define is used to create macros.

#define PI 3.14159

Now we can use:

printf("%f", PI);

The preprocessor replaces occurrences of PI with 3.14159 before compilation.

Macros can also accept arguments:

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

Then:

int result = SQUARE(5);

We will study macros in more detail separately.


Conditional Compilation

Preprocessor directives can also control which parts of the code are compiled.

For example:

#ifdef DEBUG
    printf("Debug mode");
#endif

The code inside #ifdef is compiled only if DEBUG has been defined.

Another common pattern is:

#ifndef HEADER_H
#define HEADER_H

// Header contents

#endif

This technique is commonly used in header guards to prevent a header file from being included multiple times.

Preprocessor vs Compiler

The basic process can be understood like this:

C Source Code
      ↓
  Preprocessor
      ↓
Processed Code
      ↓
   Compiler
      ↓
 Machine Code

So, preprocessor directives are handled before the main compilation stage.

In Simple Words

Preprocessor directives are special # instructions that are processed before the C code is compiled.

The most important ones to remember are:

#include → Include files

#define → Define macros

#ifdef / #ifndef → Conditional compilation

These directives are especially useful when working with header files, macros, configuration, and larger C projects.