How to Compile and Run C Program in Linux

x


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

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

What is C Langauge?

C is a general-purpose programming language best suited for system programming. Developed by Dennis Ritchie at Bell Lab to write utility program for Unix Operating System, later Unix kernel itself 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.

Compile and Run C Program in Linux

You need GCC compile and a text editor to write and compile C Program.

Note:- Below instructions are tested on Ubuntu 20.04.

1. Install GCC Compiler

The GNU Compiler Collection 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.

GCC in part of build-essential package Ubuntu/Debian based Linux Distros and Development Tools package for Fedora/Centos/Rehat based Linux Distros. It should already available in your Linux operating system.

But if it is not available, use the below command to install GCC on the respective Linux distro.

Ubuntu/Debian,

sudo apt-get install build-essential

Fedora/Centos/Rehat,

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

You can use any text editor like vi, nano, or even VIM to write a C program in Linux.

Here, I will create a classic hello-world. c program using a nano editor. Open the Ubuntu terminal and run the below command to start the nano 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

We already installed the GCC Compiler. Now, run the below command on the terminal to compile the c program using GCC.

This generates a hello-world binary file as shown below.

gcc hello-world.c -o hello-world

4. Run C Program

C Compiler generates the binary file of the program. Just Type ./<name> to run the c program on Linux. In our case,

~$ ./hello-world

The output of the program ( shown below),

c program output

Summary

A text editor and GCC compiler are the only 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.