Thursday 28 February 2013

Step By Step Compilation of C Programs in Linux


  In Linux a C program is compiled using GCC (GNU Compiler Collection) Compiler System. If the name of the program is a.c, the program is compiled using the following command.

gcc a.c

The above command will generate an executable file named a.out.

gcc a.c -o pgm

The above command will generate an executable file named pgm.

But before generating the executable file the following actions are performed  by the gcc utitility.
  • From the C program file a.c a file a.i is obtained after preprocessing.
  • From the preprocessor output file a.i the assembler generates a.s which contains the assembler code.
  • From the assembly file a.s the object file a.o is obtained after compilation.
  • From the object file a.o the executable file pgm is obtained after linking.

If required gcc allows you to do these steps separately. 


Consider the program named a.c shown below.

#include<stdio.h>

#define MAX 10

int main(int argc, char **argv)
{
    int i;
    i=MAX;
    printf("\ni = %d\n",i);
    return 0;
}

  • The following command will generate the preprocessed file a.i from the c program file a.c.
gcc -E a.c -o a.i

Figure Below Shows the Preprocessed File a.i


  • The following command will generate the assembly file a.s from the preprocessed file a.i.

gcc -S a.i

Figure Below Shows the Assembly File a.s


  • The following command will generate the object file a.o from the assembly file a.s.
gcc -c a.s
  • The following command will finally generate the executable file pgm from the object file a.o.
gcc a.o -o pgm

  • The executable file pgm can be run by using the following command.
./pgm

Figure Below Shows All the Files Generated in the Process
 

No comments:

Post a Comment