As the name signifies, pre-processor directives are instructions given to compiler which it has to run before main code compilation will begin. You must be frequently seeing #include as the top of most C++ program codes. It is nothing but a pre-processor directive to tell compiler that definitions of certain classes, function and objects have to be read before using them in the main program. Overall following major types of pre-processor directives are there.
- File Inclusion
- Macro Definition
- Conditional Compilation
- Other types
File Inclusion
This is the most common directive you come across everyday in most programs. Examples are –
#inlude <iostream> //To use things like cout, cin, endl etc.
#include <string.h> //To include c style string related functions.
#include <math.h> //To include things like sqrt, pow, sin, cos etc.
Macro definition
This is a way in C++ which allows replacement of some values in program with their pre-defined values. For e.g.
#define PI 3.1416
double circum=2*PI*r;
after compilation pass it will become
double circum=2*3.1416*r;
So if PI occurs in my formula, it will be replaced by value 3.1416 . For this replacement nature of activity this directive is also called pre-processor macros.
One may have formula style macro definition like –
#define velocity(u,a,t) u+a*t
int v=velocity(5,2,3);
The above code will apply the velocity formula as given in the define and fill value of 11 in the v named variable.
Conditions Compilation
This allows to publish multiple version of executable codes of program based on conditions set using the #define directive. For e.g.
#define Zone 1
#ifdef Zone
char msg[]="Zone information in use";
#else
char msg[]="Zone information not in use";
#endif
In the above example c style string msg will be set to Zone information in use as Zone macro has been defined above it. Based on this setting a program may take a different path of compilation.
Other directives
There many other pre-processor directives also for different purposes for e.g.
#undef (For undefining a pre-defined macro)
#pragma (For turning on and off some compilation features)
#error (to show diagnostic error messages while compilation)
The standard documentation for C++ pre-processor directives can be seen here