This blog is under construction

Tuesday, 22 May 2012

What is a Preprocessor?

Preprocessor is nothing but a program which is executed on C source code before the compilation process.  It provides facility to handle named constant, macros and file inclusion.  And it begins with the preprocessor directive hash symbol(#).

     #define SIZE 100

Actually the source program is translated to object code on compilation.  Before the compilation process, preprocessing takes places.  During preprocessing the following operations would take place.

1.  macro substitution
2.  File inclusion
3.  Conditional compilation

Execution of an ordinary C program:
source program -> preprocessing+compilation -> object code-> linking ->executable

How to preprocess a C code?
The following program will give you a clear picture on preprocessing:
jp@jp-VirtualBox:~/cpgms/preprocessor$ cat preprocessor.c
#define SIZE 10

int main() {
    int a = SIZE;
    printf("Value of a: %d\n", a);
    return 0;

In the above program we have defined a macro named SIZE, whose value is 10.  Now we are going to do preprocessing alone for the above program and see the output of it.

gcc -E <program.c>

option 'E' will help us to do preprocessing alone for the C program

jp@jp-VirtualBox:~/cpgms/preprocessor$ gcc -E preprocessor.c
# 1 "preprocessor.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "preprocessor.c"

int main() {
 int a = 10;     => SIZE substituted by 10(macro substitution)
 printf("Value of a: %d\n", a);
 return 0;

No comments:

Post a Comment