Monday, April 14, 2014

preprocessor explanation with example

There are three basic phases that are important in programming e.g. C- programming. The phases are Pre-processing, compiling and Linking, only two phases are required: compiler and linking.

prog.càPREPROCESSORà
temp.càCOMPILERà
prog.objàLINKERàprog.exe

A preprocessor basically reads line by line from the input and replicates the line to the output. If the line is a preprocessing statement, then it performs the preprocessing directives. All preprocessing statements in C begin with the # symbol and are at the beginning of a line. The operations of taking the input file and generating the output file, pre-processed file, is called pre-processing.

PRE-PROCESSOR          à    COMPILER          à      LINKER
(reads program line by line)      (identify the uncoded       (search for libraries files)
                                            functions like printf,scanf)     

Example

#include<stdio.h> // pre-processor
#define Max 10  // pre-processor
int main(void)
{
int i;
for(i=0;i<Max;i++)
printf(“Hello World!”);
return 0;
}

From above example #include and #define defines header files. Pre-processor reads line by line. Its starts from main() reading line by line, generates the output file as i.e. temp.c is pre-processor output file.
Compiler takes pre-processor output file as input for compiler and generated object file i.e. prog.obj. This object file contains machine code generated from the program you wrote in your original C file. It does not as of yet contain code for functions such as printf. Since the code for printf is not in your code, the object file contains symbol printf.   Usually a special file extension(obj) is given to an object file.
Think of an object file as a partially complete program with missing blocks of code (ie the code for printf).  During the next phase called the Link Phase, it is the linker program that is responsible to find the missing code "printf" and link it(bind it) to the object file generated by the compiler. The compiler also removes all comments from the input file.
The linker is a process that accepts as input object files and libraries to produce the final executable program. Libraries contain object code. This object code in turn contains functions. In the link phase the object code from the compile phase is bound to the missing function code such as printf. The function printf is located in the standard input and output libraries. The final executable now contains all the necessary code for execution.



1 comment: