1.4 – How to execute a C program in Linux

by subbu on July 25, 2013

Executing C program on Linux system:

Every flavor of Linux is preloaded with a C compiler called gcc. gcc is a C compiler developed by GNU as the open source. It is the implementation of ANSI C standards. Executing a C program on terminal is different from executing in an IDE. Here we need to compile and execute the C program in separate  steps.

Step1: Go to the Linux terminal by selecting applications – Accessories – Terminal

linux terminal

Step2: Open the text editor with the program name. Make sure that the file name must have .c file extension. Different flavors of Linux provide different text editors like “vi”. Here we are using a text editor “gedit” of Ubuntu Linux.

$gedit hello.c

opening gedit

Step3: Write the program in the text editor

int main()
printf("Hello World\n");
return 0;

program in gedit

Close the editor by selecting File – Quit to come back to the terminal

Step4: Compile the program using the C compiler gcc. The compiler translates the source code and produces equalant object code with the name “a.out”. It can be executed by giving its name directly at terminal.

$gcc hello.c

executing C on linux

ls : command to show the list of files in the current directory

./ : To specify that the file is in current directory

Here there is a problem with the object file a.out because the output of gcc for every C program is a.out. The object code of current program overwrites the object code of previous program compiled. If we want to execute the previous program then need to be recompiled.

We can produce different object files for different programs by sending parameter –o to gcc while compiling.

The general form of –o parameter is

Syntax of gcc

$gcc  -o  hello  hello.c

executing with gcc

Here option –o generated the object file with the name “hello” instead “a.out”. It is executed by giving its name at terminal prompt. Like wise we can generate different object files for different C programs.

Previous post:

Next post: