Search

0.6 — Creating a console project and compiling your first program

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

Projects

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, the 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 command line (though we’ll generally launch our programs from within our IDE).

Here’s a screenshot of the Windows command line:

Windows command line

By default, console applications have no graphical user interface (GUI), print text to the monitor, 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.

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.

Warning

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

To create a new project in Visual Studio, 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.5 -- Installing an Integrated Development Environment (IDE) and reinstall your Visual Studio as indicated.

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 version of Visual Studio have a different style, but most of the same fields):

Visual Studio 2017 Desktop wizard

Make sure you uncheck Precompiled Header.

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

On the left side, 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 2017 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 compiler:

To compile your program, either press F7 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.cpp
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 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, though we recommend you save it in a subdirectory off 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!

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 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 compilers (such as Bloodshed’s Dev C++) 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 compiler, 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 (right 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 compiler 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).

Conclusion

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.

Configuring your compiler: Build configurations
Index
0.5 -- Installing an Integrated Development Environment (IDE)

372 comments to 0.6 — Creating a console project and compiling your first program

  • Thomas Keith

    Alex,

    I commend you for keeping up this site for so many years.  I'm looking at retiring soon, probably becoming an expat since it's so expensive to live in the US, and want to be able to make some income from anywhere there is a decent internet connection.  So, programming seems to be the answer, and C++ can be a nearly universal answer.

    However, I have run into an issue.  I installed Visual Studio 2015 and followed all your installation advice, but whenever I successfully compile, execution shows a flash of an empty DOS box.  Attempts to make the box persistent have been fruitless, and the box seems empty of my text, though it is just a flash and I can't be sure of that.  I am copying and pasting your code, so I don't think that's it.

    Help me, Obiwan, er.. I mean Alex, you're my only hope.

    _aleph_

  • Gurjot

    Can i use codechef compiler as an alternative

  • Madhav

    I am using community 2013
    whenever i am writing Hello world.cpp
    #include "stdafx.h"
    #include <iostream>

    int main()
    {
        std::cout << "Hello world!" << std::endl;
        return 0;
    }
    // The test result show me "this project is out of date"..
    would you like to continue
    when i go to continue it show me path file error of win32 console
    //

  • troll

    thanks alex for doing this website. A great idea that has helped a lot. I found this site while I was looking for a great gaming language to code in after learning javascript, processing, HTML5, CSS, and SQL in that order. C++, with your site, will easily be my next language.

  • Zerocool

    I am using Visual Studio 2015 and it doesn't let you choose any type of Template other than 'Blank App(Universal Window). But when you
    R-Click>Properies>Configuration. It shows that the platform is indeed Win32.
    So,

    When I type in:

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

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

    I get two Errors in the Error List

    Severity    Code    Description    Project    File    Line
    Error    C3940    'EventRegistrationToken': identifier not found - possible mismatch between compiler and library versions. Please ensure vccorlib.h/.lib, vccorlib120.dll and c1xx.dll match    App1    c:program files (x86)microsoft visual studio 14.0vcincludevccorlib.h    348

    Severity    Code    Description    Project    File    Line
    Error    C1903    unable to recover from previous error(s); stopping compilation    App1    c:program files (x86)microsoft visual studio 14.0vcincludevccorlib.h    348

    These occur when I try to Build the project and bring it to life.

    Any help would be appreciated.

    Thanks.

    • Zerocool

      An error on my part previously, I was using Microsoft Blend for Visual Studio 2015... I just searched Visual Studio 2015 on my search bar and came up with a different one. When you choose New Project it gives you several choices to choose the different type of project, and Win32 is one of them.

      This time I input the previous lines of code and it worked when I tried the CTRL+F5.

      Took some trial and error.. but I got it figured out!

  • jojo

    when and why we create empty project in VS??????

  • milan subba

    there is no win32 project in visual studio 2015.. what i have to do next.. i am stuck here.

    • Alex

      When creating a new Project, you looked under Templates -> Visual C++ -> Win32?

      Visual Studio 2015 Community doesn't install C++ by default, you have to turn it on when you install. Did you do that?

    • Tom

      Have you just opened up Visual Studio for the first time? If so, there should be a 'skip this part' link somewhere. Then complete the set up and go in and open a new project as described above.

  • Rasmo

    on my first try it failed, but i looked through and found my mistake, i feel like i have lifted a truck :D.

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">