Friday, January 18, 2013

Compiling C, C++ Programs on Ubuntu

If you are a developer you need C and C++ Compiler for your development work.In ubuntu you can install the build-essential for C and C++ compilers.

Install C and C++ Compilers in Ubuntu

sudo aptitude install build-essential

This will install all the required packages for C and C++ compilers

Testing C and C++ Programs

Compiling Your first C Programs

Now you need to open first.c file

sudo gedit first.c

add the following lines save and exit the file




Firstly compile the code using the following command

cc -c first.c

that would produce an object file you may need to add to the library.

then create an executable using the following command

cc -o first first.c

Now run this executable using the following command

./first

Output should show as follows

Hello, world


Compiling your first C++ program

If you want to run c++ program follow this procedure

g++ is the compiler that you must use.

you should use a .cpp file extension rather than a .c one

You need to create a file

sudo gedit first.cpp

add the following lines save and exit the file




Run your C++ Program using the following command

g++ first.cpp -o test

./test

Output should show as follows

Hello World!


OR 


1. Install the 'build-essential' package.
$ sudo apt-get install build-essential

2. Write your first C program.
gedit myhello.c
paste this code into it, and save

#include <stdio.h>

main()
{
printf("Hello Ubuntu Lover!\n");
}


3. Compile your first C program

$ gcc myhello.c -o myhello


4. Run your first C program

$ ./myhello
Hello Ubuntu Lover!


5. Write your first C++ program
gedit myhello.cpp
paste this code into it, and save
#include <iostream>
using namespace std;

int main()
{
cout << "Hello Ubuntu Lover in C++" << endl;
return 0;
}

6. Compile your first C++ program
g++ myhello.cpp -o myhellocpp

7. Run your first C++ program
$ ./myhellocpp
Hello Ubuntu Lover in C++


Source of information:
 
  1. How to write and run c/c++ programs on ubuntu
  2. How to Install C and C++ Compilers in Ubuntu and testing your first C and C++ Program

No comments:

Post a Comment