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 (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)

568 comments to 0.6 — Compiling your first program

  • Andrew Dandrea

    Dear Sir:
    I was typing in the code as follows  in VS in windows 10

    After staring the build the project has failed. I don't understand the error.  Did I mispell an indentifier?

    ------ Build started: Project: HelloWorld, Configuration: Release Win32 ------
    1>c:\vc2018projects\helloworld\helloworld\helloworld.cpp(9): error C2653: 'Std': is not a class or namespace name
    1>c:\vc2018projects\helloworld\helloworld\helloworld.cpp(9): error C2065: 'cout': undeclared identifier
    1>c:\vc2018projects\helloworld\helloworld\helloworld.cpp(9): error C2653: 'Sid': is not a class or namespace name
    1>c:\vc2018projects\helloworld\helloworld\helloworld.cpp(9): error C2065: 'endl': undeclared identifier
    1>Done building project "HelloWorld.vcxproj" -- FAILED.
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    • Alex

      std needs to be all lowercase, as C++ is case sensitive.

    • Martin


      1.) Lowercase, as Alex said
      2.) You wrote "sid::endl;" but it has to be "std::endl;"

      change "sid" to "std" and respect the lowercase, then all should be fine.

  • Mark

    Why the codes are already written on codeblock when you build a new project?
    If you want to write your codes on codeblock, is it mandatory to write std::cout<<"Hello World"<<std::endl;        
    or can you just write cout<<"Hello World"<<endl; ?
    This is not related to this chapter, but what are #include<cstdio>, #include<cstdlib> and #include<cmath> used for ?

    • nascardriver

      Hi Mark!

      > is it mandatory to write std
      No, std:: can be omitted when you're 'using namespace std;'. Don't use 'using namespace', it will cause naming conflicts.

      > cstdio
      Allows you to use functions for console input and outpu

      > cstdlib
      Allows you to use string conversion and memory management functions.

      > cmath
      Allows you to use mathematical functions

      • Mark

        So functions for console input and output is basically every time you have to write cin>> and cout<<, you have to include <cstdio>. And what are the string conversion and memory functions? Is <cstdlib> used for pointers?

        • nascardriver


  • Alex Thomas

    I keep getting the following error message

    Severity    Code    Description    Project    File    Line    Suppression State
    Error    C2143    syntax error: missing ';' before '}'    HelloWorld    c:\vc2005projects\helloworld\helloworld\helloworld.cpp    9    

    I have tried putting semicolon in several locations but nothing seems to work. I have even copied and pasted but still keep getting the same error message.

    Pls help

    • nascardriver

      Hi Alex!

      Please also share the code you were trying to compile along with the error message.
      Save the file before compiling it.
      I suggest you upgrading your IDE, it looks like you're running an old version of VS.

  • Alex Thomas

    Hi Alex - after selecting Projects and clicking C++ - still dont see any win32 - I only see
    1. Windows Console Application
    2. Windows Desktop Application
    3. Empty Project

    Pls advise

    • nascardriver

      Hi Alex!

      Select "Windows Console Application" or "Empty Project".
      "Empty Project" is suitable for everything but might require further setup. It should be enough for what you're learning here.

  • Joe

    Hello everybody,

    I am having an issue with visual studios on a new computer.
    I just received an old lap top that i am going to put to use as my sole coding platform.
    I downloaded the latest version of VS and attempted to code but I am having some major issues.

    at first it would simply say a task was cancelled and not even open up the window.
    next it would say it could not open a pdb file.  For that issue I went into

    tools>options>debugging>general> load dll exports (native only)

    and that did nothing, next I went into

    tools > options > debugging > symbols

    and then checked microsoft symbol servors which allowed me once or twice to run my program but now
    it keeps telling me my program exited with code 0 and it does not even open the window.

    I am unsure why it will not work on this computer.  Any ideas?

    'ConsoleApplication1.exe' (Win32): Unloaded 'C:\Windows\System32\ucrtbased.dll'
    The thread 0x2758 has exited with code 0 (0x0).
    The thread 0xd24 has exited with code 0 (0x0).
    The thread 0x23fc has exited with code 0 (0x0).
    The program '[8996] ConsoleApplication1.exe' has exited with code 0 (0x0).

    • nascardriver

      Hi Joe!

      Looks your your program is running but finishes so fast that you cannot see the console window. Try this code

      VS also has an option to keep the console open without modifications to the code. I don't have VS, I cannot assist you any further if this is not the cause.

  • Worakorn

    My program doesn't seem to work...

    I'm using visual studio 2017

    • nascardriver

      Hi Worakorn!

      What makes you think it doesn't work? Any error messages? What's happening?

      Don't use 'using namespace'.

  • nitin

    hey. I am seriously new. actually I like using and learning about my computer. I don't understand what endl is. can I learn all this stff now or I have to take anyclasses. I am 14

    • nascardriver

      Hi nitin!

      You don't need any programming experience. learncpp is written for absolute beginners.
      @std::endl is covered in lesson 1.3a, it was used here because you need some code in order to show how compilation works.

  • Doe

    When I tried to run the code through the command line, it said:

    'g++' is not recognized as an internal or external command, operable program or batch file.

    I then took a look at the 0.7 tutorial, where you said to input "-std=c++11" to the command line, but then I got the following error:

    '-std' is not recognized as an internal or external command, operable program or batch file.

    Everything else runs fine, it just won't run directly through the command line. Do you know what causes the error? (Is it really necessary to compile the program from the command line, it appears to compile just fine from visual studio itself) I'm using visual studio 2017.

  • Dear Teacher, please let me report you following problem. In Visual Studio 2017, following program is not built.

    But following is built.

    In general, does #include's precedence matter? Regards?

    • nascardriver

      Hi George!

      There's no problem with includes. If you have enabled precompiled headers in your project settings you have to include stdafx.h, if you disabled precompiled headers you cannot include stdafx.h.

    • Alex

      In general, no, order of #include files shouldn't matter. If it does, then it means a header file isn't properly including all of its dependencies.

      However, stdafx.h isn't a normal header file. It's a special header file that Visual Studio uses if precompiled headers are turned on (which they are by default). If you're using precompiled header, stdafx.h must be the first line of any code file compiled.

  • Dong Huh


    I have a short question. What is a Cross Platform Program?

    • nascardriver

      Hi Dong!

      A cross platform program is a program that can be compiled for multiple platforms (Windows, Mac, Linux, etc.).
      Each platform offers some features that won't work on other platforms. If those features are used by a programmer without writing an alternative for other platforms the program won't work on other platforms. Using platform dependent features should be avoided.

  • dorsalis

    Thank you for that great Tutorial. I tried different ones but this here actually even always answers my questions coming up when I process through it. Other ones would rather produce more questions than provide answers. And yours ist structured well. I'll make sure to buy u a coffee once 😉

    I tried get running  with "Visual Studio Code" but that is kind of wierd. Got so far that I installed the C++ addon but that actually is all I was able to get. Took me some Time to find out how to get to the debugger but once I've been finally there, there always is an error prompt that I have to configure I file first (.json). I searched the online-docu there but got more confused than a solution how to fix that. Do you maybe have a tip for me?

    Thank you!

    • nascardriver

      Hi dorsalis!

      Sounds like you install Visual Studio Code (vscode). vscode is a text editor. What you're looking for is Visual Studio ( ). The Community edition is free and does all you need.

  • Jeeba

    Hello World!

    Process returned 0 (0x0)   execution time : 0.063 s
    Press any key to continue.

    Why does it show that and not only the Hello World! text?

    • nascardriver

      Hi Jeeba!

      The last two lines are generated by your IDE so you know if your program ran successfully or crashed (Return value = 0 means success) and how long it took to run.
      The "Press any key to continue." is there, because your program would finish so fast that you wouldn't be able to see the output.

  • jenn

    Hi! I learned C++ back in college but, like all students, forgot what I learned after receiving my grades. Back then we were taught using NetBeans IDE but code won't work. But I am 100% sure NetBeans can run C++ I even looked it up xD

  • Daniel

    Hello Alex,

    When I attempted to create a new project via File->New->Project, the space on the left (where I should have found the project types) was empty. I have searched online, and the general consensus is that this is a simple instilation error; however, I have reinstalled the program (MS Visual Studio 2017) with no change. I also did not see anything amiss on the installer page. Did I miss something, or do I need to aquire the project types as a seperate package?

  • paisley

    using Code::Blocks on windows 10

    After following instructions for creating the file and location, I keep receiving an error message indicating that the file could not be saved [and suggesting it may be write-protected]. What does this mean? Should I save the file in a different location?

    :EDIT: I forgot to include the backslash before CBProjects in the file location. I corrected this and the problem went away. Thank you for your tutorial, Alex, I really appreciate it!

  • Gursimar Miglani

    Hey Alex
    I have the following query:
    Are projects heavier than individual files?(in terms of space they take up on the hard disk)
    Should I create a new project for every program that I run instead of a cpp file?
    If I want to experiment with different programs, dont you think projects are a bit slow?

    • nascardriver

      Hi Gursimar!

      "Are projects heavier than individual files?"
      The project contains the files, so yes.

      "Should I create a new project for every program that I run instead of a cpp file?"
      Definitely yes.

      "If I want to experiment with different programs, dont you think projects are a bit slow?"
      If you really want to experiment with different programs then you should create a project for each program. If you just want to experiment with different functions or features you can do that in a single project.

      • Gursimar Miglani

        Thanks! Btw since I am also learning Python, and use the Spyder IDE, I was previously unaware of the concepts of projects, and I was working with standalone files themselves.

      • Joe

        I am lost here.

        Why would I create a new project for every program, instead of a new cpp file?

        On my other computer, just for fun, I created a new cpp file for all of the examples given
        on the web site, as well as some things i wrote for fun.  I used my main to call all of these
        other cpp files and run them.

        so what I am understanding, is that my code written for mathematical formulas that can be used
        by all of these would be written in one project, while each of the other programs such as ball
        drop both original and modified would best be written in a project of their own?

        For some reason I am having trouble wrapping my brain around this.

        • nascardriver

          Hi Joe!

          I answered @Gursimar's question in a general way, not related to learncpp.
          If you only have single-file projects (like it is for the most part on learncpp) and they are somehow related to each other you can of course have all of them in one project. If you're writing an actual program, with multiple files, it should not be mixed with foreign files.

  • Frederico

    Hello Alex,

    I have taken a c++ course in college back in 2007 but I'm taking the tutorial to to recap and further my knowledge. I noticed you said all examples will be console programs. This was one of my biggest frustrations, that I could not move past the console applications and make programs with GUIs. After learning the basics ( I still need to master the basics) how do I go about learning to make GUIs with c++? There is a lot of information on the web but I have not found something that takes you step-by-step like this tutorial.

    • nascardriver

      Hi Frederico!
      GUIs in C++ aren't easy, not because they're difficult to understand, but because there's no universal way to write them. You could learn Windows Forms, but they're Windows only. Or you use a framework (GTK, QT) which runs on multiple OSs but requires libraries. There are probably tutorials somewhere but most of the work is going to be reading documentations.

    • Alex

      To make GUIs in C++, you'll need the help of a 3rd party UI framework of some kind. Deciding which one to use is probably the hardest decision -- figuring out how to use them tends to be a bit easier because there are often internet tutorials on how to do things like create a window, populate widgets, and run the event loop. Many UI frameworks also come with sample apps that you can compile and run, and then inspect to see what they're doing.

  • Anon


    Do you have any examples of how these steps can be done on Xcode?
    Because I'm having quite a bit of problems with Xcode and i'm not sure where to begin

  • William Green

    When I try to create a project using Codeblocks, everything runs smoothly until I hit "Finish", then I get an error message saying Codeblocks couldn't create the file. It doesn't tell me why it failed to create the file, either. I'm using a Mac, did I fail to install something correctly?

  • Mahdi Hajji

    ERROR: You need to specify a debugger program in the debuggers's settings.
    (For MinGW compilers, it's 'gdb.exe' (without the quotes))
    (For MSVC compilers, it's 'cdb.exe' (without the quotes))

    after debugging my program i get this comment what does it mean?

  • Michael

    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\Name\source\repos\HelloWorld\HelloWorld\MSVCRTD.lib(exe_winmain.obj)    1    

    Got this error, help says it doesn't recognize the "main" function. how is this a thing? it's the main function!!??

  • ZPeU

    Help! It says: mingw32-g++.exe: error: unrecognized command line option '-std=c++14'

  • Josh

    Wow, I am very glad I found this site! This is gonna help me a ton! Can't wait to get my computer back so I can use the knowledge of these lessons :p (btw, learning this in IT class rn. it's not about c++, but I'm doing these lessons after I am done with class work.) Just wanted to show some gratitude 🙂

  • aditya

    i got  this error when i try to compile the helloworld program in codeblocks.

    ||=== Build: Debug in helloworld (compiler: GNU GCC Compiler) ===|
    C:\Program Files (x86)\CodeBlocks\MinGW\include\ctype.h|24|error: conflicting declaration 'char _ctype []'|
    C:\Program Files (x86)\CodeBlocks\MinGW\include\wctype.h|99|note: previous declaration as 'short unsigned int _ctype []'|
    C:\Program Files (x86)\CodeBlocks\MinGW\include\pthread.h|246|error: 'pid_t' was not declared in this scope|
    C:\Program Files (x86)\CodeBlocks\MinGW\include\pthread.h|247|error: 'pid_t' was not declared in this scope|
    C:\Program Files (x86)\CodeBlocks\MinGW\include\pthread.h|247|error: expected primary-expression before 'int'|
    C:\Program Files (x86)\CodeBlocks\MinGW\include\pthread.h|247|error: expected primary-expression before 'const'|
    C:\Program Files (x86)\CodeBlocks\MinGW\include\pthread.h|247|error: expression list treated as compound expression in initializer [-fpermissive]|
    ||=== Build failed: 6 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

  • Benjamin

    I get this error, when I copy the HelloWorld code into Studio 2017. I tried to Retarget solution, but it's the same.

    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 ==========

  • Patrick

    Hello Alex
    This is my error list
    How can i fix it ?

  • Gautam Kumar

    Hii Alex sir, I have downloaded VS 2017, tried to creat a new project but under visual c++, it shows
    Windows Desktop
    No option of win32 console.

  • Mike

    Hello Alex - I successfully built the file, but when I run it, I get this message:

    Unable to start program

    The system cannot find the specified file.

    What's up with that?


    • Alex

      Could be any number of things. Most likely, you compiled but didn't link the program into an executable. If you did, try disabling your virus scanner or antimalware and see if that helps.

Leave a Comment

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