Search

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!

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, 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.

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 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 doing a full reinstall, you can run the Visual Studio installer and modify your existing install 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.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 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, though we recommend you 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).

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.


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

768 comments to 0.7 — Compiling your first program

  • jeff

    Hi, I have a c: SSD and a d: HDD but my SSD is small so I try to download/save stuff on my HDD.
    Whilst installing Microsoft visual studios I selected d: and it said `This drive will affect the performance of Visual Studio and cause it to run slower.`
    Is this significant? if I do not need to save my projects in the same file as my ide then I can download MVS on the SSD and save projects in the HDD.
    Could you tell me what I should do in this situation?

    • nascardriver

      Install it on the HDD. If you're not happy with the performance, reinstall on the SSD. VS itself is huge (~20GB), if your ssd is small, you probably don't want to use it for VS.

  • Medhat Diab

    Visual Studio 2019 Users: After clicking Create, You won't see the last dialog Which is called: Windows Desktop Project.
    You will need this to disable (Precompiled Headers) and also to nake Application Type: Console, to do that follow this steps:

    1- In Solution Explorer press right click on your project name --> Properties --> C/C++ --> Precompiled Headers --> Precompiled Header (The first one on the top) Then Choose: Not Using Precompiled Headers.

    2- Linker --> System --> SubSystem --> Choose: Console.

    3- Press Apply and Ok.

  • Dear Teacher,
    Please let me say regarding "If you’re using g++ on the command line" section that there are not instructions for install gcc-MinGW. Then I suggest following
    quote
    Go to https://sourceforge.net/projects/tdm-gcc/ and during downloading
    1. On "Wizard Action" click [Create].
    2. On "Select Edition" select MinGW/TDM (32-bit) > click [Next>].
    3. On "License Changes" click [Next>].
    4. On "New Installation: Installation Directory" click [Next>].
    5. On "New Installation: Download Mirror" click [Next>].
    6. On "New Installation: "Choose Components" click [Install].
    7. Wait till [Next>] be brighten, then click it.
    8. Click [Finish].
    9. Close README text file.
    10. Open a command Prompt.
    quote
    Also let me say you that file HelloWorld.cpp should be placed in a folder, e.g. gccProjects and commands be typed at the prompt of this folder e.g.
    C:\gccProjects>
    Also let me point out that project's name could be any valid name e.g. project-1. So command for compile program could be
    C:\gccProjects>g++ -o project-1 HelloWorld.cpp
    Then command for run program could be
    C:\gccProjects>project-1
    Regards.

  • Vitaliy Sh.

    Between the titles "If compiling fails" and "Conclusion", there is a duplicate of 0.8's "Q: When executing a program, the console window blinks and then closes immediately.".

    • Alex

      That's intentional. It's one of the most common issues new users encounter, so I didn't want to send new users to another lesson to find a solution. But since 0.8 is a roll-up of common issues, it seemed appropriate to put it there as well.

  • Vitaliy Sh.

    Hi people!

    Why "ctrl" is preffered here over "Ctrl"?

    https://en.wikipedia.org/wiki/Control_key#Notation
    https://en.wikipedia.org/wiki/Control_key#Table_of_examples
    https://wiki.archlinux.org/index.php/Keyboard_shortcuts

  • Vitaliy Sh.

    Hi!

    ... Some compilers (such as Bloodshed’s Dev C++) don’t automatically pause the console screen after the program has finished executing. ...

    Typo: "compilers" instead of "IDEs".

    Diagrams in previous lessons are so beutiful, that refer compiler in connection with already compiled app isn't fit.

  • Vitaliy Sh.

    ... that can be run from the windows, linux, or mac console. ...

    Minor typo: non capital letters in "Windows", "Linux", "Mac".

  • Vitaliy Sh.

    ... save it in a subdirectory off of the C drive, such as C:\CBProjects. ...

    Possible Typo: "off of", while still in C:\.

  • Vitaliy Sh.

    ... or go the Debug menu and choose Start Without Debugging ...

    Typo: no "to" between "go" and "the".

  • Vitaliy Sh.

    Hi.

    There is two different scripts of key Ctrl, three with lower case "c", one with capital "C":

    {
    ...(if this doesn’t work, try Ctrl-Shift-B)...
    ...To run your compiled program, press ctrl-F5,...

    ...To build your project, press ctrl-F9...
    ...To run your compiled program, press ctrl-F10,...
    }

    Maybe add some unification?

  • Vitaliy Sh.

    ...It’s recommended you also check the Place solution and...

    Typo: no "that" between "recommended" and "you".

  • Vitaliy Sh.

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

    Maybe better:
    ... (GUI) - they print text to the monitor, read ...

    Maybe even change "monitor" to "console", for it were mentioned already: above and below of that sentence?

  • Sinethemba Zungu

    How do you enter "()" bracket characters on Linux command line in order to create a new directory for a new project? Example this command line ("mkdir Program Files (x86)/builds") give the following error: "bash: syntax error near unexpected token `('"

    • nascardriver

      You don't need a "Program Files" directory on linux, you can create the project wherever you want, eg. in "~/projects/".
      If you really want a name with parentheses and spaces, you can write the path in quotation marks.

      -p automatically creates parent directories.

  • Dear Teacher,
    Please let me ask you whether confirm following: In section "If you’re using g++ on the command line" first paragraph to be replaced by "In directory C: create folder "Projects cmd" and paste the following into a text file named HelloWorld.cpp and save in C:\Projects cmd."
    After program to be written:
    "
    From the command line
    C:\Projects cmd
    type:
    g++ -o HelloWorld HelloWorld.cpp
    "
    Regards.

    • nascardriver

      Hi!

      It doesn't matter which directory you create the file in, you can place it wherever you want. Adding a path to the lesson would make it less portable. There's a path in the Code::Blocks section, because Code::Blocks needs a path to create the project at.

  • Hello! At Visual Studio 2019, How can I zoom out/in the entire page of it? I am not able to see the (NEXT) button below when you create a new project and click the Windows Desktop Wizard. does anybody hear knows how to fix this error?

  • Monolog

    I have a problem, I´m from the Czech Republic and when I want to write down anything like bracket or semicolon I have to press buttons that are basicly shortcuts for steps in Visual Studio. So the only option for me is to change to US keyboard in Windows, but I´m not really used to it. For example curly brackets are in CES Ctrl+Alt+B / N etc.. Is there any chance to fix this or should I start getting used to US keyboard?

    • You can change the affected shortcuts in visual studio's settings.
      I suggest learning the US layout (Or even dvorak if you're up for some fun). Pressing more than 2 keys to get 1 character is slow and might hurt your hands if you're writing a lot of code.

  • Orphic

    Hello, world!
    C:\Users\Orpheus\source\repos\HelloWorld\Debug\HelloWorld.exe (process 2452) exited with code 0.
    Press any key to close this window . . .

    can someone help me understand why is the 2nd line is seen in my console window unlike his?

  • David Cane

    And I have another question.Do ALEX has other websites or blogs regarding programming.
    I prefer C/C++ ,but other kinds are also fine.

  • David Cane

    Hi,I am just going to be a freshman.I have already had a rough understanding of C.
    But I would like to learn C++ as well.Any tips?
    Moreover,what else should I read or browse if I want to learn C++ deeper.
    For instance,some books,some websites?

  • David Cane

    This is extremely helpful,thank you for all your efforts.

  • Jeff

    Just as an FYI,

    Im assuming visual studio code came out after the initial postings. I would recommend using that instead of the full blow visual studio, it is still free but less confusing and no real need to make "projects" just create a file with the .cpp  extensions and your good to go. also has a built in terminal so you can compile and run without ever leaving the editor.

Leave a Comment

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