Monday, January 25, 2016

How to compile and run C/C++ program on Ubuntu


Okay, on previous article i show you how to install C/C++ compiler on ubuntu, now it's time for me to show you how to write a C and C++ source code and then compile and run it.

Basically we need two things in order to do C/C++ programming, the first is a compiler which we already install, and the second is a text editor which we have also on ubuntu.

For this tutorial i'm going to use gedit as the text editor for the C and C++ source code that we are going to write. Later on you can install more advanced editor such as eclipse, netbeans, etc. But that would be on another article, for now we just use gedit.

Create helloworld program in C

For example we are going to write simple program which is helloworld program in C language. C programming language source code is stored in a file with extension of .c (dot c).

Open terminal/console/command line (press CTRL + ALT + T), and then type this command to write file called helloworld.c

gedit helloworld.c

Once gedit is open, copy paste this code into the text editor and then save the file.

#include <stdio.h>

int main(void) {
 printf("Hello World \n");
 printf("this is a sample program wrote in C language \n");
 printf("ubuntuhowtotips.blogspot.com is awesome blog \n");
 getchar();
}

Now let's compile the source code using gcc, like this :

gcc helloworld.c -o helloworld

That command is telling the compiler (gcc) to compile file named helloworld.c and create output binary/executable file called helloworld, notice the -o parameter, that means output.

If you don't specify the -o parameter, gcc will just create binary file called a.out, which is not nice, so make sure you specify the name of the output file.

You should have a new file called helloworld (with no extension), that's the binary/executable file, now go ahead run the program like this:

./helloworld

Create helloworld program in C++

Next i'm going to show you how to create helloworld program in C++ (C plus plus), the different between C and C++ is that C++ is an object oriented language while C is just procedural language.

Unlike C language, C++ source code file is stored as .cpp, so let's create file called helloworld.cpp, simply run this command on terminal/console/command line:

gedit helloworld.cpp

Next copy paste this code into the text editor (gedit)

#include <iostream>
using namespace std;

int main() {
  cout<<"Hello World"<<endl;
  cout<<"checkout awesome blog"<<endl;
  cout<<"ubuntuhowtotips.blogspot.com"<<endl;
  return 0;	
}

Now, compile the C++ source code with g++ compiler

g++ helloworld.cpp -o helloworld2

Finally we can run the program like this:

./helloworld2

That's it, now you know how to compile and run both C and C++ program on ubuntu. Happy coding and don't forget to smile :)

No comments:

Post a Comment