Saturday, March 8, 2008

Cpp programming in Linux

Before starting Cpp programming on Linux, you need to check the existence of some development tools.
Following example illustrates how to check existence of development tools. You should get a similar output.
All these commands were executed on my home PC which runs RHEL 5.

[root@SHADOWMAN ~]# which g++
/usr/bin/g++
[root@SHADOWMAN ~]# which c++
/usr/bin/c++

If you have afore-mentioned tools available, you are set to start.

C/C++ Compiler:
The C compiler on Linux is a part of compiler suite, known as GCC(GNU Compiler Collection). This suite offers compilers for several languages. Following is a list of typical ones offered.
• C
• C++
• Objective C
• Fortran

The name of C compiler program on Linux is gcc and C++ compiler is called as g++. You can find out the version of the compiler using –version option. This is the output produced on my home machine.

[root@SHADOWMAN ~]# gcc --version
gcc (GCC) 4.1.1 20070105 (Red Hat 4.1.1-52)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Now just do it....
1) Create a new file with extension .cpp in your folder.
2) Open the file and write the program. Finish it by saving (for eg; 1.cpp here).
3) Right click on the desktop and open terminal
4) In the terminal, change into your folder by using cd command.
5) Type g++ 1.cpp OR c++ 1.cppand press enter. If there are errors, they will be listed here.
6) Successful compilation would lead to the creation of an executable file a.out . Run that by using the command ./a.out . The result will be displayed in the terminal.

Here is a simple Eg for a cpp program
#include
using namespace std;
int main()
{

cout<<"Hello World!\n";

}

NOTE:
You have to include "using namespace std;". Else compilation will show error messages like this:
1.cpp: In function ‘int main()’:
1.cpp:5: error: ‘cout’ was not declared in this scope







No comments: