Running C Programs in Ubuntu Command Line
This short tutorial explains about the execution of C programs in Ubuntu, with the help of a compiler like gcc.
While there are many ways to execute a C program in Linux, using the terminal is the easiest of all, even for beginners.
It may seem scary, but it is really not. To run C programs in Ubuntu, you need to install the compiler first.
In this guide, you will learn to:
- Install GCC compiler (to compile the program)
- Execute the C program
Let's C (yeah! I am funny).
Installing the compiler - gcc
The GCC compiler used to compile C-programs into executable files is available in the official repositories of apt. Installing gcc in Ubuntu is fairly simple.
First, update the repositories:
sudo apt update
Then install GCC via:
sudo apt install gcc
clang
package rather than gcc
alone. It includes all other compiling tools too.Executing a C program in Ubuntu
Once you are ready with the compiler, you can write programs and compile and execute them.
You specify the input C file name and an output name (usually recommended to keep the same name as the program filename but without the .c extension).
gcc <filename>.c -o <filename>
The generated output file is executable and you can run this file to actually run your program.
./filename
Example
Open any text editor and write a simple C program.
For example, here, I used Nano editor to edit the file in command line and wrote a C program that prints the value of sin30
:
Save the file with a desired name and with a .c extension.
To compile this program, all you have to do is execute the GCC compiler in the following manner:
gcc c-program.c -o c-program
If your code is correct, it won't show any errors, and you will be given an executable file for your program.
You can always use the ls command to check the file contents of the directory:
ls
Now, all there's left is to execute the file:
./c-program
To C or not to C ...
If there's an error in the C program file, then it will not be compiled, obviously. Also, the error(s) are displayed as shown below.
In my case, the error was in the first line where I named the header file stdio
incorrectly. Which was supposed to be named as stdio.h
.
Sure, you can have one or more errors which will be reflected by the compiler.
On a similar note, how about learning about running Python programs in Ubuntu?
These are the simple steps to compile C programs in Ubuntu. Leave a comment if there's any doubt.
This is Pranav Krishna, a Proud Linux user in twelfth grade.