A beginner’s Visual C++ tutorial

A friend of mine who just started learning C++ ran into a build error on his first program, which looks likes this:

#include <iostream>

using namespace std;

int main()
{	
    cout << "Hello world!" << endl;
    return 0;
}

This is the type of program you’d expect to see in just about any beginner’s C++ tutorial. What they usually don’t tell you is that this program won’t work in Microsoft Visual C++ without some additional configuration.

Visual C++ displays the full error message in the Output pane (bottom)

Visual C++ displays the full error message in the Output pane (bottom)

You can see the full error message in the Output pane, which is normally docked at the bottom of the window. Here is the rest of the message:

1>------ Build started: Project: ConsoleApplication1, Configuration: Debug Win32 ------
1>  ConsoleApplication1.cpp
1>e:\code\visual c++ projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp(1): warning C4627: '#include <iostream>': skipped when looking for precompiled header use
1>          Add directive to 'StdAfx.h' or rebuild precompiled header
1>e:\code\visual c++ projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp(10): fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "StdAfx.h"' to your source?
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Right away, there’s a problem with line 1. We know this because the line number is shown in parentheses after the filename in the Output pane. This is followed by the warning code, which is C4627, and the rest of the warning message. Visual C++ is pretty clear about what the problem is, but if you’re completely new to programming or to C++ then these words probably don’t mean much to you.

Beginners often get flak in programming circles for not reading or understanding error messages – in this case, a search for warning c4627 would get you pretty far – but I think this is a bit unfair. We don’t normally expect anyone to read, much less understand, something in another language. There’s a lot of vocabulary here for a beginner to learn. So let’s break this error message down, starting with:

'#include <iostream>' skipped when looking for precompiled header use

Basically, the compiler didn’t bother to include the file we asked it to (it skipped it). What’s a “precompiled header?” It’s just another C++ file that has some code that we need in it, plus it’s already been compiled. We don’t need to compile it again because it is not going to change. (i.e., iostream will probably never be updated.)

Add directive to 'StdAfx.h' or rebuild precompiled header

A “directive” is an instruction we can give to the compiler. In our program, #include <iostream> instructs the compiler to look in the iostream header file for things like cout. We could add another directive like this to stdafx.h, another header file which is included in our project under “Header Files” in the Solution Explorer pane.

(By the way, are we having fun yet? Get used to debugging errors if you want to become a programmer. i.e. don’t get discouraged. At least 50% of my time at work is spent debugging errors.)

Visual C++ reports not one but two problems with our code. The second error message comes from line 10, error code C1010:

unexpected end of file while looking for precompiled header. Did you forget to add '#include "StdAfx.h"' to your source?

Here, the compiler is telling us it kept looking for our precompiled header ’til it hit the end of the file. It never found it, but it thinks it could be in stdafx.h. Unless you’ve been reading ahead, it won’t find it there either. It doesn’t know either way because we never told it to look there. i.e., we didn’t #include "stdafx.h" at the beginning of our file.

Want to know something freaky? Our program compiles without a hitch in Code::Blocks.

This is because new projects in Visual C++ are configured to use precompiled headers, but not in Code::Blocks. That tutorial we got our code from probably assumed we weren’t using Microsoft tools but standard tools like GNU Make. In fact, Code::Blocks normally comes with a version of GNU specifically for Windows called MinGW (Minimalist GNU for Windows). That solves that mystery.

But how do we fix our program? I’ll tell you how to change your project’s configuration to get up and running quickly, but I’ll also tell you how to take advantage of precompiled headers if you want to do things the Visual C++ way.

First, if you want Visual C++ to behave like Code::Blocks, right click on your project in the Solution Explorer pane and go to Properties:

The project's context menu as seen in the Solution Explorer pane.

The project’s context menu as seen in the Solution Explorer pane.

On the left side of the properties window, drill down to Configuration Properties > C/C++ > Precompiled Headers. Change the first option, simply named Precompiled Header, from “Use (/Yu)” to “Not Using Precompiled Headers,” then click OK.

We don't need no stinking precompiled headers... except for when we do.

We don’t need no stinking precompiled headers… except for when we do.

Now you can run your program!

If you want to use precompiled headers instead, simply change the first line of your program:

#include "stdafx.h"

using namespace std;

int main()
{	
    cout << "Hello world!" << endl;
    return 0;
}

Then add the missing directive to stdafx.h:

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

#include <iostream>

Now, run your program and celebrate. You are a programmer.

Did you see the console window appear for a brief second and then disappear? Typically, console programs do their thing and then close immediately. You can tell your program to pause and wait by adding a call to system("pause") before the line return 0:

#include "stdafx.h"

using namespace std;

int main()
{	
    cout << "Hello world!" << endl;
    system("pause");
    return 0;
}

That way you’ll have time to admire your beautiful program before closing it.

For extra credit, modify your program to print something awesome to the console.

For extra credit, modify your program to print something awesome to the console.

Advertisements

8 thoughts on “A beginner’s Visual C++ tutorial

  1. Matthew Collison

    Thank you Dave! I’m a senior web developer looking to start delving into application development and just wanted a quick basis using C++ but obviously a lot of preconfiguration is done with VS, so you have been a saviour :)

    Reply
    1. Dave Post author

      Glad I could help! Visual Studio (or Visual C++) does a lot of things for you, which can be both good and bad. I think occasional hangups like this are worth the trouble because it’s such a good IDE.

      Reply
      1. Matthew Collison

        I have to agree. As a personal point, so far the errors have been much more comprehensive and well-described than other IDE’s I have used in the past. I think there will always be the bad points but hey, I think with the subjectivity of programming, there will always be a few of these!

        C++ so far is also quite the language, far more strongly typed than what I have been using for web development (with clear advantages such as being more strict on types means less room for type errors once you adjust yourself to this). Exciting stuff! :) Thanks again.

        Reply
      2. Dave Post author

        Yes. As much as I enjoy programming in JavaScript, it’s hard to go back to after getting used to strongly typed languages like C++ or C#.

        Reply
  2. Garrett

    I am now in love with you. Your the first person I know who’s said anything about how loaded IDE’s really are behind the scenes.

    It baffles me how ignorant and condescending experts can be towards beginners in programming on certain “help” sites. It’s like expecting a foreigner to find an English speaking school inside our native country by reading English signs!?

    ***shout out***
    If you feel like a lot of questions people ask about programming are silly or not well thought out, then your probably one of the condescending people I’m talking about. Hint: there’s no such thing as a silly question in programming. Please be more polite and respectful towards beginners, and don’t moderate for websights that are too “organized”. Beginners should be able to enter a simple search to find an answer, like yahoo answers.

    Reply
    1. Dave Post author

      Yes, I think all programmers have been on that side of the conversation (or forum or whatever) at least once. So we should try to remember what it’s like when addressing novices.

      Reply
  3. Mike

    Finding this was a godsend. I have dabbled in programming for the last 40 years, used at some point just about every language ever written, and just decided that I might want to try writing an application for sale. I downloaded Visual Studio Community, created a basic console application, and modified the “Hello world” code that it started with to the first code example from Lippman’s Essential C++. I got exactly the same error you described above. I basically knew what was wrong, but didn’t know how to fix it. I was close to scrapping VS for now in favor of a more stripped down IDE when I came across this post. It was not easy to find, but I am so thankful that I stumbled across it after reading through dozens of other potential “answer” that came up when I searched.

    Now I am going to have to take a look at some of your other posts. Thanks!

    Reply
    1. Dave Post author

      Glad it helped! These days I prefer the simplicity of a plain text editor and standard tools like GNU make over Visual Studio for various reasons. For one, it just feels more natural to do C and C++ programming in Linux.

      Good luck, either way.

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s