Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

lafore_robert_objectoriented_programming_in_c

.pdf
Скачиваний:
51
Добавлен:
27.03.2023
Размер:
8.94 Mб
Скачать

Microsoft Visual C++

865

To compile and link your source file, select Build from the Build menu. A dialog box will appear asking if you want to create a Default Project Workspace. Click Yes. The file will be compiled and linked with any necessary library files.

To run the program, select Execute from the Build menu. If all goes well, a console window will appear with the program’s output displayed in it.

When the program terminates, you’ll see the phrase Press any key to continue. The compiler arranges for this phrase to be inserted following the termination of any program. It keeps the console display on the screen long enough for you to see the program’s output.

When you’re done with a program, close its workspace by selecting Close Workspace from the File menu. Answer Yes when asked if you want to close all document windows.You can also run programs directly from MS-DOS. You can start up a box for MS-DOS by clicking the Start button and selecting Programs and then the MS-DOS Prompt item. In the resulting window you’ll see what’s called the C-prompt: the letter C, usually followed by the name of the current directory. You can navigate from one directory to another by typing cd (for Change Directory) and the name of the new directory. The .EXE files for programs compiled with MVC++ are placed in a directory called DEBUG, which is a subdirectory of the one holding your project files. To execute a program, including any of the examples from this book, make sure you’re in the same directory as this .EXE file, and enter the name of the program (with no extension) at the MS-DOS prompt. You can find out more about MS-DOS using the Windows help system.

Writing a New File

To start writing your own .CPP file in MVC++, close any open workspace, select New from the File menu, and click the Files tab. Select C++ Source File, type the file name, and either type the path into the Location box or navigate to the directory where you want the file. Click OK. A blank document window will appear. Type your program into this window. Save the new file by selecting Save As from the File menu. As before, select Build from the Build menu and click Yes in response to the default workspace question. Your program will be compiled and linked.

Errors

If there are errors, they will appear in the Build window at the bottom of the screen. (You may need to click the Build tab to make this window appear.) If you double-click the error line, an arrow will appear next to the line containing the error in the source file. Also, if you position the cursor on the error number in the Build window (such as C2143) and press the F1 key, an explanation of the error will appear in the document window. You can correct the errors and repeat the build process until the message reads “0 error(s), 0 warning(s).” To execute the program, select Execute from the Build menu.

C

C++ISUALV

ICROSOFTM

Appendix C

866

A common error when writing a new program is forgetting the statement

using namespace std;

If you leave this out, the compiler will complain that it doesn’t recognize cout, <<, endl, and so on.

Before starting work on a new program, don’t forget to select Close Workspace from the File menu. This ensures that you begin with a clean workspace. To open a program you’ve already built, select Open Workspace from the File menu, navigate to its directory, and double-click the file with the appropriate name and the .DSW extension.

Run-Time Type Information (RTTI)

A few programs, such as EMPL_IO.CPP in Chapter 12, “Streams and Files,” use RTTI. With MVC++ you need to enable a compiler option to make this feature work. Select Settings from the Project menu and click the C/C++ tab. From the Category list box, select C++ Language. Click the check box named Enable Run-Time Type Information. Then click OK. This will avoid various compiler and linker errors, some of which are misleading.

Multifile Programs

We’ve shown the quick and dirty approach to building programs. This approach works with one-file programs. When projects have more than one file, things become slightly more complicated. We’ll start by reviewing what’s meant by the terms workspace and project.

Projects and Workspaces

MVC++ uses a concept called a workspace, which is one level of abstraction higher than a project. A workspace can contain many projects. It consists of a directory and several configuration files. Within it, each project can have its own directory, or the files for all the projects can simply reside in the workspace directory.

Conceptually it’s probably easiest, at least for the small programs in this book, to assume that every project has its own separate workspace. That’s what we’ll assume in this discussion.

A project corresponds to an application (program) that you’re developing. It consists of all the files needed to create that application as well as information about how these files are to be combined. The result of building a project is usually a single .EXE file that a user can execute. (Other results are possible, such as .DLL files.)

Microsoft Visual C++

Developing the Project

