How to write and run C programs in Linux

C is one of the oldest, most widely used programming languages ​​in the world. It has been used to develop countless applications, from operating systems to embedded devices.

C is one of the oldest, most widely used programming languages ​​in the world. It has been used to develop countless applications, from operating systems to embedded devices. Even today, many developers still rely on C for its versatility and reliability as a programming language.

Install C Compiler (GCC) on Linux

The steps and commands mentioned in this article are on Ubuntu 22.04 LTS system, but it also works the same on other versions like Ubuntu 20.04 or Debian 11.

To compile a simple C program, we use the Linux command line tool, Terminal. To open the terminal, you can use Ubuntu Dash or the key combination Ctrl+Alt+T.

Install the necessary build packages

To compile and execute a C program, you need to install essential packages on your system. Enter the following command as root in your Linux Terminal:

$ sudo apt install build-essential

How to write and run C programs in Linux Picture 1How to write and run C programs in Linux Picture 1

You will be asked to enter the root password; The installation process will then begin. Please make sure you are connected to the Internet.

Write a simple C program

After installing the necessary packages, write a simple C program.

Open Ubuntu's graphical Text Editor and write or copy the following sample program into it:

#include int main() { printf("nA sample C programnn"); return 0; }

Then save the file with the extension .c. This example names its C program sampleProgram.c

How to write and run C programs in Linux Picture 2How to write and run C programs in Linux Picture 2

Additionally, you can write a C program through Terminal in gedit as follows:

$ gedit sampleProgram.c

This will create a .c file to write and save the program.

Compile C programs with GCC Compiler

In your Terminal, enter the following command to create an executable version of the program you wrote:

Syntax:

$ gcc [programName].c -o programName

For example:

$ gcc sampleProgram.c -o sampleProgram

How to write and run C programs in Linux Picture 3How to write and run C programs in Linux Picture 3

Make sure your program is placed in the Home folder. If not, you will need to specify the appropriate paths in this command.

Run the program

The final step is to run the compiled C program. Use the following syntax to do so:

$ ./programName

For example:

$ ./sampleProgram

How to write and run C programs in Linux Picture 4How to write and run C programs in Linux Picture 4

You can see how the program is executed in the example above, displaying the written text to print through.

This article shows you how to write, compile, and run a simple C program in Linux. All you need are the necessary packages and skills to turn you into a programming expert in Linux!

3.5 ★ | 2 Vote