C is a robust programming language used for developing system software. This tutorial will help you to run a C/C++ program in Linux/Unix system through the command line.
In this article, we used ‘gcc’ and ‘g++’ commands from GCC (GNU Compiler Collection) to compile a C/C++ program. It is:
- gcc is the GNU C Compiler from GCC.
- g++ is the GNU C++ Compiler from the GCC.
Intalling Development Tools
In order to run a C Program, You must have installed Development Tools packages on your Linux system. Run one of the following commands to install development tools packages as per your operating system.
sudo yum groupinstall "Development Tools" ## Redhat based systems sudo apt-get install build-essential ## Debian based systems
Create Sample C Program
For the example, I have selected C hello world program. Create a new file on your system as follows:
using the below content
Compile And Run C/C++ Programs In Linux
I used GNU C Compiler to compile the above hello world C program as following:
gcc helloworld.c -o hello
[OR] Use the below command to use C++ compiler.
g++ helloworld.c -o hello
The above commands will create an executable file named hello in your current directory. You can directly run that same as other commands.
You can also copy file under bin directory (/usr/local/bin) to make them accessible system-wide.
Try Another C Example
Let’s try with another C program with user input. For this example, I used this sample C program to input two integers from the user and calculate the sum of them.
int i, j, sum;
scanf("Enter 1'st integer: %d", &i);
scanf("Enter 2'nd integer: %d", &j);
sum = i + j;
printf("Sum is: %d\n", sum);
Now compile and run C program
gcc sum.c -o sum ./sum