0.6 — Compiling your first program

Before we can write our first program (which we will do very soon), we need to know a few things about development environments.

First, although our programs will be written inside .cpp files, the .cpp files themselves will be added to a project. The project stores the names of all the code files we want to compile, and also saves various IDE settings. Every time we reopen the project, it will restore the state of the IDE to where we left off. When we choose to compile our program, the project tells the compiler and linker which files to compile and link. It is worth noting that project files for one IDE will not work in another IDE. You will need to create a new project for each program you write (or overwrite an old one).

Second, there are different kinds of projects. When you create a new project, you will have to pick a project type. All of the projects that we will create in this tutorial will be console projects. A console project means that we are going to create programs that can be run from the dos or linux command-line. By default, console applications have no graphical user interface (GUI) and are compiled into stand-alone executable files. This is perfect for learning C++, because it keeps the complexity to a minimum.

Third, when you create a new project for your program, many IDEs will automatically add your project to a “workspace” or a “solution”. A workspace or solution is a container that can hold one or more related projects. Although you can add multiple projects to a single solution, we recommend creating a new workspace or solution for each program. It’s simpler and there’s less chance of something going wrong.

Traditionally, the first program programmers write in a new language is the infamous hello world program, and we aren’t going to deprive you of that experience! You’ll thank us later. Maybe.

A quick note about examples containing code

Starting with this lesson, you will see many examples of C++ code presented. Most of these examples will look something like this:

If you select the code from these examples with your mouse and then copy/paste it into your IDE, you may also get the line numbers (depending on how you made the selection). If so, you’ll need to remove these manually.

If you’re using the Visual Studio IDE

Although the following section was written using Visual Studio 2005, it essentially works the same for all versions of Visual Studio.

To create a new project in Visual Studio, go to the File menu, and select New -> Project. A dialog box will pop up that looks like this:

VC2005 Project Dialog

First, make sure “Visual C++” is selected on the left side.

Second, underneath “Visual C++”, select the Win32 project type, and Win32 Console Application will automatically be selected for you. In the Name field, you will enter the name of your program. Type in HelloWorld. In the Location field, pick a directory that you would like your project to be placed into. We recommend you place them in a subdirectory off of your C drive, such as C:\VC2005Projects. Click OK, and then Finish.

On the left side, in the Solution Explorer, Visual Studio has created a number of files for you, including stdafx.h, HelloWorld.cpp, and stdafx.cpp.

Initial Visual C++ program

In the text editor, you will see that VC2005 has already created some code for you. Select and delete all of the code, and type/copy the following into your compiler:

What you end up with should look like this:

Visual C++ hello world program

To compile your program, either press F7 or go to the Build menu and choose “Build Solution”. If all goes well, you should see the following appear in the Output window:

Successful build

This means your compile was successful!

To run your compiled program, press ctrl-F5, or go the Debug menu and choose “Start Without Debugging”. You will see the following:

Program run

That is the result of your program!

Note: If you see the console window (black box) without any text, your anti-virus may be interfering. Try turning your anti-virus off temporarily and try again.

Important note to Visual Studio users: Visual studio programs should ALWAYS begin with the following line:

Otherwise you will receive a compiler warning, such as c:testtest.cpp(21) : fatal error C1010: unexpected end of file while looking for precompiled header directive

Alternately, you can turn off precompiled headers. However, using precompiled headers will make your program compile much faster, so we recommend leaving them on unless you are developing a cross-platform program.

The example programs we show you throughout the tutorial will not include this line, because it is specific to your compiler.

If you’re using the Code::Blocks IDE

To create a new project, go to the File menu, and select New Project. A dialog box will pop up that looks something like this:

Code::Blocks Project Dialog

Select Console Application and press the Go button.

This should pop up a wizard:

Code::Blocks Wizard Dialog

On the next page, select “C++” as your language. Click Next.

Code::Blocks Wizard Dialog

Next, you’ll be asked to name your project and choose a location. For your project title, set a name (such as HelloWorld). In the Project Title field, you will enter the name of your program. Type in HelloWorld. In the Folder to create project in field, pick a directory that you would like your project to be placed into. We recommend you place them in a subdirectory off of your C drive, such as C:\CBProjects. Click Next.

Code::Blocks Wizard Dialog

On the next screen, Code::Blocks asks you what compiler you want to use, and what configurations you want. Don’t touch anything here, just hit Finish.

Code::Blocks Wizard Dialog

Now you’ve created your project, and should see your project under the default workspace:

Code::Blocks Project Closed

