Saturday, January 30, 2016

c++ preprocessor

c preprocessor

When you work on c++ programming, we always start with #include<.....>

Like following

#include <iostream>
#include <string>

int main()
{
}

or if you look at someone else's coding, you have seen the following..

#define PI 3.14

#ifndef OBJECT_H_
     #define OBJECT_H_
#endif

These lines starting with # are preprocessor command.

Before I go further about these commands, let's talk about compiler little bit.

A compiler is not smart and does not understand C++ coding. C++ coding has to be translated into machine language(which is combination of 1 and 0). Compiler does the translation.

Before a compiler translates your c++ code, your code has be processed by a c preprocessor.
You can think the c preprocessor as a text replacer.


Let's look at the following c++ line.

       #include <iostream>
       #define PI 3.14

       using namespace std;

       int main()
      {
               cout << "hello world" ;
               cout << PI ;
      }

The above is very a simple piece of code.
It will print "hello world" and 3.14 in the monitor.
"cout" and "<<" are used to print "hello world"and 3.14.

#include <iostream> is a preprocessor command that add c++ standard library in you code

When a compiler to compile your c++ code, it does not compile the code right away.

Firstly, c++ preprocessor changes your code.

     #include <iostream>
     #define PI 3.14

     using namespace std;
 
     int main()
     {
         { system.out ~~~~~~~}   (operator~~~~~~~`) " hello world" ;
         { system.out ~~~~~~~}   (operator~~~~~~~`) 3.14
     }

strings "cout" and "<<" does not do anything. preprocessor reads these pieces and convert them to meaningful instances.
Whenever, preprocessor find PI, it will change PI to 3.14

Once preprocessor finish changing all instances, compiler compiles your code.


Think a c preprocessor as a tool that helps a compiler to compile your code.

The following is the actual compiling process.

c++ code ----> processed with  c++preprocessor  ----> compiled with compiler -------> executable.


If you think I misunderstand the concept, please feel free to talk to me or leave a comment.