Preprocessor

A software program that processes the source file before sending it to actual compilation is called preprocessor.

Pictorial Explanation

preprocessor in C

While Processing the source file, the preprocessor replaces header files and macros with defined files and values.

The line which starts with '#' will be processed before the actual compilation starts.




Preprocessor Tasks

Source file inclusion

#include<stdio.h> will be replaced by the original implementation of stdio.h file. Basically, it will remove the #include statement from source code and includes stdio.h file content into the source program.

Macro expansion

#define size 5. Here size is a macro which holds the value 5. Before the compilation starts, the preprocessor will replace size by 5 all over the program.

Conditional compilation

With the help of preprocessor, we can decide which part of the source code should compile and which part of the code should be ignored while compilation. We will discuss conditional compilation in upcoming topics.




Source File - Before Preprocessing

Example

#include<stdio.h> 
#define size 5 

int main()
{
    int i = 0;

    for(i = 0; i < size; i++)
        printf("Hello");

    return 0;
}




After Preprocessing

Example

/* origianl code of stdio.h */   //replaced by preprocessor 

int main()
{
    int i = 0;

    for(i = 0; i < 5; i++)    //size will be replaced by 5 
        printf("Hello");

    return 0;
}

This preprocessed code will be sent to the compiler for further actions.




Useful Resources

https://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html
https://gcc.gnu.org/onlinedocs/cpp/Macros.html
http://ee.hawaii.edu/~tep/EE160/Book/chap3/subsection2.1.3.4.html