The preprocessor in C++ is used for processing the code before it is compiled by the compiler. It does many tasks such as including files, conditional compilation, using macros, etc. The preprocessor also allows the developers to select which portions of code should be included or excluded.
The code processed by the preprocessor is called expanded code and is generally saved with a ".i" file extension.
Preprocessor Directives in C++
In C++, the preprocessor directives are special commands that are used to instruct the preprocessor. It begins with a '#' symbol and tells the preprocessor to the modify source code before compilation. There are different preprocessor directives in C++ for different operations.
The below table lists frequently used preprocessor directives:
Directive | Purpose |
|---|---|
#include | Links a header file in the source code. |
#define | Creates a symbolic or macro constant. |
#undef | Deletes a macro that has already been defined. |
#ifdef / #ifndef | Compilation that is conditional on the presence or absence of a macro. |
#if / #elif / #else / #endif | Compilation that is conditional based on some expression. |
#error | Halts the compilation process and produces an error notice. |
#warning | During compilation, a warning notice is shown. |
#pragma | Provide the compiler specific instructions. |
1. #include
The #include preprocessor directive is used to include the contents of one file into the current one, use the #include directive. Header files are often included using this.
Syntax
#include <header_file_name>
or
#include "header_file_name"
The first one includes the header files from the source directory, whereas the second one includes the file from directory the source file is currently in.
2. #define
The #define preprocessor directive is used to define macros. Macro names are symbolic and may be used to represent constant values or short bits of code. Using #define preprocessor makes our code more readable and easily maintainable as we can replace numbers and code snippets with a meaningful name.
Syntax
#define macro_name value