Friday 15 April 2016

How to run C program in Linux?

C language was developed by Dennis Ritchie in 1969 to 1973. In beginning, C was developed as system programming language for Linux. C language is used for Linux kernel, libraries and all of its supporting tools.

Step:-1 Creating .c file


Open gedit and write C program.
File name:- hello.c

#include<stdio.h>
int main()
{
          printf(“Hello Tycoons!!!”);
          return 0;
}


Step:-2 Open Terminal for run C program


Open Terminal window and then locate file location of c file.
Write following command for compile c program.

gcc hello.c –o hello

Note: Here we have used –o command for creating user define name object file, whatever name given after –o command will known as our object file. By default compiler will create a.out named object file.

Write following command for run c program.

./hello


Output


Hello Tycoons!!!

Actually Compiler will perform several phases for complete compilation of c program.
There are four phases.

  1. Preprocessing
  2. Compilation
  3. Assembly
  4. Linking

Let we perform all phases manually for same code.

1)    Preprocessing


For compilation of C program preprocessing is first step. In this phase, compiler will read header file, expanding macros and insert content of header file into program text. Preprocessing directives are #define, #include etc. #include contain header file. #define is known as macro.

cpp hello.c > hello.i

Here .c extension file is translated into .i extension file. .i extension file will contain source code and expanding macros.

2)    Compilation


In this phase compilation procedure will perform. Here .i extension file will translated into .s file. This .s file will contain assembly code.

gcc -S hello.i

Note: Here –S command will translate preprocessing code into assembly code without creating object file.

3)    Assembly


In this phase, Assembly code will translate into machine code. Here machine language code is contained in object file with extension .o.

as hello.s -o hello.o


4)  Linking


The final compilation phase will links object file to produce executable file.

ld -dynamic-linker /lib/ld-linux.so.2 /usr/lib/crt1.o /usr/lib/crti.o /usr/lib/crtn.o hello.o /usr/lib/gcc/i586-suse-linux/4.8/crtbegin.o -L /usr/lib/gcc/i586-suse-linux/4.8/ -lgcc -lgcc_eh -lc -lgcc -lgcc_eh /usr/lib/gcc/i586-suse-linux/4.8/crtend.o -o hello

Write following command for run executable file.

./hello


Output:



Hello Tycoons!!!

No comments:

Post a Comment