Search

0.6 — Compiling your first program

Before we can write our first program (which we will do very soon), we need to know a few things about development environments.

First, although our programs will be written inside .cpp files, the .cpp files themselves will be added to a project. The project stores the names of all the code files we want to compile, and also saves various IDE settings. Every time we reopen the project, it will restore the state of the IDE to where we left off. When we choose to compile our program, the project tells the compiler and linker which files to compile and link. It is worth noting that project files for one IDE will not work in another IDE. You will need to create a new project for each program you write (or overwrite an old one).

Second, there are different kinds of projects. When you create a new project, you will have to pick a project type. 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 dos or linux command-line. By default, console applications have no graphical user interface (GUI) and are compiled into stand-alone executable files. This is perfect for learning C++, because it keeps the complexity to a minimum.

Third, when you create a new project for your program, many IDEs will automatically add your project to a “workspace” or a “solution”. A workspace or solution is a container that can hold one or more related projects. Although you can add multiple projects to a single solution, we recommend creating a new workspace or solution for each program. It’s simpler and there’s less chance of something going wrong.

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.

A quick note about examples containing code

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

If you’re using the Visual Studio IDE

Although the following section was written using Visual Studio 2005, it essentially works the same for all versions of Visual Studio.

To create a new project in Visual Studio, go to the File menu, and select New -> Project. A dialog box will pop up that looks like this:

VC2005 Project Dialog

First, make sure “Visual C++” is selected on the left side.

Second, underneath “Visual C++”, select the Win32 project type, and Win32 Console Application will automatically be selected for you. In the Name field, you will enter the name of your program. Type in HelloWorld. In the Location field, pick a directory that you would like your project to be placed into. We recommend you place them in a subdirectory off of your C drive, such as C:\VC2005Projects. Click OK, and then Finish.

On the left side, in the Solution Explorer, Visual Studio has created a number of files for you, including stdafx.h, HelloWorld.cpp, and stdafx.cpp.

Initial Visual C++ program

In the text editor, you will see that VC2005 has already created some code for you. Select and delete all of the code, and type/copy the following into your compiler:

What you end up with should look like this:

Visual C++ hello world program

To compile your program, either press F7 or go to the Build menu and choose “Build Solution”. If all goes well, you should see the following appear in the Output window:

Successful build

This means your compile was successful!

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!

Note: If you see the console window (black box) without any text, your anti-virus may be interfering. Try turning your anti-virus off temporarily and try again.

Important note to Visual Studio users: Visual studio programs should ALWAYS begin with the following line:

Otherwise you will receive a compiler warning, such as c:testtest.cpp(21) : fatal error C1010: unexpected end of file while looking for precompiled header directive

Alternately, you can turn off precompiled headers. However, using precompiled headers will make your program compile much faster, so we recommend leaving them on unless you are developing a cross-platform program.

The example programs we show you throughout the tutorial will not include this line, because it is specific to your compiler.

If you’re using the Code::Blocks IDE

To create a new project, go to the File menu, and select New Project. A dialog box will pop up that looks something like this:

Code::Blocks Project Dialog

Select Console Application and press the Go button.

This should pop up a wizard:

Code::Blocks Wizard Dialog

On the next page, select “C++” as your language. Click Next.

Code::Blocks Wizard Dialog

Next, you’ll be asked to name your project and choose a location. For your project title, set a name (such as HelloWorld). In the Project Title field, you will enter the name of your program. Type in HelloWorld. In the Folder to create project in field, pick a directory that you would like your project to be placed into. We recommend you place them in a subdirectory off of your C drive, such as C:\CBProjects. Click Next.

Code::Blocks Wizard Dialog

On the next screen, Code::Blocks asks you what compiler you want to use, and what configurations you want. Don’t touch anything here, just hit Finish.

Code::Blocks Wizard Dialog

Now you’ve created your project, and should see your project under the default workspace:

Code::Blocks Project Closed

Open your project node, then open “Sources”, and double click on “main.cpp”. You will see that the hello world program has already been written for you!

To build your project, press ctrl-F9, or go to the Build menu and choose “Build”. If all goes well, you should see the following appear in the Build log window:

Successful build

This means your compile was successful!

To run your compiled program, press ctrl-F10, or go the Build menu and choose “Run”. You will see something similar to the following:

Program run

That is the result of your program!

If you’re using a command-line based compiler

Paste the following into a text file named HelloWorld.cpp:

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 a web-based compiler temporarily

