How to write and compile C++ program in Linux

Here is a step by step detailed guide on showing you how to write and compile a C++ program in Linux. For demonstration purposes, I’ll show you how to write and compile Hello World which is typically the first program that many students learn when introduced to programming.

How to write and compile Hello World in C++

First, let’s locate and open up our handy terminal. The terminal is the console on where you will initially learn how to create folders in order to create the programs that we will later compile. Depending on your OS your Terminal or Console might be opened in various ways. The image below demonstrates how to open it in Ubuntu.


terminal c++ hello world


Installing the appropriate tools

We might have to install the tools necessary to start writing, and compile our code. In order to do this we must specify some commands to install our tools. If you already have the programs installed, it will either upgrade them, or do nothing so either way there is no harm in trying this out.

The following commands simply give permission to install the packages we need.

sudo apt-get install g++ 
sudo apt-get install emacs

If it asks you for a password, simply provide the password you log in with. And if it asks you for what version of emacs, simply type in emacs22 for now.

Other linux distributions may have different methods for installing these tools. If so, use their Package Managers to download them.

Creating a folder and creating the Hello World program file

Now, let’s create a new folder and open a file in that folder to write our Hello World program. I’ll explain the commands shown on the screen in more detail below the image.


terminal emacs hello world C++


The following command lists the contents of the current directory.

ls

The following command makes a directory with the name FOLDERNAME.

mkdir FOLDERNAME

The following command changes your current directory to FOLDERNAME.

cd FOLDERNAME

The following command opens up the program emacs with the file hello_world.cpp. If not created it will create it for you.

emacs hello_world.cpp


Writing Hello World

With emacs open, simply click on the editor and it should turn blank. Write the following code for your Hello World program. When done, simply hit save. (It will save in the folder you called emacs hello_world.cpp)

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;
 
int main() { 
 
     cout << "Hello World!\n";
     return 0;
}



Hello World!


Your editor should look like the image above.

Compiling our Hello World Program

Now that you have your program, let’s compile it so it can be written in machine language that can later be executed.

Hello World!



The following command will compile your program and create an executable called a.out.

g++ hello_world.cpp

The following command will execute your program.

./a.out




Congratulations! You are done! I tried making it as simple as possible. If you still have any questions, feel free to drop a comment or suggestion to make this tutorial better!

Useful resources

C++ Guide Your guide for programming in C++

