What is the preprocessor in C++?
The preprocessor is a directive given to the compiler before the compilation phase of the program. The compiler executes these directives before compiling the code into an executable file.
Take a look at the image below:
The image above illustrates that, after the Preprocessing phase, all preprocessor directives are replaced with C++ code in the source code file. Then, the compilation begins.
Structure of a Preprocessor directive
A preprocessor directive begins with the # character – only white-space characters can come before a preprocessor directive on a line. The directives may have additional
#example_directive token1 token2
Common Preprocessor directives
The following are some preprocessor directives that beginner programmers encounter.
#include Preprocessor directive
The structure of the #include directive is:
#include filename
The filename is the name of a standard library (if it is enclosed in ankle brackets <>)
or a custom C++ file (if it is enclosed in double quotes "").
When the compiler encounters the #include directive, it replaces the line with the contents of the file.
#define Preprocessor directive
The #define directive is used to define Macros and Symbolic Constants. The structure of the #define directive is:
#define identifier replacement-text
In the preprocessing phase, the compiler replaces any occurrences of identifier that don’t occur as part of a replacement-text.
#error Preprocessor directive
The structure of the #error directive is:
#error tokens
Here, the tokens are characters separated by white-spaces.
In the preprocessing phase, if the compiler encounters the
#errorpreprocessor directive, it terminates the compilation and prints thetokensas error on the standard output.
Conditional inclusion Preprocessor directives
Conditional inclusion Preprocessor directives consist of the following:
#if#ifdef#ifndef#elif#else#endif
These directives instruct the compiler to conditionally include parts of the source code for compilation. The following code provides an example:
#include <iostream>using namespace std;#define PI 3.142int main() {#ifdef PIcout << "The value of PI is: " << PI << endl;#elsecout << "PI is not defined!" << endl;#endifreturn 0;}
The code above outputs The value of PI is: 3.142 because #ifdef PI evaluates to true. This happens since PI is defined as 3.142 on line 4.
Note: line 10 does not get compiled because the
#elseclause is ignored by the compiler when#ifdef PIevaluates totrue.
Free Resources