PRE-PROCESSOR DIRECTIVES

Vertika Shukla
2 min readJul 15, 2018

--

See there are certain programs that need to be pre-processed before compiling. Pre-processor directives are used to indicate the compiler that which programs need to be pre-processed. Pre-processor directives can be placed anywhere in the program. Wherever compiler finds the (# hash) symbol, it comes to know that it has to be pre-processed. We can place these pre processor directives anywhere in our program.

There are 3 main types of pre-processor directives:

  1. File Inclusion
  2. Conditional Compilation
  3. Macros

Let us now learn about each of these directives in details.

  • File Inclusion: When compiler gets this pre-processor directive it includes the file in the source code.
  • Header File or Standard files: These files contains definition of pre-defined I/O functions, string operations, mathematical operations etc. Different header files are used for different functions. For example, for mathematical computation we use ‘math.h’, for standard I/O funuctions are in ‘iostream.h’, for string operations we use ‘string.h’.

Syntax:

#include<file_name>

here’<’ and ‘>’ specifies the file to be included and ‘file_name’ is the name of the file.

  • Conditional Compilation: If we wanna compile only some specific part of program we need to put some conditions. Conditional compilation directives helps to do this. This can be done with the help of two pre-processing commands ‘ifdef‘ and ‘endif‘.

Syntax:

ifdef macro_name

statement1;

statement2;

statementN;

endif;

  • Macros: With Macros we refer to the piece of code which is given some specific name so as to replace the name with the actual piece of code. This happens whenever compiler encounter the Macro name in the program it replaces it with the actual code. We use #define to use define macro. Example:

#include<iostream>

#define X 4

int main()

{

for(i=0;i<X;i++)

{ cout<<i<<“\n”; }

return 0; }

Output:

0

1

2

3

Word ‘X’ in the program is replaced by 4 whenever the compiler executes ‘X’.

‘X’ -> Macro template

‘4’ -> Macro expansion

Note: There is no need to use ‘;’ at the end of macro definition.

That’s all for Pre-processor Directives

Thanks for reading this article. Be sure to clap & recommend as much as you can and also share with your friends. It means a lot to me.

For more about programming, follow me and CodeSharp , so you’ll get notified when we write new posts.

Also, Let’s become friends on Twitter, Linkedin and Facebook.

--

--