Let’s assume that the files you want to include in a new project already exist, and that they are in a particular directory. Select New from the File menu, and click the Projects tab in the New dialog box. Select Win32 Console Application from the list. First, in the Location box, type the path to the directory, but do not include the directory name itself. Next, type the name of the directory containing the files in the Project Name box. (By clicking the button to the right of the Location field you can navigate to the appropriate directory, but make sure to delete the directory name itself from the location field.) Make sure the Create New Workspace box is checked, and click OK.

For example, if the files are in C:\Book\Ch13\Elev, you would first type C:\Book\Ch13\ in the Location field and then Elev in the Project Name field. When you type the project name, it’s automatically added to the location. (If it were there already it would be added again, resulting in a location of C:\Book\Ch13\Elev\Elev, which is not what you want.) Another dialog appears. Make sure the An Empty Project button is selected, and click Finish. Click OK on the next dialog box.

At this point various project-oriented files, with extensions .DSP, .DSW, and so forth, have been added to the directory, along with a DEBUG subdirectory that will hold the final .EXE file.

Adding Source Files

Now you need to add your source files to the project. This includes your .CPP files and any .H files you want to view from the File tab. Select Add To Project from the Project menu, click Files, select the files you want to add, and click OK. You can review the files you’ve selected by clicking the FileView tab and then the plus sign for the project. You can also see the class structure, complete with member functions and attributes, by clicking the ClassView tab.

To open a file so you can see it and modify it, double-click the file’s icon in the FileView window. You can also select Open from the File menu and select the file.

Locating Header Files

Your project may use header files (usually with the .H extension), such as MSOFTCON.H in programs that use Console Graphics Lite. These don’t need to be added to the project (unless you want to view them from the File tab), but the compiler must know where to find them. If they’re in the same directory as your source files, this isn’t a problem. Otherwise, you must tell the compiler where they are.

Select Options from the Tools menu. Click on the Directories tab. Select Include Files from the Show Directories For list. You’ll see the directories that hold the compiler’s own include files. Double-click the dotted box on the bottom line of this list. Then navigate to the directory containing your header file, using the button that appears on the right. The dotted box will be replaced by the new pathname. Click OK. Alternatively you can type the complete pathname of the directory into the Location box.

867

C

C++ISUALV

ICROSOFTM

Appendix C

868

Saving, Closing, and Opening Projects

To save the project, select Save Workspace. To close the project, select Close Workspace. (Answer Yes to the Close All Document Windows query.) To open an existing project, select Open Workspace from the File menu, navigate to the proper directory, select the .DSW file, and click Open.

Compiling and Linking

As with one-file programs, the easiest way to compile, link, and run a multifile program is to select Execute from the Build menu. Alternatively, you can compile and link your project without running it by selecting Build from the Build menu.

Building Console Graphics Lite Programs

Building programs that use the Console Graphics Lite functions (described in Appendix E, “Console Graphics Lite”) requires some steps in addition to those needed for ordinary example programs. You will need the files MSOFTCON.H and MSOFTCON.CPP. These files, which are specific to this book, can be obtained from the publisher’s Web site, mentioned in the Introduction.

Open the source file for the program as described in the section “Building an Existing File.” This file should include the line #include “msoftcon.h”.

Select Build from the Build menu. Answer Yes when asked if you want to create a default project workspace. A project will be created, but the compiler will complain it can’t find MSOFTCON.H. This file contains the declarations for the graphics functions.

An easy solution is to copy MSOFTCON.H into your project’s directory. A more elegant approach is to tell the compiler where to find this file. Follow the instructions in the earlier section “Locating Header Files.”

Now try building your file again. This time the compiler can find the header file, but there will be numerous linker errors because the linker doesn’t know where to find the definitions for the graphics functions. This code is in MSOFTCON.CPP. Add this file to your project by following the steps in the earlier section “Adding Source Files.”

Now your program should compile and link correctly. Select Execute from the Build menu to see it run.

Debugging

In Chapter 3, “Loops and Decisions,” we suggest using the debugger to provide an insight into how loops work. Here’s how to do that with Microsoft Visual C++. These same steps can help you debug your program if it behaves incorrectly. We’ll be discussing one-file programs here, but the same approach applies, with appropriate variations, to larger multifile programs.

