C Program Compilation Steps

download C Program Compilation Steps

of 46

description

c language course

Transcript of C Program Compilation Steps

C Program Compilation StepsYou compile c program and get executables. Have you ever wondered what happens during compilation process and how c program gets converted to executable?In this module we will learn what are the stages involved in c program compilation using gcc on Linux.Normally C program building process involves four stages to get executable (.exe)1. Preprocessing2. Compilation3. Assembly4. Linking The following Figure shows the steps involved in the process of building the C program starting from the preprocessing until the loading of the executable image into the memory for program running.

Compilation with gcc with different options-E Preprocess only; do not compile, assemble or link-S Compile only; do not assemble or link-c Compile and assemble, but do not link-o Place the output into We will use below hello.c program to expain all the 4 phases#include //Line 1#define MAX_AGE 21 //Line 2int main(){printf( "Maximum age : %d ",MAX_AGE); //Line 5}

1. PreprocessingThis is the very first stage through which a source code passes. In this stage the following tasks are done:1. Macro substitution2. Comments are stripped off3. Expansion of the included filesTo understand preprocessing better, you can compile the above hello.c program using flag E with gcc. This will generate the preprocessed hello.i Example:>gcc -E hello.c -o hello.i//hello.i file content# 1 "hello.c"# 1 ""# 1 ""# 1 "hello.c"# 1 "/usr/include/stdio.h" 1 3 4# 28 "/usr/include/stdio.h" 3 4Truncated some textextern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__));# 918 "/usr/include/stdio.h" 3 4# 2 "hello.c" 2int main(){printf( "Maximum age : %d ",21);}

In above code (hello.i) you can see macros are substituted with its value (MA_AGE with 21 in printf statement), comments are stripped off (//Line 1, //Line 2 and //Line 5)and libraries are expanded()2.CompilationCompilation is the second pass. It takes the output of the preprocessor (hello.i) and generates assembler source code (hello.s)> gcc -S hello.i -o hello.s//hello.s file content.file "hello.c".section .rodata.LC0:.string "Maximum age : %d ".text.globl main.type main, @functionmain:.LFB0:.cfi_startprocpushq %rbp.cfi_def_cfa_offset 16movq %rsp, %rbp.cfi_offset 6, -16.cfi_def_cfa_register 6movl $.LC0, %eaxmovl $21, %esimovq %rax, %rdimovl $0, %eaxcall printfleave.cfi_def_cfa 7, 8ret.cfi_endproc.LFE0:.size main, .-main.ident "GCC: (GNU) 4.4.2 20091027 (Red Hat 4.4.2-7)".section .note.GNU-stack,"",@progbits

Above code is assembly code which assembler can understand and generate machine code.3. AssemblyAssembly is the third stage of compilation. It takes the assembly source code (hello.s) and produces an assembly listing with offsets. The assembler output is stored in an object file (hello.o)>gcc -c hello.s -o hello.oSince the output of this stage is a machine level file (hello.o). So we cannot view the content of it. If you still try to open the hello.o and view it, youll see something that is totally not readable//hello.o file content^?ELF^B^A^A^@^@^@^@^@^@^@^@^@^A^@>^@^A^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@@^A^@^@^@^@^@^@^@^@^@^@@^@^@^@^@^@@^@^M^@^@UH^@^@^@^@^U^@^@^@H^@^@^@^@^@^@^@^@^@^@^@Maximum age :%d^@^@GCC:GNU)4.4.220091027(RedHat4.4.2-7)^@^@^T^@^@^@^@^@^@^@^AzR^@^Ax^P^A^[^L^G^H^A^@^@^\^@^@^@^\^@^@^@^@^@^@^@^]^@^@^@^@A^N^PC^B^M^FX^L^G^H^@^@^@^@.symtab^@.strtab^@.shstrtab^@.rela.text^@.data^@.bss^@.rodata^@.comment^@.note.GNU-stack^@.rela.eh_frame^@^@^@^@^@^@^@^@^@^@^@^

By looking at above code only thing we can explain is ELF (executable and linkable format). This is a relatively new format for machine level object files and executable that are produced by gcc.4. Linking Linking is the final stage of compilation. It takes one or more object files or libraries as input and combines them to produce a single executable file (hello.exe). In doing so, it resolves references to external symbols, assigns final addresses to procedures/functions and variables, and revises code and data to reflect new addresses (a process called relocation).> gcc hello.o -o hello./helloMaximum age : 21Now you know c program compilation steps (Preprocessing, Compiling, Assembly, and Linking). There is lot more things to explain in liking phase.Your First C ProgramIn previous two sections we have learnt how to setup c environment and steps in c program compilation. Now we are going to learn how to write a simple C program.Type the following program into your favorite editor//C simple program #include> 1 ;Lets assume x=65, So x>>1 will shift each bit of x (0100 0001) by 1 bit to right and left most bit is filled with zero or one.if left most bit is 0 then filled with 0, if left most bit is 1 then filled with 1. See below diagram

Bit-wise Negate "~" OperatorIt is also called one's complement of a number. On taking one's complement of a number, all 1's present in the number are changed to 0's and all 0's are changed to 1's.For example :1's complement of 0011 0111 is 1100 1000.Special: comma, sizeof Operators in CLets discuss few special operator supported in C. This includes comma operator, sizeof operator, pointer operators (& and *) and member selection operators (. and ->). Pointer operators will be covered while discussing pointer and member selection operators will be covered with structure and unions.Comma Operator in CComma operator represented by comma ( , ) accepts two operands. It is used to combined two or more statement into single statement. We can write compact statement using this operator. The statements separated by comma operator are executed one by one from left to right. it has least precedence during expression evaluation.Example:int x=1;int y=x+1;int z=x+y;Above three statements can be combined using comma operatorint x=1, y=x+1, z=x+y; /* It will be evaluated from left to right */

Now what will the output of below program?#includevoid main( ){int x,y,z;z = (x=10, y=30, x+y);printf( "z=%d", z ) ;}

If your answer was 40 then you are correct. lets see how it has been calculated. First 10 is copied to x, then 20 is copied to y and after that x+y is calculated and finally result is stored in z.sizeof() Operatorsizeof() operator returns number of bytes occupied by variable or constant in the memory.The size of operator works on variables, constants and even on data typessizeof(operand);For Example:sizeof(char) 1 bytesizeof(int) 4 bytesDon't be surprised if you get other result for above example because size of datatype is machine dependent.Decision Control in CWe have seen the common decision control structures in C1. If Else control2. Nested If3. If Else If LadderLets discuss each of these in detail with some real world Examples!If Else Control Statement in CSyntax:if(condition){----;statements set1; // Compound statements----;}else{----;statements set2;----;}

If the condition Evaluates to True then set1 statements are EXECUTED and set2 are NOT executed. if the condition is False then statements set1 are NOT executed and set2 inside the else block are EXECUTED.Single Statement:If there is only one statement inside the if or else block the braces "{ }" can be removed.Syntax:if (condition) statement;else:statement2;

Note 1: Zero is False and any non zero value is treated as True in C.Note 2:Multiple Statements are technically called Compound Statements.Example of If in C:#includeint main(){int var1=0;if (var1 < 10){printf("Inside If Condition\n");printf("2nd statement inside If Condition\n");}else{printf("Inside Else Condition\n");printf("2nd statement inside Else Condition\n");}}

For Single Statement the If block could be written as:if (var1 < 10)printf("Inside If Condition\n");elseprintf("Inside Else Condition\n");

Be careful with these single statements:int var1=10;if (var1 != 10)printf("Statement1");printf("Statement2 Not under if block");

Here only "statement1" is under if block, the Statement2 is not under if block and is executed irrespective of the result of the condition var1!=10.Nested If in CA nested if means placing one or more if statements inside another if statement.Syntax of Nested If in Cif(condition1){//statementset1if(condition2){ //statementset2} else // executed if condition3 is false{//statementset3}}else // executed if condition1 is false{// statementset4}

If Condition1 is true, execute statementset1 and then check if condition2 is true, if yes execute statementset2 also, else execute statementset3.If Condition1 is false execute statementset4.Example of Nested If in Cint i=10,j=20;if(i==10){if(j==20){printf("i=10 and y=20");}}

i=10 and y=20 is printed only if both the if condition evaluates to true.

if-else-if Ladder in CThis decision control structure is used when you have multiple conditions and you have to execute the corresponding statements based on which condition is true.Syntax:if(boolean_expression1){//... StatementSet1}else if (boolean_expression2){// StatementSet2}else if (boolean_expression3){// StatementSet3}// any number of else ifelse{//Last StatementSet}

Example:int a =10;if( a>10)printf("a>10");else if( a>20)printf("a>20");else if(a