A Hello World C program on Linux

By | 01/09/2012

The C language has very close relation with Linux operating system. Most of the Linux kernel code is written in C language. On the user space side, most of the commands and utilities are written in C language. So one of the very first thing one should learn as part of Linux development is to write, compile and execute a hello world C program on Linux.

In this article, we will understand how to write, compile and run a hello world C program on Linux in 3 easy steps.

A Hello World C program on Linux

1. Writing a hello world C program

Consider the following source code :

#include<stdio.h>

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

The above source code is of a basic program that prints “Hello World”. Please note that in Linux, a C program can be written in any graphical text editor like ‘gedit’ or a command line editor like ‘vi’. Lets save the above code in a file named helloworld.c

2. Compiling the Hello World program

As the source code is in place, the next step is to compile the source code. A compiler is used to compile source code on any platform. On Linux the most popular C compiler is ‘gcc’. This compiler comes by default loaded with almost all of the Linux distributions. FYI, I use Linux Mint.

Any-ways, Lets open the Linux shell and compile our program.

Run the following command in the directory where you have saved the helloworld.c file.

$ gcc -Wall helloworld.c -o helloworld

The above gcc command compiles the source code (and Links the object file) to produce an executable named ‘helloworld’ in the same directory as helloworld.c file. The flag -o is used to specify the output executable file name. If -o is not used then gcc names ‘a.out’ as the output executable. The flag -Wall is used to turn on all types of warnings while compiling the code.

As already discussed, the output of above command is an executable named ‘helloworld’.

3. Run the executable

To run the executable produced in above step, use the following command :

$./helloworld

The reason for using a ./ before the executable name is to tell the shell environment that the executable ‘helloworld’ resides in the current directory.

The above command should produce the following output :

Hello World

So this way a basic C program is written, compiled and executed on Linux.

Leave a Reply

Your email address will not be published. Required fields are marked *