CS210 Lab: Introduction to Visual C++


Prelab Questions:

For a review of relevant topics click here.

Highlights of This Lab:

Lab Exercise: Exercise link

Click the little computer above for a detailed description.
For this excercise you will debug a program and demonstrate the correct results to your lab instructor.


1. Introduction to Visual C++.

Visual C++ comes within Microsoft Visual Studio. Visual Studio also contains Visual Basic, Visual C#, and Visual J#. Using Visual Studio, you can mix and match languages within one "solution". We will, however, focus on developing C++ code throughout these labs.

Visual Studio is a programming environment that contains all the libraries, examples, and documentation needed to create applications for Windows. Instead of talking about programs (as we did in CS110 and CS115), we talk about projects and solutions. Solutions can contain several projects and projects typically contain multiple items or files. For more information about projects, see the MSDN Solution and Project Basics page.

1.1 Creating Your First C++ Program

A console mode application is a text based program that is meant to run from a command prompt.

For your first C++ program, you will build a console mode application that displays a greeting message. This (i.e. a console mode application) is the kind of VC++ programs that you will build for all your lab and class exercises/assignments.

Console mode programs are often simpler to build than Windows applications, and this example will take you through the steps of creating, building and executing a program in Visual C++. We first assume that you use the built-in code editor in Visual Studio to edit your code; then we will show you how to build and run your C++ programs that you have created with any external editors.

1.1.1 How to start

Press Start | All Programs | Microsoft Visual Studio 2013 | Visual Studio 2013

You may also find a shortcut to Visual Studio 2013 on your desktop.

1.1.2 Starting Your First Program

If this is the first time Visual Studio being used, you have to choose your Select Visual C++ Development Settings, then click on Start Visual Studio. Note: If you want to choose another environment later, to to the menu and click Tools | Import and Export | Reset all Settings | Next, then you can pick either save current settings or overwrite current settings.

The next thing you will see is the Start Page.

Visual Studio start screen
To get started on your first program, you must create a "project" that will keep track of all the parts of your program, including the C++ source code, the header files, etc. Therefore, click the "Create Project" link. A "New Project" dialogue box similar to the one below will appear.
New project dialog
Follow these steps: The "Win32 Application Wizard" will appear. As demonstrated below, click on Application Settings, uncheck both Precompiled Header and Security Development Lifecycle (SDL) checks, then select Empty Project.
Console project wizard dialog

After this, click on Finish. You will notice that it doesn't appear like anything has changed. However, if you look at the Solution Explorer on the right-hand side you will see "Solution 'hello' (1 project)".

You want to add C++ source code to this project.

This file will be added to the hello workspace that we have just created, and a blank document will be opened for editing

Exercise:

Type the following program in the source code editor:

// FILE:     hello.cpp
// PURPOSE:  An example of a simple I/O stream 

#include <iostream>
using namespace std;

int main()
{
	char name[50];
	cout << "Please enter your name:" << endl;
	
	cin >> name;
	cout << "Hello, " << name << endl;
	return 0;
}

Save hello.cpp after you have finished editing it.

1.1.3 Building the hello Project

In order to compile any code in Visual C++, you have to create a project. A project holds three major types of information:

1) It remembers all of the source code files that combine together to create one executable. In this simple example, the file hello.cpp will  be the only source file, but in larger applications you often break the code up into several different files to make it easier to understand (and  also to make it possible for several people to work on it  simultaneously). The project maintains a list of the different source files and compiles all of them as necessary each time you want to create a  new executable. 

2) It remembers compiler and linker options particular to this specific application. For example, it remembers which libraries to link into the executable, whether or not you want to use pre-compiled headers, and so on.

3) It remembers what type of project you wish to build: a console application, a windows application, etc.

If you are familiar with makefiles, then it is easy to think of a project as a machine-generated makefile that has a very easy-to-understand user interface to manipulate it. For now we will create a very simple project file and use it to compile hello.cpp.

Exercise:

  1. Compile the hello project by selecting BUILD | Compile from the main menu.
    It simply compiles the source file and forms the object file (hello.obj) for it. It does not perform a link, so it is useful only for quickly compiling a file to check for errors.
  2. Select BUILD | Build hello from the menu bar to link the program.
    It compiles all of the source files in the project that have been modified since the last build, and then links them to create an executable.
  3. Choose DEBUG | Start Without Debugging to run the program.
    Start without debugging menu entry
    A DOS window will popup.

If errors or warnings are displayed in the Build status window, there is probably an error in the source file. Check your source file again for missing semicolons, quotes, or braces.

Now, we will continue using Visual C++ in another project, so select File | Close Solution. This will return you to the Start Page.

1.2 How to compile, link and execute a program with multiple files?

The preceding section showed the procedure for creating a C++ program with only one file component, hello.cpp, and we used the built-in VC++ source code editor to edit the file. However, when you are working on a large program, you would break your program into smaller, more manageable parts. In other words, your project would contain more than one C++ source file. You can create each file yourself, just like you did with hello.cpp, or you can add C++ source files from somewhere else.

The following section demonstrates how to create, compile, and execute a VC++ project with more than one file.

Exercise:

1.2.1 Creating the project

  1. Select File | New | Project....
  2. Set the project name to lab1.
  3. Make sure Create directory for solution it not selected
  4. Pick a project location, for example C:\Users\userid\Documents\Visual Studio 2013\Projects\.
  5. Click on "OK" to create the project.
  6. Under "Application Settings", select Empty project and unselect Security Development Lifecycle.
  7. Click on Finish.
You have now created a project that has information stored in the following folder:
C:\Users\userid\Documents\Visual Studio 2013\Projects\lab1\

It is always a good practice to put the source files in the project folder. Let's do that now.

1.2.2 Get multiple files using anonymous FTP

Obtain the files you need for this lab by clicking here: CS Dept FTP Server Even though the files are in the appropriate directory, you must tell Visual Studio that these files are part of the project.

1.2.3 Adding existing files to the project

  1. Select PROJECT | Add Existing Item....
  2. You should be looking in the lab1 directory. Highlight the .h and .cpp files: date.cpp, date.h and main.cpp
  3. Select "Add" to add the files to the project.

To view the contents of any of these files, double click on the file name in the "Solution Explorer".

1.2.4 Compile, build and execute your progam

  1. Select BUILD | Build lab1 (This will compile and link the files).
  2. Select DEBUG | Start Without Debugging

2. Debugging C++ Programs

Like most people, you may find that your programs do not work as you expected the first time you run them. To find out what is wrong, you might use cout statements to follow the line of execution of your code. This works, but later, when things are fixed, you must remember to remove all the extra cout statements.

Visual Studio provides a wonderful debugger for helping you find run-time errors in your code. However, before we get into the details of how to use this debugger, some terminology might be useful. Notice that the keywords below are links to pages (with the sources of this information)

Syntax Errors
  • Errors in code due to not following the rules of the language.
  • These errors are caught by the compiler or interpreter.
Semantic Errors
  • Code follows the rules, but it does not do as you intended.
  • These errors are NOT caught by the compiler or interpreter.
  • They can cause a program to crash or hang.
Logic Errors
  • Variables do not contain correct data or program doesn't go down right path.
Debugger
  • Allows you to see what is happening when you run your program so that you can determine the location of semantic and logic errors.
  • Can break (suspend) the execution of the program to examine code, view or change variable values, etc.
Breakpoints
  • "A breakpoint tells the debugger that an application should break, or pause, execution at a certain point."
  • Allows you to suspend exececution so that your program runs until it reaches a breakpoint (in the form of a place or condition that you would like to examine in more detail). You can then walk through the code line by line or instruction by instruction.

When your program is stopped at a breakpoint, your program and debugger are said to be in break mode. Visual Studio has four basic types of breakpoints:

  1. Simple breakpoint—program breaks at specified location within a specified file
  2. Function breakpoint—program breaks at specified location within specified function
  3. Address breakpoint—program breaks when it reaches a specified memory address
  4. Data breakpoint—breaks when the value of a variable changes

Remember that your project must compile and link before you can use the debugger.

As a general overview to debug your project you must:

The basic command to start the debugger can be found under DEBUG | Start Debugging in the main menu.

Start debugging menu entry

The Debugger will execute code from the current location until it reaches a breakpoint, the end of the program, or a point at which the program pauses to get input from the user. When the debugger is started, the "Debug" menu changes to have some additional commands which are also displayed on the toolbar. A few of these commands are summarized in the following section.

2.1 Useful commands


3. Sample Exercise--Debugging

The location:	ftp://ftp.cs.uregina.ca/pub/class/210/ftp/VCIntro 

The file:       debug.cpp 

Follow these steps to debug debug.cpp program:

  1. Set up a project for this program (follow the same procedure as discussed in Section 1 of this lab.). Name this project debug.
  2. Build debug. If there are any compiler or linker errors, correct them. (Remember, your program should pass the compilation before you can use the debugger).  However, if you spot any logical errors in this program, DO NOT correct them at this point.
  3. Run the program as usual to see how it works. Do not use the debugger yet.  Enter 1, 2, 3, 4, 5 as the input.  The first thing you will notice is that the five numbers printed out by the program are not the same numbers that you have just entered. Therefore, something is wrong with the program.  We will use the debugger to find out what is wrong.
  4. Set up a break point. As we mentioned earlier, a breakpoint is any point in the executable code where the execution stops. A breakpoint pauses the execution of a program so that the programmer can take a look at what is going on inside the program when it runs. At this point, we do not know what caused the program to go wrong, so we set up a breakpoint after the first cout statement. To do this, click to the left of the following for statement:
    sample breakpoint
  5. Run the program with debugging. Select Debug | Start Debugging from the main menu. The program will start to execute, then stop at the breakpoint. Notice that the output window (at the bottom) splits into two windows with tabs. The VC++ work windows have changed, now showing the source code window across the top. A yellow arrow, which indicates the current line of code being executed, has appeared on top of the red "breakpoint" dot. (See the following figure:)
    debug in progress
  6. Use watch windows to trace the values of variables. There are three kinds of watch windows in VC++ that you should know about: Autos, Locals and Watch 1, as is illustrated in the above figure. These watch windows enable the programmer to watch the state of the variables as the program executes, and thus to see if the program is doing what was intended.
  7. Step through the code. VC++ programming environment allows you to step through the code in two different ways.  You can a) execute one line at a time, stepping into each function call, or b) run the function without tracing what is going on inside the function.  We will look at examples of the first.

    Right now, the execution of your program halts after the first cout statement is executed, because we set a breakpoint there.  This is indicated by a yellow arrow inside the red dot: breakpoint and current
   location. Let's step into the loop and see what happens.

    On the Tool bar are three important icons to use with the debugger. One shows a blue arrow jumping over some lines of code (Step Over F10) Step Over Icon. Another shows the arrow pointing into the braces (Step Into F11) Step Into Icon. These are the buttons for single stepping through a program. There is also, the Step Out button, which allows you to skip large blocks of code in debugging. Let's use the Step Over Button first.

    Press the Step Over button Step Over
   Icon. The yellow arrow will move to the next line.  Keep pressing the Step Over button until the the console window pops into the forground asking you for input:

    command pop up

    At this point, the program is expecting some input from the user. Enter the number 5 as input and hit return.

    Now click on the plus sign to the left of the variable Values in the Watch Window to expand that variable. We notice that something is wrong here: the first number we entered just now should be assigned to Values[0], but instead, it is assigned to Values[1]:

    error in watch window

    Examine the code in the source code window, and you will find that inside the first loop block, the statement
    cin >> Values[1];
    should read: cin >> Values[i];;
    otherwise, all the keyboard input will go to Values[1]. Change this line of code; recompile and rerun the program and it should work properly.

We leave it to you to explore other features of the VC++ debugging utility.


4.Debugger Tips

In this lab example, we used the Step Over to examine the loop.  What will happen if we use Step In? Well, Step In will examine the program one line a time and it will go into every function if a function is called.  Therefore, if we use Step In to examine the loop with the cout and cin statements, we would have stepped into the  cout and cin system functions. this is not what we want. So when you debug your program, whenever you encounter the system functions, which do not need to be debugged, use Step Over instead of Step In. 

This is one of the tricky part of the debugging process which could get you into trouble.  You will get into even more troubles if you do not know what you are doing.  The following are some surprises, how they happened, and how to deal with them.

If all else fails, you can always select DEBUG | Restart to start your program over again, or select DEBUG | Stop Debugging to quit execution of your program and stop debugging altogether.


Lab Exercise #1

The location: ftp://ftp.cs.uregina.ca/pub/class/210/ftp/VCIntro/

The files: Prime_example.cpp 

Lab Exercise #2

The location:	 ftp://ftp.cs.uregina.ca/pub/class/210/ftp/VCIntro/newLL

The files: LinkedList.cpp,LinkedList.h, and main.cpp 

CS Dept Home Page CS Dept Class Files CS210 Class Files

© 2020 Department of Computer Science, University of Regina.