Learn How to Program C++ Games with Microsoft Visual C++ 2010 Express Edition

Let's face it: the heart and soul of any great video game is the code. Without great code you might have slick 3D models, a great soundtrack, and an interesting story, but you don't have a game. So if you don't know anything at all about programming, how do you get started?

Every programmer on the planet started by learning the basics. Learning how to program is a bit like learning math, only a lot more fun! You start out by learning simple concepts, practice them until you know them by heart, and then move on to more advanced concepts. I can't emphasize enough just how important it is to practice what you learn! Each lesson in this tutorial will provide you with a simple program to type in and experiment with. It is important that you actually take the time to enter and compile the code yourself. If you want to become an ace programmer, you have to treat it like a professional sport and spend as much time as possible practicing what you learn. If you want to become a game programmer, you have to know this stuff in your sleep!

In this tutorial, you will learn how to create a simple C++ application that prints text to the console using Microsoft's free Visual C++ 2010 Express Edition IDE (integrated development environment). If you've never programmed before, don't worry: I'll walk you through each step and explain every detail. (I always hated tutorials that left out important steps, assuming that you knew that the author was talking about, so if you can't figure something out, leave me a comment and I'll try to fix it, asap!)

About the Notes: You'll see tons of these note boxes everywhere. These contain useful or interesting information, but aren't required reading. I include lots of links to Wikipedia and other online resources to make it easy for you to follow up on whatever strikes your fancy but don't try to follow every link: you'll go crazy! The links are there to help you understand the concepts on a deeper level, or to see how they connect to other concepts. They can be safely ignored the first time through; everything you need is right here in the tutorial.

Ready? Let's get started!

Why C++?: Why should you learn C++ if you want to program video games? Because C++ is the language of choice for serious game programmers. C++ is built from the ground up to be fast and efficient and provides programmers with low-level access to hardware that is concealed by other languages, making it the perfect choice for bleeding-edge games. C++ isn't the only language you can use, of course, and I certainly encourage you to see what you can come up with in other languages once you've got your programming chops down, but it is still the most widely used and supported language for programming games. If you can master C++, you can master any language. Do you need to learn C before learning C++? Absolutely not. C++ includes everything in C plus a lot more. Besides, C is based on procedural programming, an older programming style which is not suitable for games. C++ is designed specifically for object-oriented programming, the modern way to program, and a style more suitable for game development. It's actually easier to develop games using C++ than it is to use C, even though the language is harder to pick up at first. Trust me: C++ is the way you want to go.

Download and Install Microsoft Visual C++ 2010 Express Edition

There are plenty of C++ compilers out there, but there aren't any as good as Microsoft's Visual C++ 2010 Express Edition for programming games. MSVC++ (which is what I'll call it from now on) is a powerful, sophisticated, and complex application; but, best of all, it's free! Although you could literally spend months studying all of MSVC++'s features, I'm just going to show you the features you need to know to successfully compile and run the programs used in this tutorial.

Compilers vs. Interpreters: A compiler is a program that translates human-readable source code into machine-readable object code before the application is used. An interpreter is a program that translates source code into object code while the program is being used. A compiled program can be used by anyone who has compatible hardware and a compatible operating system. An interpreted program can only be used by someone who also has an interpreter. That's why you can download and play games without owning a C++ compiler, but you need to install Java to use Java applets on web sites.

You can download MSVC++ from Microsoft here:

Download

ISO/IEC Standards: All of the programs in the C++ portion of this tutorial are ISO/IEC standard compliant, so they should compile on any compiler that follows the standard. Don't feel obligated to use a Microsoft product if you don't want to! Later portions of this tutorial, like the Windows and DirectX tutorials, are obviously not ISO/IEC standards compliant so you'll need a Windows box to utilize them. I plan on writing OpenGL tutorials eventually, too, though, so if you're really not a Windows fan there is light at the end of the tunnel. (Note: ISO = International Organization for Standardization. IEC = International Electrotechnical Commission. These are just international standards committees. Don't worry: I'm not going to test you on this. :P)

Start Microsoft Visual ++ 2010 Express Edition

Once you've got MSVC++ installed, open it. You can probably find it in the Start menu under All Programs -> Microsoft Visual Studio 2010 Express -> Microsoft Visual C++ 2010 Express. If you installed it somewhere else, you may have to go looking for it. I recommend you create a shortcut for it on your desktop, you'll be using it a lot! Once you've got it started, you'll be greeted by the start screen, which looks like this:

Select File, New, Project from the menu

The Start Page has a web browser built right into it that allows you to view various help files at the Microsoft Developers Network (internet access required). I recommend you spend some time reviewing the documentation here alongside my tutorial. In my experience, you will learn more if you study more than one guide. People (myself included) tend to forget details or explain things in unusual ways that can be cleared up with a second reference. Although I'm going to try and make this the best introduction I can, it doesn't hurt to shop around!

Create a New Project

The first thing we need to do is create a new project. If you look at the top of the window, you will see a menu bar with options like File, Edit, View, etc. To create a new project, select File -> New -> Project from the menu. (Alternately, you may just select 'New Project' from the start page, but where's the fun in that?!) You can also open recent projects using the 'Open Project' link or the list of projects under 'Recent Projects'. Microsoft makes it pretty easy to get to work!

Projects and Solutions: A project is a collection of source files and resources that make a complete application. Technically, you don't need to create a project to create a C++ program. Many tutorials skip this step entirely and start you off with a simple source file. All serious applications use project files, however, and since they're not hard to create, you might as well get in the habit of setting up a project for every program that you write. MSVC++ has one additional level of organization: solutions. A solution is essentially a collection of projects, just as a project is a collection of source files and resources. When you create a new project, MSVC++ will automatically create a new solution with the same name.

Select File, New, Project from the menu

Our first project is going to be a Win32 Console application, so select that option from the New Project dialog. Give your project a name where it says 'Name' at the bottom of the dialog window.

The New Project dialog

Console: A console is a text-only user interface to a computer, or a command-line interface. It is also often called a shell. Instead of pointing and clicking on objects with a mouse, the user types commands using the keyboard at a command prompt. Often, the words screen or monitor may be used to loosely refer to the console, but the console is really a special sort of interface. Before graphical user interfaces (GUIs), people used to do everything through the console. Graphical applications (like Windows apps) are somewhat complicated to program, so most introductory programming courses teach you how to use the console first. You can open a console on a Windows computer by opening the Start menu and selecting All Programs -> Accessories -> Command Prompt. You'll get something that looks like this:

The Command Prompt, Windows console

You don't need to know anything about using the command prompt to use this tutorial. Anything you need to know will be explained at the appropriate time. If you're curious, however, you can check out Wikipedia for a list of MS-DOS commands. (DOS stands for Disk Operating System.)

Click 'Ok' and you will be greeted with the Win32 Application wizard. Click 'Next' to fill out the application settings.

The new Win32 application wizard

On the Application Settings screen, the 'Application type' should be set to 'Console application'. Under 'Additional options', click 'Empty project'. Select 'Finish' to complete the wizard.

Application type is console, options set to empty project

The wizard will close, and you will see your empty project in MSVC++. The next thing you need to do is add a source file to your project.

Your new, empty project

Add a New Source Code File

Right-click the Source Files folder under your project name in the Solution Explorer and select Add -> New Item.

Add a new item to your source file folder

In the Add New Item dialog, select 'C++ File (.cpp)' and give your source file a name. Click 'Add' to add it to the project.

Set the new item as a c++ file

Type in the Source Code

In the empty file that appears, type in the following code exactly as it appears. Pay very careful attention to the punctuation and spelling. If you make a mistake, your program will fail to compile!

// Victory is Mine!
// A simple program that prints a message to the console.

#include <iostream>

int main()
{
	std::cout << "Victory is mine!" << std::endl;
	return 0;
}

Your final input should look something like this:

Type in the source code exactly as you see it here

When you're done, save the file by clicking on the Save icon.

Save your file

What you've just done is create the C++ source code for your program. Although there are a lot of weird symbols in your source code, computers don't understand source code at all. In order to turn your source code into something the computer can understand, you need to compile it.

Compile Your Source Code

To compile your program, press the green arrow icon on the toolbar where it says 'Debug'. Debugging and compiling are closely related procedures, so MSVC++ performs both of them at the same time.

To compile your source code, select the Start Debugging icon

MSVC++ will display a pop-up informing you that your project is out of date and ask you if you want to build it. Say 'Yes'.

Click yes to rebuild your project

When the compiler is done compiling your code, it will inform you of any errors or warnings in the Output window at the bottom of the screen. You will probably get warnings about PDBs (program database files) like I did which you can see in the screenshot below. These particular warnings are harmless, but I'll show you how to correct them after we see our program in action.

Debugger warnings and errors show up in the Output

Errors and Warnings: When you compile your program, if MSVC++ detects an error, it will stop compiling and print an error message in the Output window. If you have an error in your program, you will not be able to run your program until you fix the error. Errors that are detected during the compilation phase are known as syntax errors; in other words, you told your program to do something that the language doesn't allow you to do. Another common type of error is a linker error. These are the dreaded 'unresolved external symbols' errors that plague the forums. You get these kinds of errors when you forget to tell the linker where to find files that are supposed to be included in your project. The third type of error is a logical error. A logical error is correct as far as the compiler is concerned, but it will produce the wrong results when you run your program. (These types of errors are thus often called run-time errors.) An example of a logical error is adding the length and the width of an area instead of multiplying it. It's not incorrect, it's just not what you intended to do. Because C++ is a very strict language, the compiler can sometimes detect errors when they are technically correct, but very unusual. In these cases, the compiler will issue a warning instead of an error. The warning will also appear in the Output window, but the compiler will not stop compiling your program. Assuming that you have no other errors, you will still be able to run your program regardless of any warnings you may have received. It is always best to treat warnings like errors, however, and eliminate them by improving your code. If you compile a program and you end up with dozens of errors and warnings, don't panic! You may get multiple error and warning messages from a single error, and most of the time it's something simple like a typo. Simply correct the obvious errors and recompile. Often, that's all it takes. (I'll talk a lot more about debugging your programs later. Consider this the crash course!)

Create a Batch File and Run the Program

If you were paying careful attention to MSVC++ while it was debugging, you might have noticed the console window flash onto the screen and just as quickly disappear. That is the output of our program, but because Windows automatically closes console applications as soon as they are finished, we didn't have time to enjoy it.

To get around this problem, we're going to create a batch file. A batch file is essentially just a text file that we use to give the Windows operating system simple instructions. In this case, we're going to tell Windows to run our application, and leave the console window open until we hit enter. To create the batch file, navigate to the folder where your program files are kept. In my case, that's Users\Dave\Documents\Visual Studio 2010\Projects\VictoryIsMine\Debug\. Right-click in Windows Explorer to pull up the context menu and select New -> Text Document.

Create a new text file

Rename the file to something memorable and give it a .bat extension. I called mine VictoryIsMine.bat.

Name it and give it a batch file extension

If you get a warning about the perils of changing file name extensions that looks like this:

Renaming a file may make it unusable.

just click 'Yes'. Windows knows how to handle batch files. Now, right-click your new file and select Edit.

Right click to edit the batch file

This should open Notepad. (If you selected a different program to open the file, make sure it is a plain text editor, not a word processor. Word processors embed hidden formatting instructions in files which will prevent Windows from understanding the batch file.) Type the following into your batch file:

VictoryIsMine.exe
pause

It should look like this:

Type the name of the executable, press return, and type pause into the batch file

Save your changes and close the file.

Save the batch file

Now, when you double-click on the batch file, Windows runs your application and keeps the console open long enough for you to enjoy the fruits of your work. Ah, sweet victory!

Victory is mine!

Plain Text Editors vs. Word Processors: Because this issue comes up all of the time in programming, scripting, and coding, I thought I'd explain, briefly, the difference between plain text editors and word processors. A plain text editor is a program that allows you to type the standard keyboard characters into a file but doesn't let you format that text with anything but the spacebar, tab, and newline keys. Notepad is an example of a plain text editor. A word processor is like a plain text editor, but it also allows you to format the text using various stylistic devices, like italics, bold, different font sizes and colors, etc. Microsoft Word is an example of a word processor. You should not use a word processor to create your source code files. The files created by word processors have to embed all of your stylistic information in the document, and this embedded information will choke your compiler. Always use a plain text editor to create your source code files, preferably, the text editor that is bundled with your compiler's IDE. I am aware that many word processors allow you to save files as plain text, but why bother with the extra step? You can't take advantage of any word processing features with a source code file so there is no reason to use one. Just say no. The same rule applies if you're creating web pages "from scratch" (like I do): use a text editor to type your HTML/CSS.

Other Ways to See Your Program Output

If you've read other C++ tutorials, you may be aware that there are a number of other ways to see the output of your program that do not require you to create a batch file. I showed you the batch file method first because it is more convenient than navigating to your directory through the console, and less 'kludgey' than using a system() or cin.get() command. It is also a useful technique to know. Now that I've spilled the beans on these methods, though, you're probably interested in hearing about them.

Navigating To Your Program's Directory Using DOS Commands

Probably the most inconvenient method, but a very useful method to know, is to navigate to the directory containing your program's executable via the console. To do this, you need to know two things: where your program's executable (.exe) is located, and a couple of simple DOS commands. The executable for the VictoryIsMine program is located on my system here: Users\Dave\Documents\Visual Studio 2010\Projects\VictoryIsMine\Debug\. (Your path may be different if you've chosen to create your projects in a different folder.)

In order to navigate to this directory, follow these steps:

  1. Go to the Start menu (the little Windows icon in the bottom left corner of your desktop) and select All Programs -> Accessories -> Command Prompt. The command prompt/console should open.
  2. At the command prompt in the console (C:\Users\Your Name>, only with your own name, obviously), type the dir DOS command. dir stands for directory and shows you the contents of the current directory.
  3. In this directory, you should see a directory (folder) called 'Documents'. To change to this directory, type cd Documents at the command prompt. cd stands for "change directory".
  4. This will open the directory, and the command prompt will show the new, expanded location as C:\Users\Your Name\Documents. If you type dir again, you will see a list of the contents of your Documents folder.
  5. Find the folder called Visual Studio 2010 and type cd Visual Studio 2010 at the command prompt.
  6. Type dir again and you will see a folder called Projects. Type cd Projects to open this folder.
  7. The VictoryIsMine project should be in this folder. Open this folder with cd VictoryIsMine.
  8. Inside, you will find the Debug folder. cd Debug to find the VictoryIsMine.exe. This is the executable.
  9. To run the executable, just type the name of the program: VictoryIsMine at the command prompt. Voila!

As you can see, the output immediately follows the last command. In this case, the console doesn't close because you are inside the directory. This is what you would have seen if you'd gone through the whole process on an old computer using the command line interface to compile and link your code. Congratulations, you've just learned how to rock DOS, old school. :) (Please don't think you won't need to know this stuff. A lot of useful tools still rely on the command line. In fact, some of the tools you design or use at work may still use this kind of interface. Knowing how to get around in a console window will save you a lot of time later on.)

The full file path in the console along with the program output

Using the System() Command

One way to get the same effect from within the program itself is to have the program tell the operating system to pause for you. You do this by using the system() command to talk to the operating system and passing the "pause" command to the command line interpreter. This is essentially the same thing as writing a batch file, but without the file. Make the following change to your program, save it, and recompile by pressing the green arrow beside 'Debug'. You will notice that this time the output remains on the screen without you having to create a batch file or navigate to the proper directory.

// Victory is Mine!
// A simple program that prints a message to the console.

#include <iostream>

int main()
{
	std::cout << "Victory is mine!" << std::endl;
	system( "pause" );
	return 0;
}

Using the cin.get() Command

The other way to do this is to use the get() method belonging to the cin object from the standard library. The get() method essentially waits for the user to enter something at the keyboard, 'pausing' the program until you hit Enter. Because there are no other lines of code after this command, the program ends as soon as you press a key. To use this method, make the following changes to your program, save and recompile. The result is almost identical to the previous method, but without the friendly prompt.

// Victory is Mine!
// A simple program that prints a message to the console.

#include <iostream>

int main()
{
	std::cout << "Victory is mine!" << std::endl;
	std::cin.get();
	return 0;
}

So what technique should you use? Well, for simple little programs like this, it really doesn't matter. These are all useful techniques to know. Later, when you're programs become large and sophisticated, a better solution will present itself.

Activating the Microsoft Symbol Servers

Now, we're going to go back and correct the warnings we received earlier about the missing symbols. Although these particular warnings will not affect our program or prevent if from compiling, it is always a good idea to resolve all of your warnings. To do this, go to Debug -> Options and Settings.

Select Debug, Options and Settings

Expand the Debugging heading and select Symbols. In the box on the right, check Microsoft Symbol Servers and where it says 'Automatically load symbols for:' select All modules and click 'Ok'.

Check Microsoft Symbol Servers, All modules

If you recompile your program, you'll notice that the warnings about missing symbols have been replaced with 'Symbols loaded (source information stripped)'. This message is for information only and completely harmless, so you can ignore it.

In the next lesson we'll dissect a simple program and show you how each part of it works.

Questions

These questions are for the keeners who read all the note boxes. If you skipped them, you can skip these questions. To see the answers to these questions, triple-click or drag your mouse over the blank area below the text.

  1. Why should you choose C++ to program games?
    • C++ is the language of choice for professional game developers because it is fast and efficient and it supports object-oriented programming, which is essential for good game design.
  2. What is the difference between an interpreter and a compiler?
    • An interpreter translates source code while the program is running. A compiler translates source code once, before running the application.
  3. What is the console?
    • The console is a DOS-based, command-line interface to an operating system. The Windows console is also called the command prompt.
  4. What are three types of errors you might encounter writing a program?
    • Syntax errors during compilation. Linker errors during the link phase. Run-time errors while running your application.
  5. What is the difference between a plain text editor and a word processor?
    • A plain text editor only allows you to enter characters from the keyboard without any fancy formatting. A word processor allows you to format your text to change the size, color, etc.
  6. What are two ways to see the output of your program?
    • There are four discussed in this lesson: creating a batch file, navigating to your directory using DOS commands, using the system() function, and using the cin.get() method.

Exercises

  1. Try each of the four methods of viewing your program output. (Using a batch file, navigating to your directory using DOS commands, using the system() function, using the cin.get() method.)

Comments

Feel free to comment, but please be civil and constructive. Inappropriate, inflammatory, and spam-related comments will be deleted.

***

Last updated October 31, 2011

© 2009-2011 Dave Finch

SUPPORT TRUANCYFACTORY