This blog post provides a step-by-step guide on how to write and run a C program in Linux. It covers everything from installing the necessary software to compiling and running your program.
Step 1: Install the build-essential packages
You will have to install essential packages on your system. Enter the following command in your Linux Terminal.
$ sudo apt-get install build-essential
You will be asked to enter the password for root; the installation process will begin after that. Please make sure that you are connected to the internet.
Step 2: Write a simple C program
After installing the essential packages, let us write a simple C program.
Open Ubuntu’s graphical Text Editor and write or copy the following sample program into it:
#include<stdio.h>
int main()
{
printf("\nA sample C program\n\n");
return 0;
}
save the file with .c extension. In this example, I given name sampleProgram.c
Alternatively, you can write the C program through the Terminal in gedit as follows:
$ gedit sampleProgram.c
This will create a .c file where you can write and save a program.
Step 3: Compile the C program with gcc Compiler
In your Terminal, enter the following command in order to make an executable version of the program you have written:
Syntax:
$ gcc [programName].c -o programName
Example:
$ gcc sampleProgram.c -o sampleProgram
Make sure your program is located in your Home folder. Otherwise, you will need to specify appropriate paths in this command.
Step 4: Run the program
The final step is to run the compiled C program. Use the following syntax to do so:
$ ./programName
Example:
$ ./sampleProgram
You can see how the program is executed in the above example, displaying the text we wrote to print through it.
This article taught you how to write, compile and run a simple C program in Linux.