Tags: , , , ,

  • Devon

    Ugh. I am so confused. I just switched to Linux a few days ago. When i tried to install emacs “sudo apt-get install emac” it wouldn’t work and how do i open the c++ program thing. Man, i want to go back to vista.

  • Devon

    Ugh. I am so confused. I just switched to Linux a few days ago. When i tried to install emacs “sudo apt-get install emac” it wouldn’t work and how do i open the c++ program thing. Man, i want to go back to vista.

  • Diego

    It usually depends on the Linux distribution you have. Many times, you can go into the Install Manager, and install the applications by searching for them.

    Also, you installed Ubuntu over your Vista? You should be able to use your Recovery CD to go back.

  • http://www.befolks.com Arun | BE Folks

    This is the first blog i come across that teaches C and C++.
    I like your idea.will check regularly!!!

  • http://www.befolks.com Arun | BE Folks

    This is the first blog i come across that teaches C and C++.
    I like your idea.will check regularly!!!

  • http://www.howstuffworks.com/ NewComer in Linux

    Thanks for this quick steps in compiling C/C++ programs in GNU/Linux!

  • http://www.howstuffworks.com/ NewComer in Linux

    Thanks for this quick steps in compiling C/C++ programs in GNU/Linux!

  • Jeff

    Thanks for the tutorial. I found it via search engine. I was just about to give up on C++ then I realized that I didn’t even need an IDE! NetBeans is 150MB to DL… screw that. Using the CLI makes much more sense – it just works straight away!

  • Jeff

    Thanks for the tutorial. I found it via search engine. I was just about to give up on C++ then I realized that I didn’t even need an IDE! NetBeans is 150MB to DL… screw that. Using the CLI makes much more sense – it just works straight away!

  • Nguyen Viet Hung

    Thanks! It helps a lot!
    Looks easier than on Windows when you want to write and test just a few codes. On Windows, you must create a whole project (like Visual Studio).

  • Nguyen Viet Hung

    Thanks! It helps a lot!
    Looks easier than on Windows when you want to write and test just a few codes. On Windows, you must create a whole project (like Visual Studio).

  • http://talkbinary.com Diego

    I’m glad this tutorial has been helpful!

    Yes, it may be much simpler on linux. I prefer using the terminal, g++, and vi to test simple programs.

  • http://talkbinary.com Diego

    I’m glad this tutorial has been helpful!

    Yes, it may be much simpler on linux. I prefer using the terminal, g++, and vi to test simple programs.

  • Buba

    when i type ./a.out it tells me:
    bash: ./a.out: No such file or directory

  • Buba

    when i type ./a.out it tells me:
    bash: ./a.out: No such file or directory

  • http://www.yahoo.com Buba

    i compiled no errors i can’t excute it.

  • http://www.yahoo.com Buba

    i compiled no errors i can’t excute it.

  • Diego

    Try performing the ls command.
    Do you see a.out in the first place?
    Did you compile the program using

    g++ main.cc or something similar?
    Try seeing if a file is created afterward.

  • Yvon

    it’s easy to understand.
    And helped me to start compiling c++ in linux.
    Thanks a lot.

    for the question of
    Devon Says:
    November 5th, 2008 at 6:18 pm
    Ugh. I am so confused. I just switched to Linux a few days ago. When i tried to install emacs “sudo apt-get install emac” it wouldn’t work and how do i open the c++ program thing. Man, i want to go back to vista.

    corrected:?sudo apt-get install emacs(instead of emac)… I just noticed this one. Linux is better than vista. You made a bad decision to go back to vista. ^_^

  • Yvon

    it’s easy to understand.
    And helped me to start compiling c++ in linux.
    Thanks a lot.

    for the question of
    Devon Says:
    November 5th, 2008 at 6:18 pm
    Ugh. I am so confused. I just switched to Linux a few days ago. When i tried to install emacs “sudo apt-get install emac” it wouldn’t work and how do i open the c++ program thing. Man, i want to go back to vista.

    corrected:?sudo apt-get install emacs(instead of emac)… I just noticed this one. Linux is better than vista. You made a bad decision to go back to vista. ^_^

  • saif

    Thank u very much for these instructions , but they only worked with SUSE linux , when i tried this with Ubuntu it says that c++ and emacs are not installed ! , i tried to install using : sudo apt-get update but its taking a very long time …. also what is : using namespace std ? is writing this statement a must ?

  • saif

    Thank u very much for these instructions , but they only worked with SUSE linux , when i tried this with Ubuntu it says that c++ and emacs are not installed ! , i tried to install using : sudo apt-get update but its taking a very long time …. also what is : using namespace std ? is writing this statement a must ?

  • Diego

    I believe with Ubuntu you can use the installer to find these packages.

    Simply look for emacs, g++ in the package manager.

    The answer to your second question is at:
    http://talkbinary.com/programming/c/hello-world-in-c/

    You usually find it in your programs. I’d just stick with it.

    If you have any more questions feel free to ask.

  • saif

    Hi again , i have a number of questions regarding Ubuntu Linux ,
    Q1: i have installed Ubuntu side by side with my Windows Vista , so now i have a dual boot , unfortunately the space given to ubuntu wasnt sufficient ( 3.2 Gb ) and due to a large number of packeges being ionstalled later i couldnt simply execute C++ programs with emacs !! ,a message says : {cant execute , not enough space on device }, so i cant know easily identify the packeges installed , cause i typed : sudo-apt get update , now how can i uninstall ubuntu in order to install it again “with the idea of givin’ it a much larger space , wich i dont know how !

    Q2: When i try to select the normal or extra choices under the Visual effect tab , i get a message saying”Desctop effects couldnt be enabled !” now..compiz is installed and when i try to install my laptop drivers via the DVD { i have a Dell studio laptop with Intel Core 2 Duo 2 Ghz , 4 giga of RAM and 256 mega of video RAM on an Ati Radeon card}, it contains Linux installation file that ends with rpm extension , it refuses to be installed saying that rpm extension is not recignized, so i reaaly want to experience ubuntu visual effects ,,, any helpp please?

  • saif

    Hi again , i have a number of questions regarding Ubuntu Linux ,
    Q1: i have installed Ubuntu side by side with my Windows Vista , so now i have a dual boot , unfortunately the space given to ubuntu wasnt sufficient ( 3.2 Gb ) and due to a large number of packeges being ionstalled later i couldnt simply execute C++ programs with emacs !! ,a message says : {cant execute , not enough space on device }, so i cant know easily identify the packeges installed , cause i typed : sudo-apt get update , now how can i uninstall ubuntu in order to install it again “with the idea of givin’ it a much larger space , wich i dont know how !

    Q2: When i try to select the normal or extra choices under the Visual effect tab , i get a message saying”Desctop effects couldnt be enabled !” now..compiz is installed and when i try to install my laptop drivers via the DVD { i have a Dell studio laptop with Intel Core 2 Duo 2 Ghz , 4 giga of RAM and 256 mega of video RAM on an Ati Radeon card}, it contains Linux installation file that ends with rpm extension , it refuses to be installed saying that rpm extension is not recignized, so i reaaly want to experience ubuntu visual effects ,,, any helpp please?

  • Diego

    For your first question:

    If you have a Partition Program, I believe you can allocate more space to your Ubuntu installion that way either on Windows or Ubuntu. I don’t remember exactly.

    Other way you can try is to remove Ubuntu and install it again. Do not remove Ubuntu without learning how to do it properly first! Best thing I did was first modified GRUB so Windows would boot first and then I removed Ubuntu. If you remove Ubuntu first, GRUB would try to boot and since its on Ubuntu, you wouldn’t be able to boot to any OS anymore. BAD!

    For the second question:
    Try the ubuntu forums for specifics on installing video drivers. They have tons of people who ask similar questions. Maybe someone with the same configuration already solved the problem?

  • saif

    Hi again … using the Code Blocks C++ compiler , if iam writing a program that contains both main() , and a function , my Question is : can i write the main() in one file and the function in another file ? and when the program executes the main() will call the file that contains the function and gives the appropriate output ?

  • saif

    Hi again … using the Code Blocks C++ compiler , if iam writing a program that contains both main() , and a function , my Question is : can i write the main() in one file and the function in another file ? and when the program executes the main() will call the file that contains the function and gives the appropriate output ?

  • Markus

    All I get is an error message that says, “iostream: no such file or directory” Nothing works! I have no idea how to get this program to compile.

  • Markus

    All I get is an error message that says, “iostream: no such file or directory” Nothing works! I have no idea how to get this program to compile.

  • Diego

    @saif Yes you can, but doing that is a different topic on its own. Look into “makefiles”

  • Diego

    @Markus Did you install gdb.

    Did you try cutting and pasting the code? Maybe you mispelled something?

    If you haven’t gotten it to work yet, reply, and I’ll try to help you through with it.

  • Daniel

    Awesome!!! Thank You! Wow using terminal makes it so much easier…..This helped me out a lot. Thanks again!

  • Daniel

    Awesome!!! Thank You! Wow using terminal makes it so much easier…..This helped me out a lot. Thanks again!

  • shailesh

    i wrote the above lines in terminal but while inserting password(login) it shows error that sorry try again .after 3 attempts it stops and come back to home directry..
    plz .put ur advice …

  • shailesh

    i wrote the above lines in terminal but while inserting password(login) it shows error that sorry try again .after 3 attempts it stops and come back to home directry..
    plz .put ur advice …

  • Diego

    Are you the administrator or root user on Linux?

    Do you login to your homescreen with a password? Try using that one.

  • malik

    i get this error when compiling on Opensuse 11.2 and i know there is no problem in my code.

    Documents/c> gcc hello.cpp
    hello.cpp:5: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x
    hello.cpp:7: error: expected ‘}’ before ‘;’ token
    hello.cpp:7: error: invalid conversion from ‘void*’ to ‘int’
    hello.cpp:9: error: expected unqualified-id before ‘return’
    hello.cpp:10: error: expected declaration before ‘}’ token

  • malik

    i get this error when compiling on Opensuse 11.2 and i know there is no problem in my code.

    Documents/c> gcc hello.cpp
    hello.cpp:5: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x
    hello.cpp:7: error: expected ‘}’ before ‘;’ token
    hello.cpp:7: error: invalid conversion from ‘void*’ to ‘int’
    hello.cpp:9: error: expected unqualified-id before ‘return’
    hello.cpp:10: error: expected declaration before ‘}’ token

    • Diego

      May you post your code?

    • Diego

      Try using
      g++ hello.cpp

  • atul

    can anyone help me writing di code above,,please i want a full code of dis

    • http://talkbinary.com Diego Villasenor

      The entire code was provided in the tutorial. Thank you for your suggestion.

  • atul

    can anyone help me writing di code above,,please i want a full code of dis

  • uma.v

    while iam executing my program in linux I got an error that “expected ; befor ) token” but not in windows. What is this error and why it is so?

  • uma.v

    while iam executing my program in linux I got an error that “expected ; befor ) token” but not in windows. What is this error and why it is so?

    • Diego

      Can you post the code? Also, how you are trying to compile it? SDK? Terminal? Thanks.

  • Parviir

    Thank you very much for the above tutorial. Linux seems to be much more educational than Windows.

  • Peter

    The above tutorial was very useful to me. Thank you!

  • Elvinasadov214

    good. It was my first App in Linux. worked greate. Hi from Azerbaijan

  • Prateek

    it was a really helpful post. it worked perfectly.
    i have done quite a bit of c++ in turbo and i was wondering if there is a good book or site which teaches c++ in linux. any help would be greatly appreciated

  • http://www.techonologyreview.blogspot.com Technology review

    this is good sharing, hope more

  • Jnwoods

    perfect!!

  • First User

    Believe it or not, that was very helpful to me as I learn some basic Linux things on panda. After not dealing with unix for over 23 years (but doing C programming on a daily basis in Windows), got some serious catching up to do on command line tools.