Paste the following into the input form:

and then press “Run”. You should see your output below the form.

Once you install a full IDE, you’ll want to return to this lesson again to learn how to create a project in your IDE.

If you’re using other IDEs

You will have to figure out how to do the following on your own:
1) Create a console project
2) Add a .cpp file to the project (if necessary)
3) Paste the following code into the file:

4) Compile the project
5) Run the project

If compiling fails (“Something went wrong!”)

It’s okay, take a deep breath. We can probably fix it. 🙂

First, check to ensure that you’ve typed the code in correctly, with no typos or misspellings (also, make sure you’re not including line numbers in your code). The compiler’s error message may give you a clue as to where or what the problem is.

Second, check lesson 0.7 -- A few common C++ problems, as many common problems are addressed there (including the COFF error that many of you are encountering).

If that fails, 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 you are using a much older C++ compiler, the compiler may give an error about not understanding how to include iostream. If this is the case, try the following program instead:

In this case, you should upgrade your compiler to something more compliant with recent standards.

If your program runs but the window closes immediately

This is an issue with some compilers, such as Bloodshed’s Dev-C++. We present a solution to this problem in section 0.7 -- A few common C++ problems.

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 in the upcoming lesson 1.1 -- Structure of a program.

0.6a -- Build configurations
Index
0.5 -- Installing an Integrated Development Environment (IDE)