Open your project node, then open “Sources”, and double click on “main.cpp”. You will see that the hello world program has already been written for you!

To build your project, press ctrl-F9, or go to the Build menu and choose “Build”. If all goes well, you should see the following appear in the Build log window:

Successful build

This means your compile was successful!

To run your compiled program, press ctrl-F10, or go the Build menu and choose “Run”. You will see something similar to the following:

Program run

That is the result of your program!

If you’re using a command-line based compiler

Paste the following into a text file named HelloWorld.cpp:

From the command line, type:

g++ -o HelloWorld HelloWorld.cpp

This will compile and link HelloWorld.cpp. To run it, type:

HelloWorld (or possibly ./HelloWorld), and you will see the output of your program.

If you’re using a web-based compiler temporarily

Paste the following into the input form:

and then press “Run”. You should see your output below the form.

Once you install a full IDE, you’ll want to return to this lesson again to learn how to create a project in your IDE.

If you’re using other IDEs

You will have to figure out how to do the following on your own:
1) Create a console project
2) Add a .cpp file to the project (if necessary)
3) Paste the following code into the file:

4) Compile the project
5) Run the project

If compiling fails (“Something went wrong!”)

It’s okay, take a deep breath. We can probably fix it. 🙂

First, check to ensure that you’ve typed the code in correctly, with no typos or misspellings (also, make sure you’re not including line numbers in your code). The compiler’s error message may give you a clue as to where or what the problem is.

Second, check lesson 0.7 -- A few common C++ problems, as many common problems are addressed there (including the COFF error that many of you are encountering).

If that fails, try searching for your error message on Google. It’s likely someone else has encountered this before and figured out how to fix it.

If you are using a much older C++ compiler, the compiler may give an error about not understanding how to include iostream. If this is the case, try the following program instead:

In this case, you should upgrade your compiler to something more compliant with recent standards.

If your program runs but the window closes immediately

This is an issue with some compilers, such as Bloodshed’s Dev-C++. We present a solution to this problem in section 0.7 -- A few common C++ problems.


Congratulations, you made it through the hardest part of this tutorial (installing the IDE and compiling your first program)!

Don’t worry if you don’t understand what all the different lines in the Hello World program do. We’ll look at and explain each line in detail in the upcoming lesson 1.1 -- Structure of a program.

0.6a -- Build configurations
0.5 -- Installing an Integrated Development Environment (IDE)

500 comments to 0.6 — Compiling your first program

  • iype

    I use code::blocks IDE but when i tried to build my project (for HelloWorld) it tells me that there is an "environment error" and that "can’t find compiler executable in your configured search path’s for GNU GCC compiler" what can i do about it???
    Moreover i installed the one with mingw.

    • Alex

      Hmm, something must have gone weird with the install. The minGW version should have set up the compiler.

      Try going to settings, compiler, and choose “reset to defaults”.

  • Heesoo Yang

    • Alex

      I don’t know why stdafx.h includes stdio.h and tchar.h by default. You can probably remove them. stdio.h isn’t even a C++ header, it’s a C header that includes legacy (C) input/output routines.

      That said, if you’re using precompiled headers in Visual Studio, you must have stdafx.h as the first line of any .cpp file, or Visual Studio won’t compile properly. If you don’t like this, you can disable precompiled headers, but your program may compile slower.

  • nikos-13

    I use code::blocks IDE but when i tried to build my project (for HelloWorld) it tells me that ther is an "environment error" and that "can’t find compiler executable in your configured search path’s for GNU GCC compiler" what can i do about it???

  • Patrick

    I have tried it several times and every time it does not work, it says it does not recognise the word cout?? I am not sure what to do as have typed it out exactly as instructed, Am using a new laptop with Windows 10 and the visual studios ide

    • Patrick

      I have figured out where i made my initial mistake however I am still seeing errors on line 1 . it says

      Severity    Code    Description    Project    File    Line    Suppression State
      Error    LNK2019    unresolved external symbol _WinMain@16 referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)    HelloWorld    c:\Users\Patrick\documents\visual studio 2015\Projects\HelloWorld\HelloWorld\MSVCRTD.lib(exe_winmain.obj)    1

  • daniel bayona

    hello i have a question, i have a mac, so with this tutorial i can learn? and if i used xcode will be the same as using visual studio? and a can copy de  archives of xcode to visual studuio? thanks

  • abdullh

    first of all thanx for this awsome tutorial
    i have a problem when creating a new project in visual basic thscreen appeared as you said but there are nothing to chose from no 32 console or any other think and i made sure visual c++ is selected please help and thanx again

  • Brandon

    Hello Alex,

    I am currently trying to use Visual Studio 2015 for this tutorial and I kept getting several errors. After a little while of investigating, I found that my project doesn’t contain source files in the Solution Explorer like it does in your 2005 example. Do you have any idea what the problem could be? Thanks!

    • Brandon

      Never mind, Alex. I figured out what I was doing wrong. After clicking "New Project" I was clicking the "Console Application" option under the "Visual C#" tab instead of the "Visual C++" then "Win32" tabs. Thanks so much for this tutorial! It’s a wonderful place to start my journey in creating my first video game!

  • Roshan

    "can’t find compiler executable in your search path (GNU GCC compiler)" Please help me fix this issue in Codeblocks

  • Ronak

    i am Using DOSBox

    How will the codes differ in my case?

  • Hello Alex,
    this program is not working with online tools. Please help


  • Srilekha

    I’m following the tutorial in my mobile .I don’t know how to install these IDE and all . can you help me?

  • Avery T


    This is how to create a project with Xcode 7.3.1 for  Macs.

    1. File > New > Project
    2. Select OS X > Application > Command Line Tool > Click "Next" >"Choose options for your new project" appears
    3. Type "Hello World" in "Product Name" box > In "Organization Identifier" type "cpp" >  In "Language" select "C++" > Click "Next"
    4. Click "Create"
    5. On the left side of the project window is the project navigator, which lists all the files in your project select "main.cpp" to begin coding
    6. In the text editor you should see, select/delete the following :

    int main(int argc, const char * argv[]){
        // insert code here…  
        std::cout << "Hello, World!n";
        return 0;

    7. Copy/paste:

    #include <iostream>

    int main(int argc, const char * argv[]) {
        // insert code here…
        std::cout << "Hello, World!n";
        return 0;

    8. Press the Play icon on the top left corner of the screen. The output of the program should appear in the debug console at the bottom of the project window.

    9. Click the disclosure triangle next to the Products folder in the project navigator to show the application you built. Select the application, right-click, and choose Show in Finder. Doing this will show your application in the Finder so you can run the application outside of Xcode.

    • Alex

      Thanks! This will be super helpful for Mac users. I appreciate you taking the time to share.

      • Hi Alex and Avery

        Great tutorials so far and yes, I am a Mac user! The new project (above) with Xcode doesn’t work! Well, it does, and thanks for the info on how to create a new project, Avery - however, I’m getting an error message saying "Redefinition of main" and its highlighting in red the
        int main(int argc, const char * argv[]) part of the code. so the ‘main’ part seems to be wrong

        I downloaded Xcode yesterday (April 2016) so maybe its changed - it is also Xcode 8.3.1

        I’m wondering if I should either get Parallels or just buy a PC to learn C++

        Thanks for any help in advance.

        • Oops!  I meant to say 2017, doh!

        • Alex

          Redefinition of main() means the compiler is finding two main functions. It sounds like xcode added the main(int argc, const char * argv[]) function for you. Maybe you added your own main() function afterward? Try removing the main(int argc, const char * argv[]) function and see if it compiles.

          • Thanks (big time) for replying Alex. I didn’t add anything of my own - just copied and pasted from above. So I’m now thinking that, as I’m a lowly a carpenter/joiner, I’m totally out of my depth here and struggling already if I’m honests, but, as I liked doing coding with my degree (html), I’m going to keep going and see if I can actually learn anything from the rest of the tutorials - I’m guessing that if I persevere I can see the error of my ways! Thanks again Alex, pretty sure this aint my last message either 🙂

            • Alex

              I’m confused. 🙂 You said you copied my code, but my code uses int main(), not int main(int argc, const char * argv[]). So where did int main(int argc, const char * argv[]) come from?

              • Er, it came from Avery’s post above - sorry Avery!

                So I tried it without the (int argc, const char * argv[) and… IT WORKED!! Build Successful!

                Thanks so much Alex … onwards and upwards!

  • Adrian

    *tries to debug*
    "Access is denied.
    Press any key to continue . . ."

    I’m not sure what’s going on. I ran Visual studio as administrator but i still get the same message. Any Idea??

  • David

    Im using vs express 2013 and i tried this and keep getting the error LNK2019 and error LNK1120. How do i fix this?

  • Ye Kyaw Tun

    Thank you. I already did it. Now i am moving to
    1.1. 🙂

  • Ye Kyaw Tun

    In my IDE, when i run the "Hello World" program, it appears and disappears in very short time.
    How can i handle it?

    Thank you very much for your support and help
    Ye Kyaw Tun

  • Ady20

    Well I am completely lost. You told me to install Visual 2015, then you show me how to program in Visual 2005 lol. Visual 2005 compared to 2015 it’s like a whole new program. There are no similarities at all lol.

    • Alex

      Where are you lost?

      I’ll take a note to update the screenshots. It’s a pain to do every new release, but once every decade isn’t too bad. 🙂

  • Alex Keel

    I was having an issue getting the compile to succeed in Visual Studio Community after deleting the pre-entered code.

    ========== Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========

    For anyone else having this issue, I clicked "Build", "Clean Solution", and then compiled again:

    ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

  • Akshay

    Really felt its what I needed. I have earlier used c   and been through the programming phase yet felt that something is missing and this is what that completes what’s left .
          The work is really commendable.

  • Shivam

    I am using codeblocks and whenever I start doing anything, an error appears, "Can’t find compiler executable in your confirmed search path’s for GNU GCC compiler." Please help

  • Paul Rombach

    Finally got it to work on VS2015.
    First try, it kept asking for a pch.h precompiler, so i substituted that for stdafx.h, no success

    I finally reviewed the common problems in lesson 7 and found the lnk2019 error - i was using the wrong type of program.

    I switched to the win32 program type, it pre-populated teh hello world with 50% of the text, so I added what was missing and success.

    For VS2015 - check the  sdk - make sure that you installed it and that the program is pointing to it.  you might need to retarget to the right version (right mouse click on the hello world program header in the  search solution explorer).

  • Daphne

    If your command prompt disappears immediately - try to compile the program with ctrl+f5.

    • Alex K

      If that doesn’t work in Visual Studio, try adding

      like this:

      It will force the prompt to stay frozen until user input. 🙂

  • Eviax

    I’ve installed Visual Studio 2015 and selected Console Application. I tried to name my project HelloWorld.cpp and whenever I write that code it finds about 14 errors and won’t go past that. It’s pretty weird! I haven’t go a clue how to fix it. Do you have anything on your mind?

  • Thanks. I am trying to compile hello world program in C in Dev c++ compiler but getting compilation error.

  • Sid McMaximoso

    Visual Studio 2015 is taking hours to install…

  • Alex brother i am using codeblocks and when i tried to compile the hello world program it shows me some errors like as stated below….


    C:cbprojectsjo.c:1:20: fatal error: iostream: No such file or directory
    #include <iostream>
    compilation terminated.
    Process terminated with status 1 (0 minute(s), 2 second(s))
    1 error(s), 0 warning(s) (0 minute(s), 2 second(s))


    ||=== Build file: "no target" in "no project" (compiler: unknown) ===|
    C:cbprojects  jo.c|1|fatal error: iostream: No such file or directory|
    ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 2 second(s)) ===|

    i think i have mistaken somewhere please help me

    and one more thing which compllier i have to use it should br gnu gcc complier or any other

  • Stephen

    Hi Alex
    I have downloaded Visual Studio Community 2015. I have all the C++ template installed. I tried to create a new project, but the dialog box simply disappear for 1 second and reappears when I click the OK button. I’ve searched for the solution but no luck. Do you have any idea on this?

    On a special note, I cannot even use the devenv command that I found online. I have navigated to the directory which contain the devenv.exe and nothing happens when I enter the command.

    • Alex

      I have no idea, unfortunately. I’ve never heard of such a thing happening.

      • Stephen

        I have figured it out!

        For my case, it has to do with the language pack. The visual studio I have was the Chinese version. I installed the English language pack and I can’t create new project all of a sudden. Later, I switch back to Chinese and it works fine. As it turns out the language pack mess up the project creation for some reason.

  • Miles

    Hi Alex, I’m having an issue with VS 2015.  I ran the program once and got the cmd window just as pictured.  However, after attempting to write a few more lines to output and using ctrl+f5 again, Visual studio no longer runs a cmd window.  Now I just get this big empty white box.

    • Alex

      Try disabling your virus scanner if you have one. Sometimes they can interfere with the command window.

      • Miles

        I already attempted that, with no success.  The window that opens looks like an App (it gets the green little gear icon as it’s opening.)

        Is there any menu/area where I can choose how the program runs?

        • Alex

          The debug menu contains your options to launch the program. Visual Studio might have some settings in the project settings, but I’m not sure where they are if they exist.

          If you go back to your previous program that worked, does it still work? Maybe something is wrong with your program.

  • Emile winworth

    Thankz Alex. I am a beginner in C++ and I am using VS 2015. I did the HelloWorld successfully.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter