How to Write and Compile a C Program in Linux

C is one of the fastest running programming language, a lot of developers start their development journey with C. You can write and compile C in Linux, Windows, and macOS.

Linux is one of the favorite operating systems among developers for its open-source and in-hand tools for development. Node JS, PHP, Python name any programming language, and you can write and run it in Linux.

How to Install and Run Node Js in Linux

Today we look into compiling and running our first C code in Linux from scratch. Before that, make sure to open your terminal using the Ctrl+Alt+T shortcut.

Step 1: Install the build-essential packages

To compile and execute your C program in Linux, you need to install a build-essential package that comes with all required tools.

$ sudo apt install build-essential
build-essential packages
build-essential packages

Sudo users may require to enter a password before the installation begin.

Step 2: Write a basic C Program

After the installation is complete, lets us start writing our first C program from scratch.

Make sure to select your favorite Text Editor. In my case, I am going to use Gedit. Write or copy the below command and paste it into your Text Editor.

How to Copy Paste in Linux Terminal?

#include <stdio.h>
int main() {
   // printf() displays the string inside quotation
   printf("Hello, TREND OCEANS!");
   return 0;
}

Then save the file with any name; just make sure to add the “.c” extension in the end. In my case, it’s “code.c”.

Basic C Program
Basic C Program

Step 3: Compiling the C program with GCC Compiler

To make your application executable, we need to compile our readable code into machine understandable code using GCC compiler.

Syntax:

$ gcc [ProgramName].c -o [OutputProgramName]

Example:

$ gcc code.c -o code

Once the above code is executed, a new file will be created in the same directory.

Compiling C program using GCC Compiler
Compiling C program using GCC Compiler

Step 4: Running the program

Once the executable application is created, use the below code to run.

$ ./code
Hello, TREND OCEANS!%   
Running C Program
Running C Program

Below you can see the output of our basic C program. You can modify further and change the output in something different.

Let me know in the comment section if you successfully executed your first C Program. Facing any issues, drop that too.

Leave a Reply