The purpose of this document is to help someone who is
encountering Visual C++ for the first time, but who knows at least some
C++, to get started quickly writing C++ programs using the programming
environment provided by the Visual Studio 2008 IDE
(Integrated Development
Environment). If you are already familiar with Visual
Studio 2005 (the most recent version of Visual Studio before 2008), you
will find most of what is here to be familiar.
Suggestions for additional material to be included on this page are
always welcome.
Overview
Visual Studio 2008 allows you to write many different kinds of C++
software, from simple console programs to DLLs (Dynamic Link Libraries)
to Active Template Library Components to the usual kinds of Windows GUI
applications that we use all the time. There is no need to worry if you
don't know what some of these things are, since you will be writing
console programs for the foreseeable future.) A console
program is one that has a simple (old-fashioned, if you like)
text-based interface, in which program output appears on lines that
scroll upward to the top of, and eventually off, the screen.
Whenever you do something in the Visual Studio 2008 version of
Visual C++, you generally do it within the framework of a single
project, or a solution containing several projects.
Whatever projects you've been working on are noted by Visual Studio,
and you are presented with a list of the most recent ones via the
Recent Projects pane on the Start Page whenever you fire up Visual
Studio 2008. [However, this may not happen if you are using Visual
Studio in a strictly controlled networked environment where some
settings (including this one) are set back to their initial default
values every time you log in and start using the program anew.]
Visual Studio 2008 does its best to help you out when you're
working. Sometimes this can be pleasant and useful. Other times it can
be downright unpleasant and frustrating. It can also be quite
overwhelming, when you find, for example, that quite a number of files
you know nothing about have been created for you. Ignoring these extra
files is usually the best thing to do.
So, it is important to have a good sense of the big picture, and not
to be overwhelmed or intimidated by all the minutiae that need not
concern you, at least not in the short term.
Getting Started: Creating, Building, and Running a New "Win32
Console Application"
Here, in very brief form, is the sequence of steps necessary to
start a new project, enter a single source code file, and then build
and run the executable:
- Start Visual Studio 2008 from the appropriate submenu of your
Start menu. After a short wait, among the things you will see on your
screen will be a "Start Page" window in the center of your screen
containing four smaller panes, one of which is labeled "Recent
Projects". The contents of the other panes may vary, depending on
what you are doing in Visual Studio.
- In the "Recent Projects" pane, choose "Create: Project...".
- In the "New Project" window that opens up, choose the "Visual C++
Win32" option under "Project Types:" and "Win32 Console Application"
under "Templates:". Then enter the name of your project in the
"Name:" box ("Test", for example). The "Location:" box may contain
the path you want, and if so you can just leave it. Otherwise, you
will need to enter the full path to the location where you want your
project to be stored. (You may also want to make a note of this
location, so that you can look there later to see what files have
been created.) Next, be sure to uncheck the "Create directory
for solution" box. [The reason for this is that you are only creating
a single project, not a "solution" to contain several projects.] Now
you may click OK.
- A "Win32 Application Wizard" window opens up. Click on
"Application Settings", and make sure the "Empty project" box is
checked. Then click the "Finish" button. (Now is a good time to go to
Windows Explorer and check to see what files have shown up in the
location identified in the "Location:" box in the above step.)
- At this point your "Solution Explorer" window will contain, among
other things, an icon labeled by the name of your project. If so,
your project has been set up but doesn't contain any source code
yet.
- Under the "Project" menu choose "Add new item..." (or press
Ctrl+Shift+A). In the "Add New Item" window that opens up, choose
"Visual C++ Code" in the "Categories:" pane and "C++ file (.cpp)"
under "Visual Studio installed templates" in the "Templates:" pane.
On the other hand, if you already have a program file that you wish
to add to your project, rather than write a new one, you should
choose "Add Existing Item..." at the beginning of this step.
- Now, in the "Name:" box enter a name for your file. If this is to
be the file which contains the
main
function for your
project, you may want to give it the same name as the project, but
this is by no means necessary. You do not need to add .cpp to the
name, since Visual Studio knows this is a C++ file and will add it
for you.
- Now click the "Add" button and an editing window will open, into
which you may enter the source code for your program. If this is your
first time through, try the code for a simple "Hello, world!"
program.
- When you are ready to try a build, go to the "Build" menu and
choose "Build Solution" (or press Ctrl+Shift+B, or click on the
"Build icon" of the "Build toolbar" if that toolbar is displayed).
Your source code file is automatically saved to disk before the
build. The "Output Window" will open and display the results of your
build, including any compile-time or other errors that have shown up
in the attempt to build your solution. Note that if you have made an
error and have to make source code changes, the changes you made are
again automatically saved to disk when you choose to rebuild. You can
double click on any error line to show where that error has occurred
in your source code, or press F1 when the line is highlighted in the
"Output Window" to get more information from the Help system on the
error reported in that line.
- If the build is successful, an executable file with the same name
as the project and a .exe extension will have been created in the
Debug subdirectory. Next, go to the Debug menu and choose "Start
without debugging" (or press Ctrl+F5) to run your program. (Actually,
you can go here directly before the build step, and the build step
will be done before the run.) A console window should open and your
program should run in it. The IDE supplies its own pause at the end
of your program, but it is usually a good idea to place a pause of
your own at the end of each of your programs. If you don't, and you
run that executable by double clicking on it in Windows, you may not
see all of the output from your program, since the console window
that Windows Explorer opens will disappear the moment your program
ends.
- Once you have finished to this point, you may remove the first
file from your project and add a new one, you may close down the
current project and create another project, or you may shut down
Visual Studio itself.
Running your program outside Visual Studio
Once you have a working executable, you can run the program
independently of Visual C++ in the following two ways:
- You can double-click on the executable file while in Windows
Explorer. Once again, remember that without a pause at the end of
your program you may "miss" all or part of the output, since Windows
Explorer does not supply that "Press any key to continue" facility
that appears at the end of the Visual C++ IDE console window when a
console program is run.
- You may also open a console window yourself (by choosing Start |
Run, entering
cmd
and pressing Enter, for example) and
then run the program directly from the command line, in the "usual"
way.
Working with Files in a Project
Once you have added to your project all the files the project needs,
you may perform any of the following actions.
- Double click on the name of a source code file in the "Solution
Explorer" window to display it in the text editor window.
- Place the cursor in the word "include" (of any #include line),
right click, and then choose "Open Document" to view that particular
header file in the text editor window. Notice how a "name tab"
appears for each "window" that opens up in the text editor, above the
text of the currently active window. Just clicking on any such tab
will make the corresponding window active.
- Press Ctrl+F5 at any time to run the current executable. If it
has not yet been built, or if changes have been made in the source
code, you will be prompted to (re)build before running. Note again
that files are saved to disk as part of the build process.
- Choose "Rebuild Solution" from the Build menu at any time if you
wish to re-build everything for any reason (whether it has changed or
not).
- Press Ctrl+F7 if you just want to compile the source code file in
the active window, but not build an executable.
- A potentially confusing situation occurs if your program itself
reads from a data file: In this case, the IDE expects that file to be
in your project directory, even though the executable is in a
subdirectory called Debug in your project directory. Such a data file
does not have to be added to the project, so long as it is present
and in the right location. On the other hand, if you are running your
program from Windows Explorer, or from the command prompt in a
console window, your program and the data file from which it reads
must be in the same directory, unless you supply to your program the
full path to a file in some other location.
- To remove a file from the current project, click on the file in
the "Solution Explorer" window and press the Delete key. In the
window that opens up be sure to choose the "Remove" option to delete
that file from the current project (though not from its
physical location on disk). If you really do want to delete the file
entirely in addition to removing it from the project, choose the
"Delete" option.
The Text Editor: Creating and Modifying Source Code Files
The first thing to know about the Visual Studio text editor is that
many of the "usual" commands for navigation and applying changes to
text that are familiar to users of other Microsoft products (such as
Word) also work here, and (mercifully) in the same way. Hence, assuming
this familiarity, we shall not give the details of those commands here.
It is therefore assumed that you are familiar with what the following
keyboard commands do for you when editing text: the four arrow keys,
Home, End, Ctrl+Home, Ctrl+End, PageUp, PageDown (and using the Shift
key with any of these motion commands to select text), as well as
Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+A, and Ins.
We list below some commands and features that are either not present
in other applications, or are not as widely known or used, but which
you may find useful in the Visual Studio .NET Visual C++
environment:
- Let the editor's "smart autoindent" feature work for you. It
knows, for the most part, how your code should be formatted, and you
should let it decide, for example, things like what the indent level
should be (4 spaces), and the proper placement of braces. This
feature should be on by default. In fact, you can select a section of
code that has had its formatting "messed up", or is not formatted
quite right, and have the whole thing properly formatted for you
automatically by pressing Ctrl+K, then Ctrl+F.
- If a group of contiguous lines of code need to be indented or
unindented one or more levels, select those lines of code and then
press the TAB key to indent them an additional level, or the
Shift+TAB combination to "unindent" them one level.
- It is a good idea to have no TAB characters in your
file. You can remove all TAB characters from a file at any time by
selecting your entire file with Ctrl+A and then choosing Edit |
Advanced | Untabify Selection. Ideally, your default setting should
be to have spaces inserted into your file when you press the TAB
key.
- Ctrl+R, then Ctrl+W toggles the display of whitespace in your
source code. Blank spaces show up as a dot, while each Tab character
shows up as a small rightward-pointing arrow (->). This is a great
help when you want to check whether in fact you have removed
all the tabs from your source code, or any other document.
- To set Visual Studio itself to handle Tab characters in the
appropriate way, go to Tools | Options | Text Editor | C/C++ | Tabs
and set "Indenting" to "Smart", both "Tab size:" and "Indent size:"
to 4, and activate "Insert spaces" rather than "Keep tabs". With
these settings you should never have to "untabify" your code again,
since spaces will automatically be inserted whenever you press the
TAB key, and your indentation levels will always be 4. These settings
must of course be compatible with whatever programming style
conventions you are using.
- Double-clicking on the little rectangular box above the up-arrow
at the top of the scroll-box region at the right of the text editor
window will split the current window into two equal parts, one above
the other, as will choosing "Split" from the "Window" menu. This
gives you two views of the same file, which can be scrolled and
edited independently. Double-clicking on the separating bar will
return you to a single window, as will choosing "Remove Split" from
the "Window" menu.
- Ctrl+K, then Ctrl+K toggles an unnamed bookmark at the cursor
line, and Ctrl+K, then Ctrl+N moves to the next bookmark, while
Ctrl+K, then Ctrl+P moves to the previous bookmark. Ctrl+K, then
Ctrl+L clears all bookmarks in the current window.
- Ctrl+G allows you to go to various locations, including (probably
most usefully) a particular line number.
- When the cursor is on either side of a bracket (round, square,
curly, or angle), Ctrl+] will place the cursor on the matching
bracket symbol.
- Ctrl+U/Ctrl+Shift+U converts selected text to lower/upper
case.
- To change the font size, choose "Tools | Options | Environment |
Fonts and Colors", and then choose your desired size in the "Size:"
box.
- You can toggle a source file window between its regular size and
a full screen with either the menu command View | Full Screen, or
Shift+Alt+Enter. Even in full screen mode, a menu bar is retained at
the top of the window.
- Ctrl+Z undoes the previous change. Pressing it again undoes the
change before that, and so on. If you undo one change to many, you
can "re-do" the last undo with a Ctrl+Y.
- Clicking in the blank area to the left of the a line in the edit
window selects that line.
- Tab/Shift+Tab indent/unindent selected text one level of
indentation.
- Ctrl+Tab cycles through the queue of open windows, much like
Alt+Tab does in Windows itself.
- Ctrl+F opens a Find dialog box for entry of a search string,
after which F3/Shift+F3 find the next/previous instances. Esc gets
you out of Find and back to the source code window.
- Ctrl+F3 will start a search for selected text.
- Ctrl+H starts a Find/Replace.
- Ctrl+I starts and "incremental search", i.e., a search that
starts as soon as you begin typing and looks for the first instance
of as much as you have typed in so far, and Ctrl+Shift+I starts a
similar backwards search.
- Ctrl+Shift+T interchanges the current and following words, while
Alt+Shift+T interchanges the current and following lines.
- Ctrl+Delete deletes from the cursor up to but not including the
first character of the next word to the right. Ctrl+Backspace deletes
from the cursor back to, and including, the nearest character to the
left that appears as the first character of a word.
- Ctrl+L deletes the current line and places it on the clipboard,
Ctrl+Shift+L deletes it without placing on the clipboard (i.e., it's
gone).
- Ctrl with the arrow keys provides some useful commands:
Ctrl+RightArrow moves the cursor to the beginning of the next word,
while Ctrl+LeftArrow moves the cursor to the beginning of the
previous word. Ctrl+UpArrow scrolls the window down one line, while
Ctrl+DownArrow scrolls the window up one line, with the insertion
point remaining fixed in both cases.
- Ctrl+K, then Ctrl+C will "comment out" any lines you have
selected, while Ctrl+K, then Ctrl+U will remove the comments from
selected lines commented out with C++ style comments.
-
Visual Studio has a number of other useful features that we will
not describe in detail here. We do mention them, however, since you
should at least know about them, and do your best to explore their
possibilities, as needed, in the course of your program
development:
- the "Task Window", which generally pops up, along with the
"Output Window", when you build a project, and can be useful in
tracking and/or annotating problems, or things-to-do, related to
your project
- "Outlining" of source code (see under Edit | Outlining),
which allows you to alternately collapse and expand selected
sections of code in your editing window
- the "Clipboard Ring", which may be helpful if you have some
complicated cutting and pasting you want to do
- the display of line numbers, on the screen and/or on a
hard-copy printout of your code
- By default your "Working Directory" is your project
directory. This means that this is where the IDE looks for
certain things, such as an input data file from which your
program expects to read data, as well as files your program
includes via #include directives. You may change the
working directory by going to Properties | Configuration
Properties | Debugging and entering the path to the desired
working directory in the Working Directory box.
Debugging
As your programs get more complex, you may from time to time want
(or need) to use the Visual C++ debugger to help you track down a
run-time error or see where your program is going astray as it
executes. When you start debugging, a number of windows will open
automatically. It may be useful to explore the various options that are
available to you for viewing, and for other actions, via these windows.
Here is a brief list of some debugger commands:
- Choose your break points, which can be toggled on and off, either
by pressing F9, or by clicking in the grey vertical bar to the left
of the code, when the cursor is on the code line at which you wish to
break during a run.
- Start debugging by choosing Debug | Start, or by simply pressing
F5.
- Press F10 to step through your code a line at a time (without
going into functions, which may be what you need most of the time),
or F11 to step through your code, including the internal code of
functions.
- To skip over some code place the cursor at the point to which you
would like to go without stopping and then press Ctrl+F10 to "run to
the cursor".
- Press Shift+F5 to stop debugging and Ctrl+Shift+F5 to
restart.
Useful Miscellaneous Information
- An editor macro is like a C++ function (or C++ macro,
for that matter) that can be called upon to perform a specific task.
A number of editor macros may be available for your use,
and, if so, they will be described elsewhere.
- If your program uses command-line parameters and you are testing
it with the IDE, in the "Solution Explorer" window select your
project, right click and choose "Properties". In the "Property Pages"
window that opens, choose Configuration Properties | Debugging and
then enter your command line arguments in the "Command Arguments:"
box.
- If your program uses RTTI (which stands for Run-Time Type
Identification, or Run-Time Type Information, depending on where you
read about it), this feature may need to be "turned on". To do this,
first right click on the name of your project in the "Solution
Explorer" window and then choose "Properties". In the "Property
Pages" window which appears, choose "C/C++" and then "Language". One
of the lines in the sub-window that then appears is labeled "Run-Time
Type Info", and this option must be set to
Yes
.
- When you start using C++ with Visual Studio .NET, you may get
some (or a lot) of "Warning" messages at compile time that you are
not used to seeing, particularly if you are using the STL. These
warnings will be numbered, and if you know that whatever the
"problem" is truly will not affect your code, you can avoid such a
message with a line like the following placed at the beginning of
your program, just before your #include directives. If the warning is
numbered 4786 (for example), put in this line:
#pragma warning(disable:4786)
A "pragma directive" such as this one is a compiler-specific
instruction of some kind meant for the C++ pre-processor. Another
reason you might want to use such a pragma is to avoid the messages
from Microsoft telling you that certain perfectly standard features
have been "deprecated" (by Microsoft, apparently), strcpy
from the <cstring> header of the Standard Library
being one of them, for example.
-
If you wish to prepare a standalone package in the form of a
.obj file that others can link to, for use with simple
console programs, you should first ensure that the following
settings are made:
- Properties | Configuration Properties | C/C++ | General |
Debug Information Format = Disabled
- Properties | Configuration Properties | C/C++ | Code
Generation | Enable Minimal Rebuild = No
-
If you upgrade your compiler at any point, it is a good idea to
rebuild your old projects with the new compiler, and to discard any
of the IDE-generated files associated with those projects. Although
this is generally good advice, the practice can rise up to bite you
as well. For example, just blindly recompiling with Visual Studio
2005 a C++ program that worked fine when compiled with Visual
Studio 2003 produces an executable that no longer works on a
machine that only has Visual Studio 2003 on it. Or at least a Win32
Console Project produced by going through the same motions on 2005
that were used on 2003 produces this effect. You can get an
executable that is "backward runnable", using Visual Studio 2005,
by starting not with a Win32 Project, but with a General Project
and in addition to the two settings mentioned above, making the
following setting as well:
- Properties | Configuration Properties | C/C++ | Code
Generation | Runtime library = Multi-threaded (/MT)
- Thanks to Dr. Mark Young for the following observation: If you
are trying to make any of the settings mentioned in the previous two
list items, and you are not seeing the C/C++ option under
Configuration Properties on your project's Properties page, it is
likely because you are trying to set the property before adding a C++
file to your project. So ... make sure you have some C++ code in your
project before trying to set any of those properties.
Files Used/Created by Visual C++
If you are curious about what's in the many different kinds of files
that Visual C++ produces in the course of its meanderings toward your
final executable, check under "Files Created for Visual C++ Projects"
in the MSDN Library.
Using Built-In and Programmer-Defined Macros
An editor macro is like a C++ function (or C++ macro, for
that matter) that can be called upon to perform a specific task. Two
groups of editor macros are available for your use, and you should know
how to install them in Visual Studio and make them available to use
during your C++ program development.
First, there should be two files available from your course web
site. As of fall, 2008, these files are:
- CPP2008.vsmacros
- Samples.vsmacros
Download both of these files and store them in a suitable place. If
you have set up a Visual Studio 2008 C++ Test folder for your projects,
Visual Studio has probably created a "macros folder" for you, and you
can put these files there, but they don't have to be in that
location.
In any case, you need to make your Visual Studio aware of these two
file and their contents. To do this you have to open Visual Studio and
then perform the following steps for each file:
- Go to Tools | Macros | Load Macro Project...
- Browse to the location where you've stored the two files, click
on one of the files, and then click the Add button, which will add
that particular file of macros to Visual Studio.
Once you have the macros installed, you can use any one of them by
performing the following steps:
- Make sure the cursor in your code window is positioned at the
location where you want the action of the macro to be performed.
- Click on one or more of the plus signs (+) until you
come to the macro that you want to use.
- Right click on the name of the macro and choose Run from
the pop-up menu.
You can also write your own macros, and if there is time this is a
topic that may be discussed in the lab.
Using the TR1 and/or the Boost Library with Visual Studio 2008
For this information see here.
Compiling, Linking and Running C++ Programs from the Command
Line
Sometimes, in addition to working in the Visual Studio IDE, it is
convenient to do a quick compile, link and run of your program at the
command line. Among other things, this avoids creation of many of the
files that the IDE creates whenever you use it to build a project.
Thus, testing a program this way cuts down on the amount of real estate
consumed, if that is a consideration.
One thing to keep in mind if you are doing this is that you should
ensure that you open a Visual Studio 2008 command window, since this
will make certain things available that might be necessary and that
might not be available if you open just a "garden variety" command
window. You can do this a one of the Visual Studio options in your
Start menu, and you may also be able to open such a command window by
right clicking on the directory where you would like the command window
to open.
To compile and link a simple program, say hello.cpp, use
the following command:
> cl -EHsc hello.cpp
This will produce the files hello.obj and
hello.exe. In other words, it will both compile the source
code and link the resulting object file to produce the final
executable. Think of the -EHsc compiler switch as a way to avoid
complaints that the cl command will have if you don't use it (try
compiling without it just to see).
You may also use the cl command to just compile by supplying it with
the -c switch, after which you may use the link
command to explicitly link the resulting .obj file (along
with, perhaps, other .obj files).
It may also be possible to set up the "system include path" and the
"system library path" so that the cl and/or link
commands know where to find source files to be included and/or
.obj files to be linked, without explicitly indicating the
corresponding paths in your code or on the command line.
One thing to keep in mind when working at the command line is this:
you should do all of your compiles at the command line. That is (for
example), if you have compiled a source code file within the Visual
Studio IDE, you should not necessarily expect the resulting
.obj file to link properly with another .obj file
that you have obtained by compiling at the command line.
Working Directories and #include Files
A recommended "best practice" is to create a single Test
project, and then simply move files into and out of the project as you
continue to work on various submissions and other programs. This works
well as long as your current project contains only one file, or a small
number of files. Even if this is true, over time your project folder
will start to fill up with source code files that really have no
connection with one another and your project directory will start to
get very cluttered.
So ... it makes sense to group the files that belong together and
place them in a subdirectory where they can be kept separate from the
files in the main Test project folder and also separate from the files
in other similar subdirectories.
But ... and this is the key concept here ... it would be even better
if we could put the files belonging together in a separate subdirectory
and still continue working on them as the current project with the
Visual Studio IDE, but without moving them back into the project folder
itself. Fortunately, we can. We just have to make sure we tell Visual
Studio where to find the things that it needs.
Let's suppose you have a subdirectory called other in your
Test project directory. If the files you want the ID to work
on are in this directory, the first thing you should do is make this
your working directory. Here's how you do this:
- Right click on your project name (Test, say) in the
Solution Explorer pane.
- Choose the Properties option at the bottom of the pop-up
list.
- In the Test Property Pages window that opens, choose
Configuration Properties | Debugging in the left pane and then click
on the Working Directory line in the right pane.
- Browse to the other directory, then click on it and make
sure the full path to this directory shows up as the Working
Directory.
Doing this tells Visual Studio to look for whatever files in needs
in this directory, rather than in the main project directory. For
example, if it needs to include a file like utilities.h, it
will look for it there. Or, if you are working on a C++ file that wants
to open and read from a textfile, it will look, by default, for that
file in the current working directory as well.
Note, however that a potential difficulty arises here. The
utilities.h file is not in the other
subdirectory; it's in the main project directory Test. We can
fix this problem in at least three ways:
- First, we can copy (or move) the utilities.h file into
whatever subdirectory is our current Working Directory. It should be
clear that this option is one to be avoided.
- Second, we can simply add the utilities.h file to our
project. In the beginning, we did not add this file to our project,
since it wasn't necessary as long as it was in our main project
folder Test, which (by default) was also the current Working
Directory.
-
Third, we can explicitly add our Test project folder as one of the
places where Visual Studio looks for #include files, even if its
current working directory is somewhere else. Here's how we do this:
- Click on the Tools menu and choose Options... at the bottom
of the pop-up list.
- In the Options window that opens up, choose Projects and
Solutions in the left pane, and then click on VC++ Directories.
- In the "Show directories for:" box at the upper right,
choose "Include files" from the drop-down list.
- Now press Ctrl+Insert to open up a new line in the list
of include directories.
- Now browse to, and then click on, your main project directory
folder (Test, or whatever) and make sure the full path
to that directory shows up in the new line you've created.
- Finally, click OK to close the window.