How To Write, Compile and Execute C++ Program on Unix OS (With Hello World Example)

by Ramesh Natarajan on September 11, 2009

Question: I would like to understand the basics of how to write, compile and execute a C++ program on Linux OS. Can you explain it with a simple example?

Answer: Last week we reviewed how to write C program on Unix OS. In this article, let us review very quickly how to write a basic Hello World C++ program and how to compile *.cc program on Linux or Unix OS.

1. Write a Hello World C++ Program

Create the helloworld.cc program using a Vim editor as shown below.

$ vim helloworld.cc
// my first program in C++

#include <iostream>
using namespace std;

int main ()
{
  cout << "Hello World!";
    return 0;
}

2. Make sure C++ Compile (g++) is installed on your system

Make sure g++ is installed on your system as shown below.

$ whereis c++
c++: /usr/bin/c++ /usr/include/c++ /usr/share/man/man1/c++.1.gz

$ which c++
/usr/bin/c+

$ dpkg -l | grep g++
ii  g++                                        4:4.3.3-1ubuntu1                          The GNU C++ compiler
ii  g++-4.3                                    4.3.3-5ubuntu4                            The GNU C++ compiler

3. Compile the helloworld.cc Program

Compile the helloworld.cc using c++ command as shown below. This will create the a.out file.

$ c++ helloworld.cc

$ ls -l
-rw-r--r-- 1 ramesh ramesh   71 2009-09-03 11:03 helloworld.cc
-rwxr-xr-x 1 ramesh ramesh 9152 2009-09-03 11:06 a.out

4. Execute the C++ Program (a.out)

You can either execute the a.out to see the output (or) rename it to some other meaningful name and execute it as shown below.

$ ./a.out
Hello World!

$ mv a.out helloworld

$ ./helloworld
Hello World!
Download Free eBook - Linux 101 Hacks

Get free Unix tutorials, tips and tricks straight to your email in-box.

If you enjoyed this article, you might also like..

  1. How To Write, Compile and Execute C Program on Unix OS [With Hello World Example]
  2. Pascal Hello World Example: How To Write, Compile and Execute Pascal Program on Unix OS
  3. Python Hello World Example: How To Write and Execute Python Program on Unix OS
  4. Fortran Hello World Example: How To Write and Execute Fortran Program on Linux OS
  5. Ruby Hello World Example: How To Write and Execute Ruby Program on Unix OS
  

Vim 101 Hacks Book

Leave a Comment

Previous post:

Next post: