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

Here’s a screenshot of the Windows console:

Windows console

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.

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

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

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

For Linux users

Linux users may need to install the build-essential package before Code::Blocks will compile on Linux. From the terminal command line, type:
sudo apt-get install build-essential

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


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

671 comments to 0.7 — Compiling your first program

  • Viridian

    Just a small typo on the last sentence of first paragraph:
    "When you choose to compile your program, *the* all of the .cpp files in the project will get compiled and linked".

  • Hi I made it
    everything worked smoothly although it reported an error first but I took a deep breath,analyze this error and got rid of it.
    I am happy to learn here, Alex you be too much.

  • Kushal

    What does precompiled header means ? Why did you turn it off ?How does it affect the build and compile operation ?

    Regards
    Kushal

    • Alex

      Precompiled headers are an option that, if used correctly, can speed up compilation times for large projects with lots of files. Since precompiled header support varies by compiler, and our examples are fairly small, we turn them off for simplicity. This helps keep the examples shorter, and reduces the number of potential things that can go wrong when trying to learn.

      But for large programs, precompiled headers can be very useful. I've added an item to my to-do to come back to precompiled headers in the future and talk about them some more.

  • Kamal

    Hello, till yesterday ide was working good but today I start getting a problem console closed even before checking the output, I also included stdafx or pch header file but showing error “cannot open source file” and “cannot open include file pch.h: no such file or dictionary”

    Now what should I do

  • Tristan

    i get this error: Object reference not set to an instance of an object. I haven't made any typo, I rechecked 5 times

  • Louis Cloete

    @Alex, in section "If your program runs but the window flashes and closes immediately", you have:

    Should be:

  • GG

    on the top of this page : the author wrote: "new programs within our Integrated Desktop Environment (IDE)", this is incorrect, IDE stands for Integrated development environment.

    Also, it would be nice to have navigation arrows at the top as well, scrolling to the bottom to go from page to page each time is not very ergonomic

    Other that these ......This course is pretty amazing !!!

    • Alex

      Thanks for pointing out the typo.

      I figured most users would read the lesson and then navigate, not navigate right off the bat. How are you navigating the site in such a way that a top-nav to adjacent lessons would be useful? Thanks!

      • GG

        Top navigation is very useful when searching  prior lessons for forgotten bits which often relate to one's current lesson or confusion...

        True learning requires retaining informations which require repeat reading and checking things few times

        Your entire C++ course is particularly well fitted and conducive to such type of learning behaviors patterns, as everything is concise yet comprehensive and all info must be retained.

        Put yourself into a beginner's mindset (which I know you did writing these great lessons and this is why people love it so much).   This is not like linear story book that only goes forward... people get confused,  forget bits, need to check things again, you also make reference to past lessons as well.
          
        Going back to the table of content is one more click plus a long scroll to the bottom and does not show you anything but a title.
        Likewise, getting to previous page button requires the same scrolling down, if this happens to be the wrong page, another scroll down is required to get to the previous page  and so on..  
        This can be done much more ergonomically with top navigation.
        Hence, top navigation is always great to have and to scan back thru stuff swiftly or ( even scan forward to check what's coming next for motivation and curiosity....)

        Also, Imagine a very tall book that you could only flip thru from the bottom of each page!

  • Addison

    I have a Mac and I used XCode 10.1. A helpful video on Youtube is titled "How to Create First C++ Hello World Project using Xcode Mac OS X."

  • Rob Rodgers

    Hi,

    I got this as the output, instead of the clean version you posted.  Is that something I can avoid?  I'm using VIsualStudio 2017 Community, version 15.9.4.

    thanks!

    ***

    Hello, world!

    C:\Users\rrodgers\source\repos\HelloWorld3\Debug\HelloWorld3.exe (process 25180) exited with code 0.
    Press any key to close this window . . .

    • Running without a debugger should not keep the console open. See the yellow "For Visual Studio users" box.

      • Aurme

        I have the same display as Rob Rodgers, but with version 15.9.5.

        I am unsure how you're answer addressed the question. This prompt is given when not in debug mode, either by using ctr + f5, or when using Debug > Start Without Debugging.

        I see the pathway shows Debug in it, even when we do this, however, could you shed any more light please?

        It still shows the pathway after either running without debugging, or using the above code.

        • Alex

          You're seeing this in the console window? Not sure -- it's just Visual Studio telling you what the exit code was, but I'm not sure where this is configured and a google search didn't turn anything up about how to enable/disable it.

  • marrtin

    Is it okay/advantages to set the 'Solution Platform' in Visual Studio to x64 on an x64-machine?

  • Ole Lop

    Hi, what are the .sln and .vcxproj files and which one should I open?

Leave a Comment

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