Compile C/C++ Programs on Linux
by Vamsi Srikanth in Circuits > Computers
14945 Views, 39 Favorites, 0 Comments
Compile C/C++ Programs on Linux
This article will show you how to compile a C/C++ program on Linux using the GNU gcc/g++ compiler.
Hopefully this article will serve as a guide and tutorial to compiling GNU C/C++ programs on Linux.
Install Build-essesntial Package
Open up a terminal on Ubuntu Linux and install the build-essential package by typing the following command in the terminal
sudo apt-get install build-essential
These are the important library files for compiling C/C++ programs on linux.
Create a Seperate Folder to Hold Your Programs
Use the below command to make a directory on your desktop.
sudo mkdir -p CPP/HW/
By using the above command we are making a folder named 'CPP' & a sub-folder named 'HW' inside it.
Change Your Working Path to Your Created Directory
Change your working directory in the Terminal to the folder which you just created by using the below command.
cd CPP/HW/
Creating the Program File With 'nano'
We will use 'nano' an inbuilt simple text editor to create & write programs & their files. Use the command below to make your program file.
sudo nano helloworld.c
Write Your Program Code and Save It
type your program code into the nano editor. For the sake of this tutorial I'll be making a simple helloworld program.
Program :
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("\nHello World,\nWelcome to my first C program in Linux");
return(0);
}
Now save your program by pressing Ctrl+X on your keyboard at the same time and ' press Y ' and press Enter
Compiling Your Program
Type the below command to compile your program
gcc -Wall -W -Werror helloworld.c -o helloworld
The first line will invoke the GNU C compiler to compile the file helloworld.c and output (-o) it to an executable called helloworld
The options -Wall -W and -Werror instruct the compiler to check for warnings.
If you want to compile a C++ program then use the below command
g++ -Wall -W -Werror helloworld.cpp -o helloworld
Executing Your Program
Type the below command to execute your program.
sudo ./helloworld
we typed ./helloworld since our compile version in the previous step is helloworld. If its xyz then we will type ./xyz
After typing this your program output will be shown in the Terminal.
Thank you.
As Shown on
http://www.mightygeekstuff.com/2015/01/compile-c-programs-on-linux/