How to Compile and Run C Program in Linux

Compile and Run C Program in Linux

C is a general-purpose programming language, best suited for system programming. It is developed by Dennis Ritchie at Bell Lab to write utility programs for Unix Operating System. Later, the Unix kernel itself was implemented in C Language. Low-level access to memory, simple keywords, fast and efficient execution features, made C one of the most used programming languages.

Learning a C is a must if you are starting your career as a programmer. You only need a text editor to write a C Program and GCC or Clang compiler to compile the program.

In this article, we will see how to write and compile C Program.

Compile and Run C Program in Linux

GCC compiler is part of the GNU Compiler Collection that includes front ends for C, C++, Objective-C, Fortran, Ada, Go, and D, as well as libraries for these languages (libstdc++,…). It was originally written as the compiler for the GNU operating system.

1. Install GCC Compiler

GCC is part of the build-essential package for Ubuntu/Debian-based Distros and the Development Tools package for Fedora/Centos/Rehat-based Distros. It should already be available. If that is not the case, first you need to install GCC.

Use the below command to install the build-essential package on Ubuntu/Debian-based distros and

sudo apt-get install build-essential

Development Tools on Fedora/Centos/Rehat-based distros.

yum groupinstall 'Development Tools'

Use the below command to verify the installation,

~$ gcc -v
~$ whereis gcc
gcc: /usr/bin/gcc /usr/lib/gcc /usr/share/man/man1/gcc.1.gz
~$ which gcc
/usr/bin/gcc

2. Write C Program

Any text editor like vi, nano, or even VIM is fine to write a C program. Here, I  am going to create a classic hello world program using a nano editor. Open the terminal and start the editor.

nano hello-world.c

C program listing,

#include <stdio.h>
int main()
{
printf("/n Hello World ");
return 0;
}

Where,

  • studio.h – standard input output header file
  • printf – command to print a message

3. Compile C Program with GCC Compiler

Next, compile the program using the GCC compiler. The syntax is gcc <file name> -o <output file>. In our case

gcc hello-world.c -o hello-world

This generates a hello-world binary file.

4. Run C Program

Now, just Type ./<output name> to run the program.

~$ ./hello-world

The output of the program ( shown below),

c program output when run on linux terminal
c program output

Summary

A text editor and GCC compiler are the basic tools you need to start writing and compiling c programs. Go ahead and start learning c.

I hope this small article was helpful. Please share and subscribe.

Share This:
Scroll to Top