Microsoft Visual C++

869

Start by building your program as you normally would. Fix any compiler and linker errors. Make sure your program listing is displayed in the Edit window.

Single-Stepping

To start the debugger, simply press the F10 key. You’ll see a yellow arrow appear in the margin of the listing, pointing to the opening brace following main.

If you want to start somewhere other than the beginning of the program, position the cursor on the line where you want to start debugging. Then, from the Debug menu (which replaces the Build menu when you’re debugging), select Start Debug and then Run to Cursor. The yellow arrow will appear next to the statement selected.

Now press the F10 key. This causes the debugger to step to the next executable statement. The yellow arrow will show where you are. Each press of F10 moves it to the next statement. If you’re in a loop, you’ll see the yellow arrow move down through the statements in the loop and then jump back to the top of the loop.

Watching Variables

You can watch the values of your program’s variables change as you single-step through your program. Click the Locals tab in the window at the bottom left of your screen to see the values of local variables. The Auto tab shows the compiler’s selection of variables.

If you want to make your own selection of watch variables, enter them into the Watch window in the bottom right corner of your screen. To do this, right-click a variable name in the source code. A pop-up menu will appear. Select QuickWatch from this menu. In the resulting QuickWatch dialog box, click Add Watch. The variable and its current value will appear in the Watch window. If a variable is out of scope, such as before it’s been defined, the Watch window will show an error message instead of a value next to the variable name.

Stepping Into Functions

If your program uses functions, you can step into them (single-step through the statements within the function) by using the F11 key. In contrast, the F10 key steps over function calls (treats them as a single statement). If you use F11 to trace into library routines like cout <<, you can trace through the source code of the library routine. This can be a lengthy process, so avoid it unless you’re really interested. You need to switch judiciously between F11 and F10, depending on whether you want to explore a particular function’s inner workings or not.

C

C++ISUALV

ICROSOFTM

Appendix C

870

Breakpoints

Breakpoints allow you to stop the program at any arbitrary location. Why are they useful? We’ve already shown that you can execute the program up to the cursor location by selecting Run to Cursor. However, there are times when you want to be able to stop the program in multiple locations. For example, you might want to stop it after an if and also after the corresponding else. Breakpoints solve this problem because you can insert as many as you need. (They also have advanced features we won’t describe here.)

Here’s how to insert a breakpoint in your listing. First, position the cursor on the line where you want the breakpoint. Then click the right mouse button, and from the resulting menu select Insert/Remove Breakpoint. You’ll see a red circle appear in the left margin. Now whenever you run your program at full speed (by selecting Debug/Go, for example) it will stop at the breakpoint. You can then examine variables, single-step through the code, or run to another breakpoint.

To remove a breakpoint, right-click it and select Remove Breakpoint from the menu.

There are many other features of the debugger, but what we’ve discussed here will get you started.

Borland C++Builder

IN THIS APPENDIX

• Running the Example Programs in

 

 

C++Builder

872

 

 

 

Cleaning Up the Screen

873

 

Creating a New Project

873

 

 

Naming and Saving a Project

874

 

Starting with Existing Files

875

 

Compiling, Linking, and Executing

875

Adding a Header File to Your Project 876

Projects with Multiple Source Files

877

Console Graphics Lite Programs 878

• Debugging

878

 

 

 

A PPENDI X

D

Appendix D

872

This appendix tells you how to use Borland C++Builder to create console-mode applications, which are the kind of applications used in this book.

C++Builder is Borland’s most advanced development product, and, as of this writing, the C++ product that adheres most closely to Standard C++. It’s available in a student version for under $100. (Also, a free compiler-only system is available for download from the Borland Web site. You will need to use Notepad or some similar text editor to write your source files.) This discussion is based on C++Builder 5.0.

We’ll assume that C++Builder is installed on your system, and that you can start it by using the Windows Start button and navigating to the appropriate menu item: C++Builder.

You’ll want to make sure you can see file extensions (like .CPP) when operating C++Builder. In Windows Explorer, make sure that the option Hide MS-DOS File Extensions for File Types That Are Registered is not checked.

Running the Example Programs in C++Builder

The programs in this book require minor modifications to run under C++Builder. Here’s a quick summary.

You can compile most of the example programs and run them without modification in the the Windows MS-DOS window (Start/Programs/MS-DOS Prompt). However, if you want to run them from within C++Builder using the Run command from the Run menu, you’ll need to insert a statement at the end of the program to keep the console window on the screen long enough to see. You can do this in two steps:

Insert the statement getch(); just before the final return statement in main(). This enables you to see the program’s output.

Insert the statement #include <conio.h> at the beginning of main(). This is necessary for getch().

If the program you’re building uses Console Graphics Lite functions (described in Appendix E, “Console Graphics Lite”), you’ll need to take some additional steps. These are summarized later in this appendix.

In the balance of this appendix we’ll cover these points in more detail and describe how to use C++Builder to edit, compile, link, and execute console-mode programs.

Borland C++Builder

873

Cleaning Up the Screen

When it’s first started, C++Builder shows you some screen objects that you won’t need for console-mode programs. You’ll see a window on the right called Form1. Click on its close button (the X in the upper-right corner) to make it go away. Likewise, you won’t need the Object Inspector, so click its close button too. You’ll need to get rid of these items every time you start C++Builder.

When you remove the Form1 window you’ll find another window under it, with some C++ code in it. This is called the code editor window. It’s where you’ll look at source files and write your own programs. However, it starts with a file called UNIT1, and you don’t need this. Click the close button to make this window go away, and answer No if a dialog asks whether you want to save changes.

C++Builder starts with many more toolbars than you need. You probably need the Standard and Debug toolbars. Get rid of the others by selecting Toolbars at the bottom of the View menu and unchecking the toolbars you don’t want.

Creating a New Project

C++Builder (like other modern compilers) thinks in terms of projects when creating programs. A project consists of one or more source files. It can also contain many other kinds of files that we don’t need to be concerned with here, such as resource files and definition files. The result of a project is usually a single .EXE file that a user can execute.

To begin a new project, select New... from the File menu. You’ll see a dialog box called New Items. Click the New tab (if necessary). Then double-click the Console Wizard icon. In the resulting dialog box, make sure that the Source Type is C++ and that Console Application is checked. Uncheck Use VCL, Multi Threaded, and Specify Project Source. Click OK. Click No if another dialog asks whether you want to save changes to PROJECT1. You’ll see the following source file appear in a new code editor window:

//--------------------------------------------------------------

#pragma hdrstop

//--------------------------------------------------------------

#pragma argsused

int main(int argc, char **argv[])

{

return 0;

}

//--------------------------------------------------------------

D

UILDERC++B

ORLANDB

Appendix D

874

This is a skeleton version of a console-mode program. You don’t need some of the lines in this program, and you will need to add some others. We’ll make these changes, and add a statement to print some text so you can see whether the program works. Here’s the result:

//test1.cpp

 

#include <iostream>

 

#include <conio.h>

 

using namespace std;

 

//#pragma hdrstop

//not needed

//#pragma argsused

//not needed

int main()

//arguments not needed

{

 

cout << “Happy are they whose programs “ << “compile the first time.”;

getch(); return 0;

}

The two #pragmas aren’t necessary, and you don’t need the arguments to main().

If you run the original skeleton program without these modifications, you’ll find that the console window doesn’t remain visible long enough to see. As we noted, this is fixed by inserting the statement

getch();

at the end of the program, just before return. This causes the program to wait for a keystroke, so the console window remains in view until you press any key. The getch() function requires the CONIO.H header file, so you’ll need to include it at the beginning of your program.

If you’re creating your own program, you can start with the skeleton program and modify it. If you’re starting with an existing file, read the section “Starting with Existing Files.”

Naming and Saving a Project

You’ll need to save and rename both your source file and the project it’s in. The compiler automatically names the source file UNIT1.CPP. To save it and rename it, select Save As from the File menu, navigate to the directory for your project, name the file (keeping the .CPP extension) and click Save.

Information about a project is recorded in a file with the extension .BPR. Thus when you save a project, you’re actually saving both the .CPP file (or files) and the .BPR file. When you first create a new project, it’s called PROJECT1 (or a higher number).