Developing C and C++ Programs in Linux Environment

Running C and C++ applications in Linux is entirely different from Windows TurboC++ users. Linux uses GCC [Gnu Compiler Collections - C and C++ compiler] for developing these applications . Let us see how to develop C and C++ applications in Linux .

Checking GCC compiler
GCC comes with all Linux flavors by default . To check the version of your GCC , type this command in your terminal

root@Ubuntu:/home/anthoniraj# gcc  –version
gcc (Ubuntu 4.4.1-4ubuntu9) 4.4.1
Copyright (C) 2009 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.
By default only C compiler will be there in GCC , you can install C++ support by typing this command in Ubuntu
#sudo apt-get install build-essential
Developing C Program
You can use your favorite editor or IDE like Netbeans or Eclipse to develop the C and C++ programs. I am using VIM the simple and king of all editor for developing these programs. Now simply we can write one C program for finding factorial of a given number.
#vim factorial.c [ file type is .c ]

#include<stdio.h>
int main()
{
int n , i ;
unsigned long int  res = 1;
printf("nEnter the number to find the factorial:");
scanf("%d" , &n );
for(i = 1 ; i <= n ; i++)
{
res *= i;
}
printf("n The factorial value of %d is %lun" , n, res);
return 0;
}

Compiling and Running
To compile c program , use gcc with file name

#gcc factorial.c
#./a.out [Default buffer for output]
Enter the number to find the factorial: 5
The factorial value of 5 is 120
or
#gcc factorial.c -o fact.out
#./fact.out [customized file for output]
Note :
  1. There is no void keyword in GCC ,
  2. Use int instead of void and also use return 0 .

Developing C++ Program
Now I am going to write C++ for the same factorial method.
#vim factorial.cpp [File Type is cpp]

#include <iostream>
using namespace std;
int main()
{
int n ;
unsigned long int  res = 1;
cout << "nEnter the number to find the factorial:" << endl;
cin << n ;
for(int i= 1 ; i <= n ; i++)
{
res *= i;
}
cout <<"The factorial value of " <<"is " << endl;
return 0;
}
Compiling and Running
To compile c program , use gcc with file name

#g++ factorial.cpp
#./a.out [Default buffer for output]
Enter the number to find the factorial: 5
The factorial value of 5 is 120
or
#g++ factorial.cpp -o fact.out
#./fact.out [customized file for output]
Note :
  1. Dont use .h for header files
  2. Use name space for header-file functions

No comments:

Post a Comment