Frequently Asked Question

Run a C Program in Linux
Last Updated 2 years ago

Step 1: Write a simple C program

Let us 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 program\n\n");
return 0;
}

Then save the file with .c extension. In this example, I am naming my C program as sampleProgram.c

Example C program

Alternatively, you can write the C program through the Terminal in gedit as follows:

$ vi 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
Compile sourcecode with gcc

Make sure your program is located in your Home folder. Otherwise, you will need to specify appropriate paths in this command.  If no error messages were printed to the screen, your code compiled. Now do ls and you will see a file called a.out. By default, gcc places the executable into this file, overwriting any existing file of the same name. You specify the name of your executable, say samplePrgoram by the following line:
gcc sampleProgram.c -o sampleProgram

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
Start our compiled program

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

Please Wait!

Please wait... it will take a second!