≡ Menu

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

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!
Add your comment

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

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • akhil November 8, 2012, 4:34 am

    you can compile a C++ program using cc compiler as well.
    use :- aCC file.cpp -o file

  • harish March 16, 2013, 12:48 pm

    thank you so much 🙂