504 comments to 0.6 — Compiling your first program

  • Kikata

    Hello,i don’t have a 32 bit option when i want to create a new project for c++

  • i dun have a file explorer, just a server explorer please help

  • Kuldeep Singh

    Please told me how i can compile the program i have a problem to compile the program as you told in your website above.

  • Jay

    I’m using VS 2017. After copying the code, I clicked build solution. I was greeted with two errors:

    Severity    Code    Description    Project    File    Line    Suppression State
    Error    LNK1120    1 unresolved externals    HelloWorld    1
    Error    LNK2019    unresolved external symbol _WinMain@16 referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)    

    What gives?

    • Alex

      It looks like you may have created a Windows application rather than a Console application. Recreate your project from scratch and make sure you’ve picked the right kind of project.

  • Dear Teacher, please let me report you some inconsistency. In section "If you’re using the Code::Blocks IDE" under 6th icon you say: "Open the tree under “Console Application”," but in icon (current version 16.01) tree is
    Workspace
       HelloWorld
          Sources
    and is under "Projects" and that under "Management". No “Console Application” is visible.
    Regards.

  • Dear Teacher, please let the question: In visual studio 2017 community, what is the difference between "Build Solution or F7" and "Compile or Ctrl+F7"? Regards.

  • Dear Teacher, please let me say you that in April I had downloaded visual studio 2017 community. Yesterday I downloaded same IDE and I found important modifications in downloading and creating project. I think you have to update your lessons about, at least yearly. Regards.

    • Anne

      Hi George,
      That being said I followed the directions and installed Visual Studio successfully yesterday. However, I cannot get it to compile as I work on the Helloworld assignment.  Any suggestions would be greatly appreciated.  Did I need to download another program to assist with Visual Studio  or is everything I need already in Visual Studio  including the compiler and the interpreter?
      This is what is says:
      // HelloWorld.cpp : Defines the entry point for the console application.
      //

      #include “stdafx.h”

      #include

      int main()
      {
      std::cout << "Hello World!" << std::endl;
      return 0;
      }
      ====================================
      ANSWER SHOWED UP HERE WHEN I PASTED THE BUILD MESSAGE FROM VISUAL STUDIO………that was interesting 🙂
      1>---- Build started: Project: HelloWorld, Configuration: Debug Win32 ----
      1>C:Program Files (x86)Microsoft Visual Studio2017EnterpriseCommon7IDEVCVCTargetsPlatformsWin32PlatformToolsetsv141Toolset.targets(34,5): error MSB8036: The Windows SDK version 8.1 was not found. Install the required version of Windows SDK or change the SDK version in the project property pages or by right-clicking the solution and selecting “Retarget solution”.
      1>Done building project “HelloWorld.vcxproj” -- FAILED.
      ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

      • Alex

        Hi Anne. You shouldn’t need to download another program than Visual Studio, but it sounds like your IDE either didn’t install the right components or is configured incorrectly. I’d re-run the installer, and make sure that the Windows 8.1 SDK box is checked so that it gets installed.

  • Weckersduffer

    Mr. Alex,

    Thanks from Spain. I am using code::block but when I try to compile the original "Hello world" code as you say, there´s an error message (unrecognized command line option "-std=c++14") Please, help

  • Donna

    Hello, need assistance

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

    #include "stdafx.h"

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

    then see this after build
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    • Alex

      I see two potential issues:
      1) You’re using std::cout and std::endl but you haven’t done #include
      2) You’re referencing endl instead of std::endl.

  • Seif El-deen

    hello mr alex i am back with another problm 🙂 (you will never get rid of me)

    // ‘elloooooooo.cpp : Defines the entry point for the console application.
    //
    #include "stdafx.h"
    #include <iostream>

    int main()
    {
        std::cout << "Hello world!" << std::endl;
        return 0;
    }// ‘elloooooooo.cpp : Defines the entry point for the console application.
    //
    #include "stdafx.h"
    #include <iostream>

    int main()
    {
        std::cout << "Hello world!" << std::endl;
        return 0;
    }
    p.s: what happened is this (build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped)

  • William

    Hello! So I am on IOS using Xcode and I don’t have a CLUE how to use it or put turn it into a .cpp file. Or what type of file to make or anything!
    Now i am trying Eclipse but its asking for another JVM and i don’t know how to update it.

  • ABitShit

    system cannot find the file specified
    help pls

    • ABitShit

      worked it out. i went through it all right, butwhen i made the file Visual C++ was not properly selected. To others encountering this problem, always make sure Visual C++ is highlighted when you make a new project.

  • Slim Shady

    The tutorial upto this page was awesome! I just have one small doubt.
    I copied the exact same lines of the Hello World project in the Codeblocks IDE (with MinGW). I ran the program. The Cmd prompt box opened. There was Hello World! displayed there, but there was something else, too. It was:

    Process returned 0 <0x0>  execution time : 0.016 s

    I want to know what it is. Is it a default of the OS itself? I use Codeblocks 16.01  and Windows XP Service Pack 2. So, Sir Alex, I request you to answer my query. By the way, Thank you Sir for your initiative and support to newbies in programming!

  • PARAM DHILLON

    DEAR SIR,
    I AM USING MICROSOFT VISUAL 2010
    IT IS DIFFERNT FROM 2005
    THERE IS A PROBLEM IN OPENING CONSOLE PAGE
    PLEASE GET ME THE RIGHT WAY
    AND THANK U FOR THIS AMAZING WEBSITE
    HOPE FOR REPLY SOON

    • Alex

      Microsoft hasn’t changed this dialog much since 2005. Even in Visual Studio 2017 it’s almost the same. What problem are you encountering?

  • Stephen

    Hi. I’m using CodeBlocks v13 on Mac OS X. I’m a beginner here, so I apologise if my terminology isn’t great.
    I have some questions regarding the std operator.
    Firstly, I noticed that when CodeBlocks autocreated the HelloWorld file that it didn’t add the std:: command, just cout on its own. Is this optional within C++ as a language, or is this specific to the compiler/IDE?
    Secondly, I noticed that when I type std:: I get the code completion window, however it doesn’t contain cout/cin as a functions. Is there something particular about cout/cin? Why wouldn’t they come up in auto-complete?
    All the best

    • Alex

      Hi. First, std:: isn’t an operator, it’s a namespace. That aside, one of several things may be happening:
      1) If code::blocks added a “using” statement, then use of the std:: prefix isn’t required in the scope where the using statement is active.
      2) If code::blocks included iostream.h instead of just iostream (no .h), then cout/cin are put in the global namespace instead of the std namespace. This is bad practice by today’s standards, but provided for backwards compatibility with older programs.

  • Paul

    Hi Alex,

    Have you looked at CLion as an IDE? It’s seems to be gaining in popularity and is cross platform for Linux, Windows and Mac.

    Thanks for the great site!

  • My dear c++ Teacher,
    Please let me ask you how to install and use a command-line based compiler.
    With regards and friendship.

  • Rick

    hi Alex! Just started cpp a few days ago, had knowledge on python prior to this. Currently i’m up till chapter 3 and i have only been using console application. Which chapter (if there is) will we learn to use other project formats such as win32 project/ empty project?

  • Barkha

    Hi, i am using code block compiler. When I run a programme and after that i make certain change in the same programme and try to compile or built it, the option is not highlighted. I need to open a new project again and again, and type the same thing again along with new changes, is it normal or there is some issue in the compiler. Coz in turbo c++ i dont have to name the programme again and again even after running the programme i can make changes in existing programme and rerun it. Plz suggest.

    • Alex

      Definitely not normal. I’d maybe search Google or visit a Code::Blocks specific forum and see if you can figure out what’s going on.

  • Nima

    Hello dear Alex.
    You said me for creating static or dynamic library but I read elsewhere about make and makefile which prevent from recompiling all of project even without any .lib or .dll files.(untouched sources are not recompiling)
    However compiling with make and makefile still took so long to compile.
    Any advise?
    Best Regards.

    • Alex

      Today’s IDEs will also generally only recompile what is absolutely necessary.

      A lot of what causes programs to take a long time to recompile is poor structuring of header files. A single change to a header can cause almost every code file to recompile if it’s widely included. So to that end, the best thing you can do is keep your header files small, independent, and only include what you need.

  • In all the programs I write, I always include this line after the include statements:

    using namespace std;

    So my statements for printing something on the screen becomes simple like so:

    cout << "Please enter a number: ";

    The code becomes a little bit user friendly!!.  Me thinks so anyway!!

  • Dear Alex,

    You recommend to place the projects in a subdirectory off of C drive, such as C:\CBProjects. Why?

    • Alex

      Mainly because it makes your programs easier to find and avoids long path issues since some compilers tend to create a lot of subdirectories.

  • Nima

    Hello dear Alex.
    I asked you about compiling a program that contains Eigen library.
    Compilation time was high and you told me to make Eigen to static library if doesn’t change it continuously.
    But I have another question right here:
    What about make and makefile?
    It is true if I build the project for first time and it takes so long to compile but second times or more shouldn’t take so long because I don’t change Eigen library and based on make rule in compilation process g++ is not need to compile Eigen again.
    Thanks in advance.

  • Jeremy

    Not sure how your html pages are set up, but if you use a cascading style sheet, and add these lines for ol {} (ordered lists) and li:

    ol { -moz-user-select: none; -ms-user-select: none; -webkit-user-select: none; }
    li { -moz-user-select: all; -ms-user-select: text; -webkit-user-select: all; }

    No one should be able to copy-and-paste the numbers in ordered lists anymore.

    Good to see you’re still around, Alex. Your learncpp.com is still the best!

  • Nima

    Hello again dear Alex.
    I have another question about compiling a program with C++ language.
    When we compile a .cpp file it provides us an assembly code which we can’t see content of that directly (main.o for instance on windows) so why people say assembly can be faster than C++?
    I’m confuse about this issue.
    Thanks.

    • Alex

      C++ doesn’t compile into assembly code, it compiles into object files that contain machine code.

      Assembly is a different programming language that has fewer more primitive commands. Those commands are very fast, but it’s also very difficult to write large or complicated programs.

      Previously, C++ compilers weren’t that great at producing optimized code, so assembly was always much faster. That’s been increasingly less the case, as compilers and optimization techniques have gotten more advanced.

  • Nima

    Hello dear Alex.
    I have a problem with compilation time when using Eigen library.
    Simply with including .h directory (#include <Eigen/Dense>) you can use this library throughout your program.
    My problem is compilation time. It took so long in this case. (about one minute or more)
    I know this is a template library however can I reduce compilation time?
    Really thanks dear Alex.

  • My dear c++ Teacher,
    Please let me ask your suggestion on my problem.
    For the time being I work with Code::Blocks and do not know how can give first file of a project, name different than "main". With Dev it is easy.
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me one more comment regarding Code::Blocks.
    You state:" You will see that the hello world program has already been written for you!".
    Indeed it is not that one you suggests! Then could you say that for help the beginner.
    When, long ago, I red it for first time was confusing. Eventually with God I understood.
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me say that regarding Code:Blocks you state:
    "Open the tree under “Console Application”, open “Sources”, and double click on “main.cpp”.".
    But tree is:
    Workspace
       HelloWorld
          Sources

    Above tree there is:
    Management
       Projects

    With regards and friendship.

  • My dear c++ Teacher,
    Please let me this question: is your editor "visual studio code"?
    With regards and friendship.

    • Alex

      No, Visual Studio Code is a separate product that Microsoft now produces. It is more of a lightweight code editor. You can plug compilers into it, but it’s not trivial to do. Personally, I don’t use it.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter