Have you ever thought about how Computer knows the commands you are writing? Have you seen that if you type wrong syntax or data types, then it shows an error? Well, it’s all due to the preprocessor.
For example, the commands like printf, scanf, int, char, float, cout, cin, try, catch, return, >>, <<, ?, if, else etc. All these are defined in header files like #include.
In C/C++ the preprocessor replaces macros with their expansion and is used to make it possible to write one large program using multiple sources. The preprocessor takes the original code and replaces the placeholders by the actual value, so that the new code can be further processed by an editor, a compiler, or an interpreter.
The preprocessor programs provide directives that tell the compiler to preprocess the source code before compiling. There are 4 main types of preprocessors, these are
- File Inclusion
- Conditional Compilation
- Other Directives
Macros are defined as a piece of code given some name to a variable for later use. Whenever the compiler sees this, it replaces the code with defined variables and values. It is used by #define directives. For example: #define value 5.
You can also pass it with arguments like: #define value(1,a)(2*a)
File Inclusion: This preprocessor directive tells the compiler to include a file in the source code program. The user can include two types of files:
- Header Files: Such as printf(), scanf(), cout, or cin, etc
- User defined Files: When more and more functionalities are added in program, then it is advice to divide it into smaller files, hence User-defined files can be be included by #include “filename”.
- Conditional Compilation: These are used for Conditional Statements which are required according to User’s requirement. They mainly used for ifelse, endif, etc.
- Other Directive: The other directives are not commonly used. The #undef directive is used to make program undefined for the previously defined variables or macro. The other type of directive is #pragma startup and #pragma exit. It helps in specifying the functions that are needed to run before program startup and program exit().