Tuesday, August 21, 2012

How to Compile ‘n’ Execute/Run C/C++ program in Ubuntu 12.04

Posted: 20 Aug 2012 10:16 AM PDT


Now a Days, Ubuntu is one of the most popular OS among programmers (not only nerds but also the beginners who just entered into the programming world) but for a beginner Ubuntu user coming from Windows may feel some problem in programming with Ubuntu.
On Windows they use nice GUI based IDE, but in Ubuntu things are little different. In Ubuntu it’s better to use Terminal (specially for the beginners), instead of GUI based IDEs such as Eclipse, Netbeans etc for compiling programs. In fact, the command line approach is much easier and efficient, due to the powerful shell such as bash, zsh etc.
So, in this post – you will learn - how to compile and execute (run) C/C++ programs in Ubuntu 12.04 (Precise Pangolin)/12.10(Quantal Quetzal) or other Linux distributions such as Linux Mint 13 (Maya). You don’t need to install any extra applications or tools other than the compiler. The default text editor – gedit will work fine for source code editing (unless you have a preferred source editor such as Emacs, Vim, Nano, Kate or something else).

#1. Install the C/C++ Compiler

First make sure that you have GCC (GNU Compiler Collection, for C language) and G++ (for C++ language) installed on your system. If not, then install it by typing the following commands on Terminal -
For C
sudo apt-get install gcc
For C++
sudo apt-get install g++

#2. Write the Program (Source Code)

Open gedit and write the following lines of code (it’s a simple program that contains one print line and one comment, just for explanation purpose) -
#include

void main()
{
	printf("Hello! Human!\n");
	/* Do something more if you want */
}
Then save the file as hello_human.c on your Home Directory (~). If you ae writing a c++ program, then give it the extension as .cpp (and of course you will also have to change the command accordingly during compilation)

#3. Compile it

The command structure is :
gcc source_file_name.c -o executable_file_name
if leave the -o option (name of the output file) then by default a.out will be created as the executable output file.
To execute the above example program, open a terminal and type -
cd ~
gcc hello_human.c -o hello_human
[In case of C++, just replace gcc with g++, rest of the things are same, e.g g++ source_file.cpp -o executable_file]

#4. Execute It

On Terminal, type (from the same directory where you have the executable file, in this case, it’s Home Directory(~) ) -
First make the script executable (sometimes, it may not be necessary)
chmod +x hello_human
Then run the program using the command -
./hello_human
Now you should get the output -
Hello! Human!

No comments: