0.7 — Compiling your first program

Before we can write our first program, we need to learn how to create new programs within our Integrated Development Environment (IDE). In this lesson, we’ll cover how to do that, and you’ll also compile and execute your first program!


To write a C++ program inside an IDE, we typically start by creating a new project (we’ll show you how to do this in a bit). A project is a container that holds all of your source code files, images, data files, etc… that are needed to produce an executable (or library, website, etc…) that you can run or use. The project also saves various IDE, compiler, and linker settings, as well as remembering where you left off, so that when you reopen the project later, the state of the IDE can be restored to wherever you left off. When you choose to compile your program, all of the .cpp files in the project will get compiled and linked.

Each project corresponds to one program. When you’re ready to create a second program, you’ll either need to create a new project, or overwrite the code in an existing project (if you don’t want to keep it). Project files are generally IDE specific, so a project created for one IDE will need to be recreated in a different IDE.

Best practice

Create a new project for each new program you write.

Console projects

When you create a new project, you’ll generally be asked what type of project you want to create. 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 Windows, Linux, or Mac console.

Here’s a screenshot of the Windows console:

Windows console

By default, console applications have no graphical user interface (GUI), they print text to the console, read input from the keyboard, and are compiled into stand-alone executable files. This is perfect for learning C++, because it keeps the complexity to a minimum, and ensures things work on a wide variety of systems.

Don’t worry if you’ve never used a console before, or don’t know how to access it. We’ll compile and launch our programs through our IDEs (which will invoke the console when necessary).

Workspaces / solutions

When you create a new project for your program, many IDEs will automatically add your project to a “workspace” or a “solution” (the term varies by IDE). A workspace or solution is a container that can hold one or more related projects. For example, if you were writing a game and wanted to have a separate executable for single player and multiplayer, you’d need to create two projects. It wouldn’t make sense for both of these projects to be completely independent -- after all, they are part of the same game. Mostly likely, each would be configured as a separate project within a single workspace/solution.

Although you can add multiple projects to a single solution, we generally recommend creating a new workspace or solution for each program, especially while learning. It’s simpler and there’s less chance of something going wrong.

Writing your first program

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.


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 the line numbers manually before you compile.

Creating a project in Visual Studio 2019

When you run Visual Studio 2019, you should see a dialog that looks like this:

Visual Studio 2019 Get Started dialog

Select Create a new project.

You’ll then see a dialog that looks like this:

Visual Studio 2019 Create New Project dialog

If you’ve already opened a prior project, you can access this dialog via the File menu > New > Project.

Select Windows Desktop Wizard and click Next. If you don’t see this, then you probably forgot to choose to install the Desktop development with C++ workload when you installed Visual Studio. In that case, go back to lesson 0.6 -- Installing an Integrated Development Environment (IDE) and reinstall your Visual Studio as indicated (note: rather than doing a full reinstall, you can run the Visual Studio installer and modify your existing installation to add the C++ workload).

Next, you’ll see a dialog that looks like this:

Visual Studio 2019 Configure New Project dialog

Replace the existing project name with HelloWorld.

It’s recommended that you also check the Place solution and project in the same directory, as this reduces the number of subdirectories that get created with each project.

Click Create to continue.

Finally, you’ll see one last dialog:

Visual Studio 2019 Project options dialog

Make sure the Application type is set as Console Application (.exe) and that the Precompiled Header option is unselected. Then click OK.

You’ve now created a project! Jump down to the Visual Studio Solution Explorer section below to continue.

Creating a project in Visual Studio 2017 or older

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

Visual Studio 2017 New Project dialog

First, make sure Visual C++ is listed on the left side. If you don’t see Visual C++, then you probably forgot to choose to install the Desktop development with C++ workload when you installed Visual Studio. In that case, go back to lesson 0.6 -- Installing an Integrated Development Environment (IDE) and reinstall your Visual Studio as indicated (note: rather doing a full reinstall, you can run the Visual Studio installer and modify your existing install to add the C++ workload).

If you’re using Visual Studio 2017 v15.3 or newer, underneath Visual C++, select Windows Desktop and then select Windows Desktop Wizard in the main window.

If you don’t see Windows Desktop as an option, you’re probably using an older version of Visual Studio. That’s fine. Instead, choose Win32 and then Win32 Console Application in the main window.

Down below, in the Name field, enter the name of your program (replace the existing name with HelloWorld). In the Location field, you can optionally select a different location for your project to be placed into. The default is fine for now.

Click OK. If you’re using an older version of Visual Studio, the Win32 Application Wizard will launch. Press Next.

At this point, you should see a wizard dialog that looks something like this (older versions of Visual Studio use a different style, but have most of the same options):

Visual Studio 2017 Desktop wizard

Make sure you uncheck Precompiled Header.

Then click Ok or Finish. Now your project is created!

Visual Studio Solution Explorer

On the left or right side of the window, you should see a window titled Solution Explorer. Inside this window, Visual Studio has created a solution for you (Solution ‘HelloWorld’). Within that, with the name in bold, is your new project (HelloWorld). Within the project, Visual Studio has created a number of files for you, including HelloWorld.cpp (underneath the Source Files tree item). You may also see some other .cpp or .h files, which you can ignore for now.

Visual Studio 2019 initial windows

In the text editor, you will see that Visual Studio has already opened HelloWorld.cpp and created some code for you. Select and delete all of the code, and type/copy the following into your IDE:

To compile your program, either press F7 (if this doesn’t work, try Ctrl-Shift-B) or go to the Build menu > Build Solution. If all goes well, you should see the following appear in the Output window:

1>------ Build started: Project: HelloWorld, Configuration: Debug Win32 ------
1>HelloWorld.vcxproj -> c:\users\alex\documents\visual studio 2017\Projects\HelloWorld\Debug\HelloWorld.exe
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

This means your compile was successful!

Q: I got error C1010 ("fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?"). What now?

You forgot to turn off precompiled headers when you created your project. Recreate your project (as per the instructions above) and make sure to disable precompiled headers.

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

Program run

That is the result of your program! Congratulations, you’ve compiled and run your first program!

Creating a project in Code::Blocks

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

Code::Blocks Project Dialog

Select Console application and press the Go (or Create) button.

If you see a console application wizard dialog, press Next, make sure C++ is selected and press Next again.

Now you will be asked to name your project. Title the project HelloWorld. You can save it wherever you wish. On Windows, we recommend you to save it in a subdirectory of the C drive, such as C:\CBProjects.

Code::Blocks Save Project Dialog

You may see another dialog asking you which configurations you want enabled. The defaults should be fine here, so select Finish.

Now your new project has been created.

On the left side of the screen, you should see a Management window, with the Projects tab selected. Inside that window, you’ll see a Workspace folder, with your HelloWorld project inside of it:

Code::Blocks Workspace

Inside the HelloWorld project, expand the Sources folder, and double click on “main.cpp”. You will see that a hello world program has already been written for you!

Replace that one with the following:

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

-------------- Build: Debug in HelloWorld (compiler: GNU GCC Compiler)---------------
mingw32-g++.exe -Wall -fexceptions -g -std=c++14  -c C:\CBProjects\HelloWorld\main.cpp -o obj\Debug\main.o
mingw32-g++.exe  -o bin\Debug\HelloWorld.exe obj\Debug\main.o   
Output file is bin\Debug\HelloWorld.exe with size 1.51 MB
Process terminated with status 0 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))

This means your compile was successful!

To run your compiled program, press Ctrl-F10, or go to Build menu > Run. You will see something similar to the following:

Program run

That is the result of your program!

For Linux users

Linux users may need to install the additional packages before Code::Blocks will compile. Please see the Code::Blocks installation instructions in lesson 0.6 -- Installing an Integrated Development Environment (IDE) for more info.

If you’re using g++ on the command line

In this case, you don’t need to create a project. Simply paste the following into a text file named HelloWorld.cpp and save your file:

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 other IDEs or a web-based compiler

You will have to figure out how to do the following on your own:
1) Create a console project (IDEs only)
2) Add a .cpp file to the project (IDEs only, if one isn’t auto-created for you)
3) Paste the following code into the file:

4) Compile the project
5) Run the project

If compiling fails

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

First, look at the error message that the compiler gave you. Most often, it will contain a line number indicating which line was in error. Examine both that line and the lines around it, and make sure there are no typos or misspellings. Also make sure you’re not including line numbers in your code.

Second, look at the Q&A in lesson 0.8 -- A few common C++ problems, as your issue may be covered there.

Third, read the comments below -- someone may have encountered the same issue.

Finally, if all of the above fail, 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 your program runs but the window flashes and closes immediately

Some IDEs don’t automatically pause the console screen after the program has finished executing. Your program is running, but the output window is closing before you can view the results.

If this is the case with your IDE, the following two steps will fix your problem:

First, add or ensure the following lines are near the top of your program (Visual Studio users, make sure these lines appear after #include “pch.h” or #include “stdafx.h”, if those exist):

Second, add the following code at the end of the main() function (just before the return statement):

This will cause your program to wait for the user to press a key before continuing, which will give you time to examine your program’s output before your IDE closes the console window.

Other solutions, such as the commonly suggested system("pause") solution may only work on certain operating systems and should be avoided.

Your anti-virus or anti-malware may also be blocking execution of the program. If that’s the case, try temporarily disabling your scanners and see if the problem resolves.

For Visual Studio users

Visual Studio will not pause at the end of a console application if it is run with debugging (Debug Menu > Start Debugging). If you want it to pause, you can either use the code solution above, or run your program without debugging (Debug Menu > Start Without Debugging).


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 at the start of the next chapter.

0.8 -- A few common C++ problems
0.6 -- Installing an Integrated Development Environment (IDE)

866 comments to 0.7 — Compiling your first program

  • Jack

    Whenever I build Helloworld, the output shows up fine, but when I press Crl-F5,it says

    Executable for Debug Session

    Please specify the name of the executable file to be used for the debug session.

    Executable file name:

    URL where the project can be accessed (ATL Server only):


    And then the command prompt does not run.
    Please Help!!!

    • TS

      Did you ever work this out as I'm having the same problem.

      • ab

        i had the same problem. i right clicked on the bold HelloWorld in the explorer on the right, chose properties > General > Project Defaults and for "configuration type" i changed it from DLL to exe. this seems to have worked. i am a newbie, so take this all with a big grain of salt.

  • Matthew

    I love this site. However it would be nice to see a Makefile tutorial.. those things are a real brain ache.

    • That's one of the best things about modern IDEs -- no need to create Makefiles because the IDE does it for you!

      I was never very good at Makefiles anyway.

  • Elijah

    ok so is there a diference between codeblocks and visual, do i need them both or only 1? ahh this is alot of stuff lol

  • Tom

    g++ is not recognized as an internal or external command.

    Thanks in advance. Great Site!

  • Chris

    Hi, got down to the section in 0.6 - "Using a command-line based compiler", on a Windows XP machine, am a bit confused as to where/what directory the HelloWorld.cpp 'text' file, created in notepad, should be placed. And where the command line is. If i run the command 'g++ -o HelloWorld HelloWorld.cpp' from the Windows 'cmd' screen, I get an error.

    Regards Chris

    • On Windows, I highly recommend using an IDE. It makes things much easier.

      You probably got an error because you never installed g++, which I do not cover how to do in this tutorial because using an IDE is much simpler.

  • Jonathan

    Hi alex i have a problem when i run the first version of the program in "Start without Debugging " i get a message "The application has failed to start because MSVCR90.dll was not found.Re-Installing the application max fix the problem"

    What have i done wrong i followed everything you said?
    Please reply soon i cant continue on!

    • I am not sure what is going on. MSVCR90.dll is a windows dll that programs compiled with visual studio 2008 need to run. It should be in your windowssystem32 directory (I think).

  • i just started to learn C++
    i have mocrosoft visual studio 2008 professional
    i see here you use mvs2005
    so i cant do some things that u do here as code::blocks; please help me... it is my first time and i have no one to help me

    • All of the code that works with MSVS 2005 should work with the 2008 version as well. The code::blocks stuff is just for people using that compiler and can be skipped if you're using the MS compiler.

  • Roger

    the following is what i have entered, i must have made a mistake when it said to delete the _tchar function.
    What have i done wrong.
    cannot get the iostream to display in this message

    // HelloWorld.cpp : Defines the entry point for the console application.

    #include "stdafx.h"
    #include iostream

    int _tmain(int argc)
    return 0;
    int main()
    std::cout << "Hello world!" << std::endl;
    return 0;

    • Get rid of _tmain(). You don't need it for these kinds of programs. Also, it should be:

      Don't forget the angle brackets.

      (PS: Put your code in <pre> tags and you will be able to use angle brackets in messages)

  • Hello I Am Using Code::Blocks, And Am Having trouble with compiling. When I Select console application, I am prompted to select a compiler, but there is like 50 to choose from on the list, and all of them give me the same error when i compile.

    Please Help

    • wert

      i have found that the first-run compiler autodetection fails on vista. or maybe it is that it never even runs. you need to go into the compiler settings and the toolchain executables tab and choose autodetect. this should find the mingw compiler that should have been installed with your codeblocks (you should be running the codeblocks installer that comes WITH mingw and has mingw in the name, unless you are installing it seperately). this fixed the invalid compiler error for me.

    • csvan

      You need to download and install a compiler I think, I do not believe Code::Blocks comes packed with one. A good compiler to use is the GCC (Gnu Compiler Collection), but to my knowledge it can be quite hard to set up a compiler on your own if you do not have the appropriate knowledge.

      Depending on what platform you use, there are solutions to this. If you run OSX (as I do), you will find GCC and the complete IDE Xcode on the installation disc for OSX (just insert it and look for optional installs and Xcode tools), that will install GCC as well.

      If you are running Windows, I would suggest downloading and using DevC++, its good, and comes with a compiler out of the box I think.

      Email me if you have further problems (

  • Noah

    I did it without looking!! (on my fourth try).

  • Aeris

    Every time I try to create a new project, it says "Automation sever cannot create object." Or something to that effect. What's going on?

  • Once again, never mind. I figured it out. In case someone else ends up with the same problem down the road, you can't have spaces in the filepath and I don't think it liked my main folder name "C++Programming" either.

  • danaldo

    microsoft visual studio 2008

    new project

    visual c++


    comes with two 'visual studio installed templates'

    1) Win32 console application
    2) win32 project.

    whats the differnece between the two?

    the simple reason and the complex reason would be much appreciated.
    thanx dan

    • A console project is one that uses the MS Dos console and has no windows graphical user interface. A win32 project is one that has an actual window/dialog box.

  • I'm using Code Blocks for Mac Os X and I got the program compiled correctly, however; when I use ctrl-F10 to start it, I get a message saying that the file does not exist. I can go through and open it by itself from outside the Code Blocks program and it runs correctly. I was wondering if there was some way to fix this problem so I can run it from Code Blocks. Thanks in advance.

    • csvan

      Hmmm, I have used Code::Blocks in the past and not had this problem. Did you start a new project, or did you just create a new file? I believe your problem lies there. Always start by creating a new project.

      • Alex

        No, I have the same error, and I opened a new Project. It says, and I quote:

        "Conversion - Debug" uses an invalid compiler. Skipping...
        Nothing to be done.

        I've looked all over the internet, and nobody seems to have any idea how to fix this.

        • Elsa

          I have the same error when I try to compile it, it does the exact same thing as that!

          (“Conversion – Debug” uses an invalid compiler. Skipping…
          Nothing to be done.)

          Have you found anything to solve it?

          It would be great if somebody could help :)

  • shamun.toha

    As i saw this is a standard online guide for C++ and Hellow World. Questions and Request:

    1. Can it be update for Mobile/PDA OS Nokia, Microsoft "hello world" too, using code block or IDE MS2008 ?

    i am tired to find it and central url as my blog, but c++ tutorial seems great in this site.

    • The information presented on this site is generally platform agnostic. Anything that is Windows specific is explicitly noted (or should be -- if it isn't, let me know). If you're developing on another platform, the code presented in these tutorials should work (assuming your compiler implements language support correctly), but you will of course have to figure out how to actually get it to compile yourself. :)

  • Tim

    I am wondering how to get the Code::Blocks templates to show up. I have tried the add and create on the solution thingy.
    The link below is what I have done

  • Ben

    Hi Alex,

    I use Visual C++ 2008 and when I create a Win32 console application I get an extra file: "targetver.h". This file seems to define the minimum configuration required for my program:

    #pragma once

    // The following macros define the minimum required platform. The minimum required platform
    // is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
    // your application. The macros work by enabling all features available on platform versions up to and
    // including the version specified.

    // Modify the following defines if you have to target a platform prior to the ones specified below.
    // Refer to MSDN for the latest info on corresponding values for different platforms.
    #ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
    #define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.

    But I don't have Windows Vista, just XP. So far it runs just fine, but I'm wondering if I shoudn't swith for Visual C++ 2005 right now; or can I keep going like that?

    This file "targetver.h" is called in "stdafx.h", and if I remove the command, it runs again. But maybe some more advanced features will require this file.

    To make it short, I'm just wondering if I can run C++ 2008 without having Vista.

    Thanks a lot for this tutorial.

    • If I'm not mistaken (and someone correct me if I am), the _WIN32_WINNT #define tells Visual Studio which set of Windows header files to compile your programs with. Visual Studio 2008 defaults to 0x0600 because they assume you will be coding Vista programs. If you're coding programs that you want to run on WinXP, you should probably change this to 0x0501 (0x0502 for XP SP2) as this will ensure you don't accidentally use Vista-only functions.

      Note that this has nothing to do with whether you can run VS2008 on XP -- you can. It only has to do with what OS the programs you COMPILE using VS2008 can run on.

  • Derek

    Umm I'm a complete noob...

    I'm using Code::Blocks and for some reason I can't run the hello world program...

    I put the code in, pressed build (successful), and when I click 'run' nothing happens.
    Any ideas...?

    • My guess is that your program is running and then terminating so fast you can't see the result. Read the part of this tutorial entitled "If your program runs but the window closes immediately" and see if that fixes your issue.

  • Very nice. This got me up and running quite nicely.

  • Masss

    I'm following this well, but the problem is that using this Microsoft Visual C++ 2008 version, I don't have the header file or the source file created from the start. I only have three empty files in the tree.

    I've managed to write as you did, but how do i create those other files?
    I managed to add a header item to the folder and coded

    and it seemed to work! Is that what is coded in the header file in the example above?

    • I'm not sure I understand your question. However, just to make it clear, in order to use cout (which is what puts your text on the screen), you have to include iostream, because that's where cout is defined.

  • louis

    code compiles fine, and i can run the .exe from the command line. the problem is this...
    once the program is complete the console window closes automatically.

    so i only see the hello world for a nanosecond!

    how can i make the window stay open, or do the "press any key to continue" bit?


  • Josh

    thanks bro, this helped me out alot! thnaks for helping me write my first C++ program

  • When using a command line to compile (ms vs c 2008 express ed.), what does the "-c" mean in the following command? (i.e. cl SomeFile.cpp -c).

    • Depends on the compiler. With g++, -c means "compile to object files, but don't link into an executable file". With Microsoft's command line compiler, -c doesn't mean anything because cl.exe uses slash commands (/) rather than minus commands (-).

  • Abhishek

    I don't get the "using namespace std" thing coz i don't know what's a namespace and what's std(standard??)

    And in my book they have written using namespace std before int main().......does that make any difference?

    • Don't worry about the namespace thing right now. I cover namespaces in a future lesson when you're better equipped to understand what a namespace is.

      If you put using namespace std outside of main (but not in another function), it affects the entire rest of the file. If you put it inside a function, it only affects rest of the function.

      There's really no right or wrong way to do it. I prefer to do it on a function-by-function basis because it's slightly safer, but for simple programs either way is fine.

  • Wesley

    Some people do:

    Is there a difference and a reason? Do some compilers only accept that?

    • I presume you are talking about the difference between:


      It's really just two similar but slightly different ways of doing the same thing. Both should work on all compilers.

      To elucidate slightly, the cout object lives inside a namespace called std. If you just use the name cout, the compiler doesn't know to look inside of the std namespace. Consequently, you have to tell it to look there. There are two ways to do this: directly (std::cout), or indirectly (using the using statement, which basically sets up a default namespace that the compiler will look in if it can't resolve symbols). Using std::cout is the safer solution, but can make for ugly code if you're doing lots of I/O. In those cases, the using statement can be a better choice.

      BTW: Including iostream inside PRE tags seems to work fine for me:

      • Brian

        What do you mean by "Using std:: is the safer solution?" Is it more efficient/faster by not loading the entire namespace or just more compatible? Thanks!

        • Alex

          When you use the std:: prefix, you're referencing a specific thing, so the odds of something going wrong is very small.

          When you use "using namespace std", you're telling the compiler to check the std namespace whenever it can't resolve a name. This opens up a small possibility that the compiler could resolve a name to something in the std namespace when you didn't intend for it to do so. This is unlikely, so it's generally not worth worrying about.

  • Tiomon

    By the way the end1 is endl (LOWERCASE L)

    i thought it was a 1 and i took an hour trying to figure out what was wrong lol.

  • Quinton

    How could I get this for Dev-Cpp? I did it, but the executable file flashes for .1 of a second and closes.

  • Zung

    Extremely useful and easy to understand ans follow. Thank you guys for a great work.

  • Suntha

    Very useful tutorial- especially for beginers for me! Thanks a lot!

  • Bryan

    There are 2 different things you have "using namespace std;" while in the pic example you have "std:: cout

    [ Code::Blocks does that by default, so I just left it. Either way works. -Alex ]

Leave a Comment

Put all code inside code tags: [code]your code here[/code]