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

622 comments to 0.7 — Compiling your first program

  • olander

    i can't even figure out where to find the command line, am i blind or something or have i just skipped something?

  • I am m new to programming and I want to learn C++. Before reading this article I was in fear how difficult a  C programming will be! But thanks to site admin it was not as difficult as people think. Thank you so much

  • Dan

    I get this error message after clicking Build in Code Blocks:

    ld.exe      cannot find -lWs2_32.lib

    Does anyone know why I get this error.
    Thanks.

  • Juan C. Luna H.

    For linux users, must install c++ essentials before to work with Code::Blocks

    Execute this command on terminal

  • Pochi

    I get the following error, i double checked to make sure i unchecked precompiled. Not sure what's goin on.

    1>------ Build started: Project: HelloWorld2, Configuration: Debug Win32 ------
    1>Object reference not set to an instance of an object.
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

  • vbot

    Hello!

    After starting "HelloWorld" the process "xxxx" automatically exits with exit code "0". So there is not just the desired text-output and "press any key ..."-message in the console (like in your example output), but also the mentioned exit-message above the "press any key ..."-message.

    Question: Why? / Is this bad?
    I'm using MS VS Community 2017 15.8.5

    Thanks! + great tutorial so far! 🙂

    • vbot

      Update:

      Ok, it's nothing bad, as explained in Lesson 1.1 - Structure of a program:

      "This particular return statement returns the value of 0 to the operating system, which means “everything went okay!”. Non-zero numbers are typically used to indicate that something went wrong, and the program had to abort. We will discuss return statements in more detail when we discuss functions."

      Thanks.

    • Alex

      The "return 0" statement returns a 0 value to the operating system (we cover this in the next chapter). Your IDE is taking the liberty of showing you what that return value is in order to potentially help you debug your program. This is IDE-specific behavior.

  • Ryan

    Hello! I wanted to point out a potential typo I noticed in 'Creating a project in Visual Studio'. Where you said 'older version of Visual Studio have a different style', I think you accidentally didn't pluralize 'version'.

  • Adil Numan

    i started with first project helloworld but after doing exactly what asked to do but still when i am trying to build project its giving error
    MSB6006: "cmd.exe" exited with code -1073741515

    • Alex

      This is some kind of misconfigured compiler error. Try reading here and see if any of those solutions are applicable. If that doesn't help, I can only suggest a google search to see if it turns anything up further.

  • Azeara

    There is a ton of code here and I have no idea what's going on. You've talked about Compilers Linkers IDEs Executable programs and explained it. But then you don't teach us code until after we or at least me are ridiculously confused and you even reference code without explaining it in the slightest. I'm sure it gets better as you move on but I'm going to somewhere that actually makes sense and explains the things that we couldn't possibly understand if we have no code background.

    • Hi Azeara!

      This first lessons are just about setting up a coding environment so you can follow along in the upcoming chapters. If you already have an IDE or editor/compiler running you can skip chapter 0. Chapter 1 is where the coding begins.

  • Akshay

    why after installing and copying this code in codeblocks ,it doesn't build? (64 bit compiler)

  • Yunus

    #include "pch.h"
    Instead of
    #include "stdafx.h"
    Fixed the prob for me.

  • Math

    I don't find "win32" as a possibility. the possibilities are :
    Windows Deskstop, General, ATL, CMake and Test. Wich one should i pick?

    I use Visual btw

  • pouya akhgari

    hi, i plan on starting to learn c++ and i have a question to ask:
    since this tutorial was published in 2007 changes have been made to c++, and i was wondering: after learning all of lessons would it be hard for me to get updated or not?

  • Hassaan

    what is the difference between

    and

    ???

  • Roemer

    Im using VS but i follow your instructions but then this happens...
    Severity    Code    Description    Project    File    Line    Suppression State
    Error    MSB4024    The imported project file "C:\Users\Roemer Caliboso\AppData\Local\Microsoft\MSBuild\v4.0\Microsoft.Cpp.x64.user.props" could not be loaded. Root element is missing.ConsoleApplication2    C:\Users\James Caliboso\source\repos\ConsoleApplication2\ConsoleApplication2\ConsoleApplication2.vcxproj
    Do you have any solution?

  • Josh

    What if I'm using Visual Studio on Mac? It doesn't show up with the Visual C++ nor the Win32. What should I do?

  • Kaitlynn

    Is there a reason you'd suggest against using namespace(std)?

  • Crystal blue

    It says Compilation successful but then just everything freeze. Only hello world is seen in the screen.
    Can you please help me out?

    • Kaitlynn

      Only hello world should be seen in the screen as this is a simple output program. It's simply attempting to display the words : "Hello World!" in your command prompt. In your code it shows
      cout << "Hello World!" << endl;
      return 0;

      That return 0 tells the compiler that there is nothing else in that function for it to compile and since you don't have any other functions (This is main, if you don't already know) it stops there.

  • Brook

    here I am again. I also tried "not using precompiled headers" in the solution explorer properties. IDK. I'll just keep going with what I have till I run across something or someone give me a lead. I'm not going to spend too much time worrying about it.

  • Brook

    using vs 2017 community

    I get an error when using stdafx.h.
    cannot open source file "stdafx.h"
    cannot open precompiled header file: Debug\HelloWorld/pch: No such file or directory.

    I right clicked solution explorer->properties->precompiled headers->precompiled header Use:(/Yu).

    Not letting me do it. Am I missing something?
    in the meantime, I'm using #include "Windows.h"... is this bad?

Leave a Comment

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