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

837 comments to 0.7 — Compiling your first program

  • Anonymous

    I have two minor issues. I am using Visual Studio Community 2019 that I downloaded yesterday (latest version)

    1. Below my output in the console I get this line:

    C:\Users\Anon\source\repos\Practice\Debug\Practice.exe (process 1076) exited with code 0.
    Press any key to close this window . . .

    Is it a bad thing that this is different from the "Press any key to continue" line? Is there a way to change it and should I?

    2. Build Solution (Ctrl+Shift+B) and Compile (Ctrl+F7) both seem to compile the code, although it seems that Build Solution takes longer. What is the difference and which is preferrable?

  • Frank Cole

    Alec,
    Thank you for your thorough tutorials.

  • Phuong

    Hi, i'm using Code block for the first time and when i compile any projects, this message appears: "Process returned 32762 (0x7FFA)   execution time : 0.000 s
    Press any key to continue."
    And shows no indended results of the code. Please help me : (

  • TheLinuxCowboy

    If you're using Code::Blocks on Linux, make sure XTerm is installed if you are having issues running the program. For me, nothing happened until I installed it.

  • I'm not sure if this is normal, but, after I press Start Without Debugging (Windows), it says, "Press any key to close this window . . ." instead of "Press any key to continue . . ." Again, is it normal?

    • C918

      I got the same window as yours.

      it shows....

      Hello World!

      (file path)<process 8484> excited with code 0.
      Press any key to close this window . . .

      • C918

        Hi Alec, I think I found how to get that screen we both needed

        goto tools>options>debugging> Automatically close the console when debugging stops

        put a tick there and things get back to normal. :)

        BUT if someone can tell me why it happened and how it happened... That would be great :)

  • NASSAR

    Hellow
    I am still beginning to learn C++, According to what written above I have wrote this code in visual studio 2017

    // Hellow.cpp : Defines the entry point for the console application.
    //

    #include <iostream>

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

    but under it appeared:
    Severity    Code    Description    Project    File    Line    Suppression State
    Error    C1010    unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?    

    then after adding "stdafx.h" to the code it has done.
    I want to ask why is it important to add this library here? and how I can do the program without "stdafx.h" library ?
    Thank you.

    • nascardriver

      Disable precompiled headers in your project settings. You should never include stdafx.h, because it breaks cross-platform compatibility.

  • Hooman

    Hello,
    When I run the code I have just seen the below message but can not see the results.

    1>------ Build started: Project: Win32Project7, Configuration: Debug Win32 ------
    1>  Skipping... (no relevant changes detected)
    1>  Win32Project7.cpp
    ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

  • C.H

    Just started the tutorials, I open the first project and when pressing F7 I get this..

    1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
    1>Project1.cpp
    1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.26.28801\include\yvals.h(12,10): fatal error C1083: Cannot open include file: 'crtdbg.h': No such file or directory
    1>Done building project "Project1.vcxproj" -- FAILED.
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    I tried it without even changing any of the code that comes as default, with the hello world and everything and it still shows that error. What should I do?

    • C.H

      I uninstalled and installed it again making sure I selected all the SDKs I could (as I saw Alex advice someone else) and now it works! sorry for the useless comments.

  • LD

    Hello, I attempted to compile the first code and think I was successful if I can remember. Any reason as soon as I built solution windows detected a Trojan horse. I've never had this problem before so I am extremely skeptical to continue the modules.

    • Noctilys

      Windows Defender automatically blocks any new executable (it wasn't used by anyone)
      Just whitelist this file, it's YOUR program so there is no Trojan inside.

  • shay

    when i try to build the project in codeblocks the build lpg return this:
    -------------- Build: Debug in HelloWorld (compiler: GNU GCC Compiler)---------------

    g++.exe -Wall -fexceptions -g -std=gnu++20  -c C:\שי\HelloWorld\main.cpp -o obj\Debug\main.o
    g++.exe  -o bin\Debug\HelloWorld.exe obj\Debug\main.o  
    g++.exe: error: unrecognized command line option '-std=gnu++20'; did you mean '-std=gnu++2a'?
    Process terminated with status 1 (0 minute(s), 0 second(s))
    1 error(s), 0 warning(s) (0 minute(s), 0 second(s))

    it does not what im trying to run even if main is empty.
    can someone help me please?

  • Sami

    Hello,
    When we are creating a new project on Visual Studio 2019, is there something wrong with choosing "Console App" instead of "Windows Desktop Wizard"? Is there any differences?

    • Alex

      If I recall correctly, the Windows Desktop Wizard gives you more options (such as being able to turn off precompiled headers).

  • Dawgtaggz

    I'm using codeblocks to try this Hello World program and have finally just copied and pasted it but it still won't build and I can't figure it out. Any help would be appreciated

  • New CPP User

    hello !
    im getting this code after my compile of hello world
                 [/process 11828]
    can any one tell me what is this??

  • I just started this yesterday, and am very interested in learning C++. I have been playing around with sketches for my Arduino Uno board, using the Arduino IDE. It requires files to be saved with the extension .ino. The Visual Studio 'save as' menu does not have this option. Will I learn how to do this?
    The (my) Arduino IDE does not have the <iostream> library. I turned to google for some insight, and found a lot of confusing responses. Of course I have a lot to learn, and curiosity feeds learning. I'm an old dog (66) but I am quite capable of learning new tricks. Any response to this will be appreciated.

    • nascardriver

      Hi!

      Arduinos are fun :)
      Only the main file has to have an "ino" extension. All other files can be placed in a "src" subdirectory and have the usual "cpp" and "h" or "hpp" extensions (We talk about multi-file projects later). I can't help you with VS and I don't think it's suitable for Arduino development (You can edit the files, but includes will fail to resolve and you could get false errors). You might be better off sticking with the official IDE or Visual Studio Code (There's an extension for Arduino development).

      Arduinos don't have a standard library at all. No header that we include in these lessons is available on an Arduino. Everything you need has to be written by yourself or you need to download a library that does it (The Arduino IDE has a library manager).

      To print something from an Arduino through serial to your pc so that you can see it in the serial monitor, you can use `Serial.println` from the "Arduino.h" header.

      I suggest you to do chapter 1 and maybe 2 on a desktop machine to learn the very basics of C++. Then read through an Arduino tutorial to learn the basics about Arduino development. After that, you should be able to follow the lessons here and adjust them to run on your Arduino. Keep in mind that your Arduino doesn't have a standard library. There are several lessons dedicated to the standard library, you won't be able to do those.

      If you have any more questions, feel free to ask.

  • Gal Ozer

    is there any difference in Compiling programs in mac os (i mean in Xcode)
    thank you very much, I'm so far really enjoying learning;
    I knew a little about coding with java but u never really learned about Compiling linkers and more.

    • nascardriver

      The interaction with the editor is obviously going to be different. As far as I know Xcode can use different compilers (Just like code::blocks) and uses clang by default. clang has almost the same command line interface as gcc (and mingw), which is used by code::blocks by default. You might be able to find similarly named settings in Xcode if you follow the code::blocks/gcc instructions in the lessons.

  • Tim Earl

    I typed in the "Hello, world" program, plus extra lines as it didn't run first time. It still won't run, but gives this msg:

    "There were build errors.
    Would you like to continue and run the last successful build?"

    I disabled my anti-virus (AVG), but the same thing happened.
    Any suggestions, please?

    • nascardriver

      You're missing a closing bracket

    • Tim Earl

      Thanks. I was going to say "Why didn't the compiler pick it up?", but it did – except that the red markers were so tiny I missed them. It's a bit clearer with visual studio in full screen (and I know what to look for now).
      Another thing is that "return" is in purple, which the MS documentation for VS says "denotes other types of errors" . Any ideas on that one?
      Also, thanks for spending your time right back here with the beginners.

      • nascardriver

        There's a list of errors and warnings at the bottom of VS. That gives you a description of what the errors/warnings are and where they are. I don't have VS, this should be it https://docs.microsoft.com/en-us/visualstudio/ide/reference/error-list-window?view=vs-2019

  • Arthas

    I followed the step above, but I don't see dialog shown in 'Creating a project in Code::Blocks' section.
    The visual studio I installed as below.
    Microsoft Visual Studio Professional 2019
    Version 16.1.5

  • phil

    lesson 0.7, when I run HelloWorld i get:

    Hello, world!
    Process returned 0 (0x0)   execution time : 0.017 s
    Press any key to continue.

    How to not get the second line: Process returned 0 (0x0)   execution time : 0.017 s ?

    Or is this debug information that would be removed in final compile ?

    • nascardriver

      That's debug information added by your IDE. If you run the executable directly, ie. not through your IDE, you shouldn't get that output.

  • Johannes

    can someone help me fix this?

    #include <iostream>
    #include <string>

    int main()
    {
        std::cout << "Enter your name ";
        std::string name;
        std::cin >> name;

        std::cout << "Enter the grade in Math: ";
        int math;
        std::cin >> math;

        std::cout << "Enter the grade in English: ";
        int english;
        std::cin >> english;

        std::cout << "Enter your grade in Science: ";
        int science;
        std::cin >> science;

        int  x{ english + math + science };
        std::cout << name << " Your average is " << x / 3;

        if (x <= 75)
            std::cout << " congratulations you pass the semester";
        else
            std::cout << " You fail idiot";
        
        
        return 0;
    }

    • nascardriver

      That's happening? What did you expect to happen? Which error messages are you getting?

      • Johannes

        it's working but what ever average I get it outputs that you fail.

        • nascardriver

          There's nothing wrong with your code. When I input 1 1 1, I get "Your average is 1 congratulations you pass the semester". Are you recompiling the code? You might be running an older, broken, version of your code.

          • Johannes

            yes you got it. why does it out put congratulations when you get a 1 average? my goal is when the average is 75 our above it should be congratulations and 74 below is the cursing word.

            • nascardriver

              Seems like you're confusing < and >
              < and > are the mouth of a crocodile. The crocodile eats the larger number.

              You want to check if `x` is larger than or equal to 75, so the crocodile eats `x`.

              • Johannes

                Thanks for trying to help me, but I already tried that. The program doesn't work like what I want. Maybe my compiler has a problem or something. but can you please use it and try get a 76 and 74 average and tell me if it works. Thanks

                • kid123

                  #include <iostream>
                  #include <string>
                  using namespace std;

                  int main()
                  {
                      cout << "Enter your name ";
                      string name;
                      cin >> name;

                      cout << "Enter the grade in Math: ";
                      int x;
                      cin >> x;

                      cout << "Enter the grade in English: ";
                      int y;
                      cin >> y;

                      cout << "Enter your grade in Science: ";
                      int z;
                     cin >> z;

                      int  sum = x+y+z;
                      int ave = sum/3;
                      cout << name << " Your average is " << ave;
                      

                      if (ave>=75)
                      {
                      
                          cout << " congratulations you pass the semester";
                      }
                      else if (ave<75 || ave!=75)
                      {
                         cout << " You failed idiot";
                     }
                      
                      
                      return 0;
                  }

                  Hope this helps.

                • nascardriver

                  You're not checking the average, you're checking `x`. Store the average in a variable and compare that to 75.

  • EJW

    (Sorry for the adblock--see my question in section 0.1.)

    As recommended, after more lessons I did a little extra work on the "Hello, World" program.  Please comment:

    • nascardriver

      - You're initializing `flag` to 'n', but never use that value. Initialize it with empty curly braces.
      - Separate code into many functions. Your code isn't reusable and more difficult to maintain.
      - Line 23/24 are unnecessary. You can change the loop's condition to `flag != y`.
      - `std::string::length` doesn't return a `long unsigned int`. It returns a `std::string::size_type`, which is an implementation-defined unsigned integer. Use `std::string::size_type` or `auto`.
      - Use ++prefix unless you need postfix++. postfix++ is slower.
      - Line 29-36 defeat the purpose of using `std::getline`. If you don't want to allow whitespace, use `std::cin >>` followed by `std::cin.ignore` to remove the rest of the name.

      Although there are some issues, your code shows that you understood the individual concepts. You just need some practice to put it all together :)

      • EJW

        Thank you for the detailed comments. (Lines 29-36 have to do with storing the full name separately from printing the greeting in case the program is expanded.)

  • SW

    Okay so I copied the code by hand into Visual Studio 2019 for Mac, and I have no idea what I'm doing. I'm trying to follow a windows specific tutorial on a mac.

Leave a Comment

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