Search This Blog

Thursday, September 1, 2011

Compiling programs with gcc and g++



Using Linux can be a lot difficult, but only for those who are new to it. But that's pretty obvious. Isn't it?
So, one of the most common problem faced by all the new comers to this platform, who are also into computer programming, is... HOW DO I COMPILE MY C/C++ PROGRAM????
After being asked by too many people on how to compile programs on Linux, i felt a need to write a post describing the whole process in a single place.

The only pre-requisition to getting started is -- an Internet connection.
So, firstly we need to install the compiler for c++. GNU-gcc is the standard compiler for C/C++.
To install GCC, go to the terminal and type:

sudo apt-get install g++
Since gcc has some dependencies for its advanced functionality on g++, it is recommended g++ is installed as well. You can skip this step if you want to.
Your output screen would look a lot different, because my computer had g++ and gcc installed at the time of writing of this post. While in your case, it would probably download it from the internet and install it. It would take a while depending on the speed of your internet connection.


Also, this is of-course for those who are using Ubuntu (or any other Debian variant). The users of other operating systems should use their respective installers. For example,
Fedora: yum install g++
RHEL : rpm -ie g++


Once g++ is installed, now we need to install gcc. For installing gcc, again go to terminal and type
sudo apt-get install gcc


Now you are all set. The compiler is installed and auto-configured to be used on your machine.

Simply open a text editor and start writing a program. I prefer gedit, but vim, emacs and nano can be used as well.


Save the file and remember the location where you have saved it.



Now, go to the terminal and change your present working directory path to the place where your program is saved using "cd" command.
when you are there, type the following commands.

gcc filename.c -o output.o

To generate an object file as output.
chmod +x output.o
This would make the generated output file executable.
./output.o
To execute the program from the object file.


No comments:

Post a Comment