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 Visual Studio 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 (a program that can be compiled on different operating systems/architectures).

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)

597 comments to 0.6 — Compiling your first program

  • Dahare

    Hi! I am using code::block. When I create a new project, I don't find "Sources" under "Console application". I cannot start writing the code. Why is this?  How can I find it?

    • Alex

      It's possible that newer versions of Code::Blocks have changed the UI slightly. When you create a new project, it should start you with a sample hello world program. Where does that program live within the Projects tab?

      • Dahare

        I got it. Thanks. I am  new to programming so I lack observing where things are. I got it under the projects tab.  I was looking up in the Resources tab.

      • Mahendra

        I made "helloworld" as a new project step by step as instructed, it also bulid and run smoothly. But when I tried to edit the program statement like:

        original ---> cout << "Hello world!" << endl;

        Edited by me  ---> cout << " Hello world!" << endl; // I just introduced one space before the word Hello.

        result on ctrl+f9 --->

        === Build: Debug in helloworld (compiler: GNU GCC Compiler) ===

        ld.exe   cannot open output file binDebughelloworld.exe Permission denied

                 error: ld returned 1 exit status

        === Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===

        This error comes on again even after removing that space before the word Hello(making it as it was originally written), but after 10-15 minutes(after removing of extra space) it build and runs successfully on ctrl+f9 & ctrl+f10. WHAT IS WRONG ?

        • Alex

          I can think of two possibilities:
          1) Your executable is still running when you try to recompile it, so the compiler is unable to overwrite the old executable with the new one.
          2) Your virus scanner (assuming you have one) may be interfering. Try disabling it and see if the problem disappears.

          • Mahendra

            1) I don't think executable is still running because on very first build and run process(when I didn't introduce a space before the word "Hello") it shows the execution time like 0.182 seconds on the output screen and also says to press any key to continue. Then how is it possible that it still in progress?

            2) I also tried after disabling system antivirus but nothing changed.

            Another problem: After making the very first program "hello world"(without introducing any space before the word "Hello") when I press build(ctrl+f9) it shows:

            === Build file: “no target” in “no project” (compiler: unknown) ===

            === Build finished: 0 error(s), 0 warning(s) (0 minute(s), 10 second(s)) ===

            Why “compiler: unknown” is showing in the first line? Although program executes successfully.

            IMPORTANT NOTE : I'M THE SAME PERSON WHO'S ASKING "[-std=c++14]" PROBLEM IN CHAPTER 0.5 Installing an Integrated Development Environment (IDE) COMMENTS SECTION.

            Here's our full conversation till now (read between "****" lines):

            May 9, 2017 at 2:17 am · Reply
            After installing code blocks,in global compiler settings I found the [-std=c++11] and also C++14 ISO C++ language standard [-std=c++14]. According to instructions I selected [std=c++14] and clicked ok. Now whenever I restart code blocks, the toolbar item called “Build Target” becomes faid in colour hence can’t switch between debug & release. Besides this, on restarting, under global compiler settings the [-std=c++14] is now vanished but [-std=c++11] is still there , so I have to check box C++11. On clicking other compiler options under compiler settings [-std=c++14] is showing. Every time when I opens code block the toolbar item called “Build Target” becomes faid or disabled by itself. What is the solution?

            May 9, 2017 at 12:03 pm · Reply
            When you start code::blocks, are you reopening a project? The build target should only be available once you’ve done so.

            May 10, 2017 at 2:27 am · Reply
            Is that means if I edit any previous program one or more time then I can’t get access to build and release function at the same time. Do I have to make new project again to get build and release function? And what about [-std=c++14] issue? why it vanished and present only in other compiler options tab(under compiler settings)?

            May 10, 2017 at 3:10 am · Reply
            Another problem: After making the very first program "hello world" when I press build(ctrl+f9) it shows:

            === Build file: “no target” in “no project” (compiler: unknown) ===

            === Build finished: 0 error(s), 0 warning(s) (0 minute(s), 10 second(s)) ===

            Why “compiler: unknown” is showing in the first line? Although program executes successfully.


            I hope this may clear some doubts.

            • Alex

              If it says press any key to continue, and you haven't done that yet, then your executable is still running until you do. If you open your operating system's task manager, you should be able to see whether the executable is still in memory or not.

              • Mahendra

                But I pressed key on asking to press any key to continue afterwards the black output screen vanishes itself, then how is it possible that process is still going on? I'm using 32 bit windows 7 Operating system, is there any possibility of occurring errors due to 32 bit and not having 64 bit system? Is there any different setting for code blocks to run in 32 bit system.

                • Alex

                  If you pressed a key and the console dialog went away, then your process has likely terminated. 32 vs 64 bit should make no difference here.

                  Do you have a virus scanner, and if so, have you tried disabling it?

  • My dear c++ Teacher,
    Please let me ask your help on my problem with visual studio community 2017 c++ compiler.
    I'm confused with projects and files.
    1. When I click File > Open > Project/Solution, a window appears with name "Open Project" and at left some directories and some of my projects. One of the directories is "Projects". Also in the main area there are other projects of mine.
    When I click "Projects" directory, other projects appear in the main area.
    Why this dispersion of projects?
    2. I have one question for the files too.
    When I click on some project and then on "Open", another list of directories and a file appears:
    .vs (project)
    Debug (project)
    selected project
    file with same name as selected project and with extension .sln

    When I click on selected project and then on "Open", another list appears:
    Debug (project)
    file with same name as selected project and extension .vcxproj

    Why so many files and duplicated projects?
    I searched in the web but did find answer.
    With regards and friendship.

    • My dear c++ Teacher,
      Please let me answer my own comment:
      To create a big project I need to learn programming by visual studio, so  to learn all its complexity.
      With regards and friendship.

    • Alex

      When you click Open > Project/Solution, Visual Studio is showing you what's on your hard drive, so you can find a project or solution to open inside the IDE.

      By default, all of your projects and solutions are saved inside the Project directory. What you're calling a "project" in #2 is actually a directory on disk.

      I can't speak to why Visual Studio decided to use the directory structure they did -- you'd have to ask Microsoft. Regardless, you generally don't need to worry about this, as it's application specific and outside of core C++.

      • My dear c++ Teacher,
        Please accept my many thanks for you replied my message and for your helpful answer.
        I describe situation somehow better than in my first message.
        After clicking File > Open > Project/Solution appeared window's name is "Open Project" and its path is
        C:/Users/Amandine/Documents/Visual Studio 2017/Projects
        In the list at left, under
        "Images" (with some picture at its left) there are 3 of my projects (with yellow rectangular at their left).
        Below them there is
        "Microsoft Visual Studio 2017" (with visual studio's logo at left)
        and under it there is
        "Projects" (with a yellow rectangular at its left)
        In the main area there is a complete list of my projects (each with yellow rectangular), including the three at left column. So these three are somehow duplicated.
        It means projects are sub-directories of directory "Projects" although with same rectangular.
        However, initially, I given path to project
        "C:VC2005Projects" later "C:VS2017Projects" and now I leave the default path that is
        c:/users/amandine/documents/visual studio 2017/Projects
        By the way, what does picture at upper left corner in your comments mean?
        Indeed it is not your picture!
        With regards and friendship.
        P.S. Unfortunelly your site does not show backslash character, so in paths I use common slash. G.T.

  • Jarod

    I want to start programming in c++ but i am not always on wifi what is the best compiler or ide to use that is free?

  • My dear c++ Teacher,
    Please let me say in "If you’re using the Visual Studio IDE" section, 4th §, recommend: "place them in a subdirectory off of your C drive, such as C:VC2005Projects." Today's Visual Studio edition is 2017. Then please change subdirectory's address to C:VC2017Projects.
    Also I do not understand why VC instead of VS.
    With regards and friendship.

  • TJ

    Can you use  "using namespace std;" before "int main()" instead of typing "std::" for every string

  • Alice

    I'm using SSD drive, will it still be as good on D:/?
    Why do you recommend setting the projects folder on C:/?
    I did the next tutorial and it was 21.5 MB which is a lot for such empty program.
    Thank you for all the effort.

  • Luke

    im using Microsoft visual studio 2017 and when I try to build solution it just says

    1>------ Build started: Project: HelloWorld, Configuration: Debug Win32 ------
    1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Platforms\Win32\PlatformToolsets\v141\Toolset.targets(34,5): error MSB8036: The Windows SDK version 8.1 was not found. Install the required version of Windows SDK or change the SDK version in the project property pages or by right-clicking the solution and selecting "Retarget solution".
    1>Done building project "HelloWorld.vcxproj" -- FAILED.
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    so what am I doing wrong

    • Alex

      What OS are you on? If you're on Windows 10, make sure you've installed the Windows 10 SDK and that your console application is using it. If you're on Windows 8, then I'm not sure (I don't have any Win 8 machines). You could try installing the Windows 8.1 SDK:

      • Luke

        I installed the Windows 8.1 SDK but now its giving me a different error message
        1>------ Build started: Project: HelloWorld, Configuration: Release Win32 ------
        1>c:usersspoeluk20documentsvisual studio 2017projectshelloworldhelloworldstdafx.h(10): fatal error C1083: Cannot open include file: 'stdio.h': No such file or directory
        1>Done building project "HelloWorld.vcxproj" -- FAILED.
        ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

        • Alex

          It sounds like maybe something in your IDE's configuration paths isn't set up correctly. I'm not sure how to fix this. Maybe try doing a clean uninstall of the compiler and reinstall, making sure to install any SDKs in the right-hand pane that it allows?

  • fysher5

    when i want to find an IDE you talked all about Microsoft, or Windows, but what about using apple or a Mac

    • Alex

      Code::Blocks used to work for Mac but it looks like they don't have enough Mac developers interested in helping them produce Mac versions any more. I'd probably recommend xcode on Mac now.

  • Joseph

    I was suuuuper confused, but then after a while a realized I had Microsoft Visual Code, which isn't an IDE. :')

  • Matthew

    Every time I Orin the program it closes almost instantly! Anyone know how to fix it?

  • C++ Student

    What if I'm using an app on android. I am unable to download code::block or other compilers listed. I downloaded Mobile C but I can't find anything labeled project. I AM NOT COMPLAINING IF YOU HAVE NO SOLUTION. I love this website. GREAT WORK!

  • Mehdi

    Thanks a lot.this site is wondeful.

  • Sahaj

    what is wrong in this code??
    If I give input 1 2 3 4  then it shows output 2 0 0

  • Ashish Patel

    Hi Alex,

    After posting this question on Jan 1, I went through old comments and found similar post with your response pointing out win32 application and it helped me to correct the mistake. You have created a wonderful website and I would like to sincerely thank you. I am determined to finish all tutorials within a month. Wish you a very happy and healthy new year.

  • Ashish Patel

    I intalled Visual Studio Community 2015 on my 64 bit system that has Windows 10. When the first program code for "Hello World" was tried exactly as per the tutorial, I am getting following errors.

    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\babu\OneDrive\documents\visual studio 2015\Projects\HelloWorld\HelloWorld\MSVCRTD.lib(exe_winmain.obj)    1    

    Severity    Code    Description    Project    File    Line    Suppression State
    Error    LNK1120    1 unresolved externals    HelloWorld    c:\users\babu\onedrive\documents\visual studio 2015\Projects\HelloWorld\Debug\HelloWorld.exe    1    

    Can anyone guide me as to what steps need to be taken? Thank you.

    #include "stdafx.h"  
    #include <iostream>

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

    • Alex

      It sounds like you created a Win32 application instead of a console application. Try recreating your project, and make sure you choose console application this time.

  • Dio Dziban

    Visual Studio Community is A LOT more confusing on the left side and idk how to get anywhere. There's no helloworld.cpp, and if there is idk how to get there. I waws following your tutorials with a mac running code::blocks up until 3.4 and then decided to switch to windows. It is a lot more confusing than code::blocks was, please help me find everything or point me to a tutorial where it shows me, thanks!

  • Ginnungagap

    I'm using code::blocks and I'm always getting this error:
    -------------- Build: Debug in HelloWorld (compiler: GNU GCC Compiler)---------------

    g++ -Wall -fexceptions -g  -c home/.../main.cpp -o obj/Debug/main.o
    /bin/sh: 1: g++: not found
    Process terminated with status 127 (0 minute(s), 0 second(s))
    0 error(s), 0 warning(s) (0 minute(s), 0 second(s))

    Sorry I know this request is dumb but I've searched it on google and I didn't get an answer

    • Alex

      It sound like you probably didn't install the version of Code::blocks that comes with G++. Make sure you downloaded and installed the version that comes bundled with MinGW.

  • Magis

    First of all, I want to say that your tutorials are the best I have found on the internet, and they are very simple and pedagogical. Thank you for that 😉

    But I have a problem when i compile my program. I use the Hello World! sentence, and change it to something else. But the words Hello world! still appears on to the screen when compiled, and not the sentence i want. I may have overlooked the answer in the tutorial, and if i have, it would be awesome if someone would show me where it is. 😉


    • Alex

      Hi Magis. That definitely shouldn't be happening, so you're likely doing something wrong. But it's hard to say what. I also don't know what compiler you're using.

      Here's the steps you should be taking:
      1) Make sure your program is not still running. This is important, or your compiler won't be able to overwrite the executable.
      2) Change "Hello, World" to something else.
      3) Recompile. Make sure you see the file compile and link, and that there are no errors.
      4) Run the executable produced.

      You should see the new string. If that doesn't work, maybe try finding the executable file on disk and check the timedate stamp. Try recompiling and see if it changes. Maybe it's compiling a different file than it's running or something bizarre like that.

  • Abhay

    Thanks Alex.A really good tutorial.

  • Jagdeep Singh

    What is the crazy reason that c++ is not selected default in ms vs?

    • Alex

      Microsoft says that in the long run they intend to make ALL the programming languages optional, and you will choose which ones you want. So far, they've only done this for C++ though.

  • umm, not to be mean, but i can do that with a  Batch file...

    @echo off

    echo Hello World!

    This is also much shorter...

    • Alex

      You can. You can also do it in Java, Python, Perl, or any number of other compiled or scripted languages. But this is a C++ tutorial, and we have to start somewhere.


    Some information for fellow Eclipse users. My university requires Eclipse and to start off, make sure you installed the C++ IDE of Eclipse not the Java IDE which is provided at the front page of
    The next step is to install a compiler because Eclipse has NO OWN C++ COMPILER. My uni recommended MinGW, other compilers may work as well but I can only tell what I did. When you downloaded the MinGW setup and installed it, mark the "mingw32-base" and "mingw32-gcc-g++" packages and apply the changes to install. To check if you've installed it correctly, open the cmd of windows, type "g++" and enter. It should say at the end "compilation terminated".
    It is possible that you're now able to build binaries and run the compiler but to make sure, you've to check if Eclipse finds the compiler's path. Go to your Windows System > Advanced System Settings > Environment Variables. Then look for your User Variable called "Path". If there is none, create it. Now look if the path to your MinGW bin-folder is written in there. If not, search the bin-folder of MinGW up and paste the path in there. My path was something like this "C:\MinGW\bin".
    If you try to compile the Hello_World.cpp now and the console throws the error "program 'make' wasn't found" or something like that, go into the MinGW bin-folder, look out for a file named mingw32-make.exe and rename it to the wanted "make.exe". Try to run the program again, it should success.

    Quite a damn hassle to figure this all out.

    • SomeNEEEERD

      Instead of changing the file name. Just open "Project" when you've created a project folder, then "Properties" > C/C++ Build > Change "Builder type" to "Internal Builder".

  • GEScott71

    My Hello World worked the first time - thanks!  Using Visual Studio 2015 on Windows 7.

  • Hey Alex, I just wanted to let you know that I really appreciate your effort into creating this website that has almost sprouted into a community, and I just have one question: Do you work full time on this website, or do you have another full time job other than this website
    By the way, I just started my journey into programming today 😀

    • By the way, is it weird I only get the "========== Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========" and not get the "succeeded" and the "compiling..." words?

      • Alex

        Most likely not weird at all. The compiler is telling you that it didn't need to recompile 1 file because it was already compiled previously and hadn't changed.

    • Alex

      I have a full time job outside of this website. This is just a passion project I've been working on for the last 9 years.

      Good luck in your journey!

  • Gurpreet

    i installed video studio but i don't have "win32 console application" as a template. What should i do?

  • John Clark

    I'm having problems with my first compile Visual Studio HelloWorld.cpp

    #include  gives error --- expected file name found new line

    <iostream> gives error ---- expected a declaration    

    std::cout << "Hello  gives error --- missing closing quote    
    same error for:

            world!" <<


    #include "stdafx.h"

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


  • Amy

    when i put the code in codechef, nothing happened.
    May i find out why?
    Thank you!!

  • Abdurahim

    Thanks Mr Alex.
    I did it during 2 week ( Installing IDE and writing "Hello World" )
    in that time I met different problems ( Can not installing IDE's and Ftal Errors )
    But I fixed all of them ( even I reinstalled My Windows )
    Now everything ok !

Leave a Comment

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