A preprocessor directive in C is a special instruction to the C compiler that is processed before the actual compilation begins. Preprocessor directives are processed by the preprocessor, a tool that runs before the C compiler starts its job. These directives begin with a hash symbol (#
) and are used to handle various tasks such as file inclusion, macro expansion, conditional compilation, and more.
The most commonly used preprocessor directives in C include:
#include
: Used to include header files.#define
: Used to define constants or macros.#ifdef
,#ifndef
,#endif
: Used for conditional compilation.#pragma
: Used for special compiler instructions.
#include
Directive
The #include
directive is used to include the contents of another file into the current C program. This file is typically a header file that contains function declarations, macro definitions, and other code that can be shared across multiple source files. There are two ways to use #include
:
-
Angle Brackets (
< >
): When the#include
directive is used with angle brackets, such as#include <stdio.h>
, the preprocessor looks for the header file in the standard library directories. This is used for including system-level header files or libraries that come with the C compiler.Example:
#include <stdio.h>
This includes thestdio.h
header file, which provides standard input/output functions likeprintf
andscanf
. -
Double Quotes (
" "
): When#include
is used with double quotes, such as#include "myheader.h"
, the preprocessor looks for the header file in the current directory (or the directory specified by the developer) before searching the system directories.Example:
#include “myheader.h”
The #include
directive helps separate the interface of a module from its implementation, which improves code organization, reusability, and maintainability. By including header files in multiple source files, you can share common function prototypes, constants, and data type definitions without rewriting the same code multiple times.