⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 apd.htm

📁 Learning language of Visual C++6
💻 HTM
📖 第 1 页 / 共 2 页
字号:
to examine the local variables and code of the functions that called the function
now executing. After you've looked at everything you want to look at, it's time to
move on. Although there are items on the Debug menu to Step Over, Step Into, and
so on, most developers use the toolbar buttons or the keyboard shortcuts. The Debug
toolbar can be seen in Figures D.1, D.3, and D.5. Pause your mouse over each button
to see the command it is connected to and a reminder of the keyboard shortcut. For
example, the button showing an arrow going down into a pair of braces is Step Into,
and the shortcut key is F11.</P>
<P><A HREF="javascript:popUp('xduvc07.gif')"><B>FIG. D.7</B></A><B> </B><I>The number
32771 corresponds to ID_TOOLS_OPTIONS.</I></P>
<P>As you move through code, the yellow arrow in the margin moves with you to show
which line is about to execute. Whenever the program is paused, you can add or remove
breakpoints, examine variables, or resume execution. These are the mechanics of debugging.</P>
<P>
<H3><A NAME="Heading7"></A>Edit and Continue</H3>
<P>Most developers are familiar with the cycle of debugging work. You build your
project, you run it, and something unusual happens. You debug for a while to understand
why. You find the bad code, change it, rebuild, rerun, and either find another bug
or convince yourself that the application works. Sometimes you think you've fixed
it, but you haven't. As your project grows, these rebuilds can take a very long time,
and they break the rhythm of your work. It can also take a significant amount of
time to run the application to the trouble spot each time. It's very boring to enter
the same information every time on a dialog box, for example, trying to set up an
error condition.</P>
<P>In version 6.0 of Visual C++, in many cases you can keep right on debugging after
making a code change--without rebuilding and without rerunning. This feature is called
Edit and Continue and is sure to be a major time-saver.</P>
<P>To use Edit and Continue, you should start by confirming that it's enabled both
for the product as a whole and for this specific project. First, choose Tools, Options
and click the Debug tab. Make sure that Debug commands Invoke Edit and Continue is
selected, as in Figure D.8. Second, choose Project, Settings and click the C/C++
tab. In the left pane, make sure you are editing your Debug settings. Ensure that
the Debug Info drop-down box contains Program Database for Edit and Continue. If
not, drop the box down, select this option, as in Figure D.9 (it's last on the list),
and then rebuild the project after exiting the Project Settings dialog. Always check
the project settings when you start a new project, to confirm that Edit and Continue
is enabled.</P>
<P><A HREF="javascript:popUp('xduvc08.gif')"><B>FIG. D.8</B></A><B> </B><I>Enable
Edit And Continue on the Debug tab of the Options dialog.</I></P>
<P><A HREF="javascript:popUp('xduvc09.gif')"><B>FIG. D.9</B></A><B> </B><I>Your project
must generate Edit and Continue information.</I></P>
<P>Now, debug as you always did, but don't automatically click Build after making
a code change: Try to step to the next line. If it's not possible to continue without
a build, you will receive a line of output in the Build tab of the Output window
telling you so and the familiar One or More Files Are out of Date message box offering
you a chance to rebuild your project. If it's possible to continue, you will have
saved a tremendous amount of time.</P>
<P>Most simple code changes, such as changing the condition in an if or for statement
or changing the value to which you set a variable, should work immediately. More
complex changes will require a rebuild. For example, you must rebuild after any one
of these changes:</P>

<UL>
	<LI>Any change to a header file, including changing code in an inline function
	<P>
	<LI>Changing a C++ class definition
	<P>
	<LI>Changing a function prototype
	<P>
	<LI>Changing the code in a global (nonmember) function or a static member function
</UL>

<P>Try it yourself: Imagine that you can't remember why the string originally displayed
by ShowString is black, and you'd like it to be red. You suspect that the OnNewDocument()
function is setting it, so you expand CShowStringDoc in the ClassView and double-click
OnNewDocument(). Then you place a breakpoint (F9) on this line:</P>
<P>
<PRE>string = &quot;Hello, world!&quot;;
</PRE>
<P>Click Go (F5), or choose Build, Start Debug, Go; ShowString will run, create a
new document, and stop at your breakpoint. Change the next line of code to read</P>
<P>
<PRE>color = 1;   //red
</PRE>
<P>Click Go again and wait. Watch your output window and you will see that showstringdoc.cpp
is recompiling. After a short wait, the familiar Hello, world! will appear--in red.
Your changes went into effect immediately.</P>
<P>When you finish your debugging session, it's a good idea to do a build because
the changes used by Edit and Continue may be in memory only and not written out to
your executable file.</P>
<P>
<H3><A NAME="Heading8"></A>Other Debug Windows</H3>
<P>Three debug windows have not yet been mentioned: Memory, Registers, and Disassembly.
These windows provide a level of detail rarely required in ordinary debugging. With
each release of Visual C++, the circumstances under which these windows are needed
dwindle. For example, the Registers window used to be the only way to see the value
just returned from a function call. Now that information is in the Variables window
in a more accessible format.</P>
<P><B>The Memory Window&#160;&#160;</B>This window, shown in Figure D.10, shows you
the hex values in every byte of the memory space from 0x00000000 to 0xFFFFFFFF. It's
a very long list, which makes the dialog box hard to scroll--use the Address box
to enter an address that interests you. Typically, these addresses are copied (through
the Clipboard, not by hand) from the Variables window. It is a handy way to look
through a large array or to track down subtle platform- dependent problems.</P>
<P><A HREF="javascript:popUp('xduvc10.gif')"><B>FIG. D.10</B></A><B> </B><I>You can
examine raw memory, though you'll rarely need to.</I></P>
<P><B>The Registers Window&#160;&#160;</B>If you are debugging at the assembler level,
it might be useful to examine the registers. Figure D.11 shows the Registers window.
This shot was taken at the same point of execution as Figure D.5, and you can see
that the EAX register contains the value 1, which is the return value from DoModal().</P>
<P><A HREF="javascript:popUp('xduvc11.gif')"><B>FIG. D.11</B></A><B> </B><I>All the
registers are available for examination.</I></P>
<P><B>The Disassembly Window&#160;&#160;</B>By default, the Disassembly window comes
up full screen, replacing the C++ code in the main working area. You can see the
assembly language statements generated for your C++ code, shown in Figure D.12. Debugging
at the assembly level is beyond the scope of this book, though perhaps you might
be curious to see the assembly code generated for parts of your program.</P>
<P><A HREF="javascript:popUp('xduvc12.gif')"><B>FIG. D.12</B></A><B> </B><I>You can
debug the assembler that was generated for you.</I></P>
<P>
<H2><A NAME="Heading9"></A>Using MFC Tracer</H2>
<P>The MFC Tracer utility is a standalone application with an integrated menu item
in the Developer Studio. To run it, choose Tools, MFC Tracer. Figure D.13 shows the
Tracer dialog that appears.</P>
<P><A HREF="javascript:popUp('xduvc13.gif')"><B>FIG. D.13</B></A><B> </B><I>A standalone
utility simplifies setting trace flags.</I></P>
<P>Tracer doesn't do very much: It's just an easy way to set trace flags that govern
the kind of debug output you get. Try setting all the flags on and running ShowString,
simply starting it up and shutting it down. Turn off a few flags and see how the
output changes.</P>
<P>With all the trace flags on, your application will be slow. Use Tracer to set
only the ones you're interested in, while you're interested in them. It's much easier
than changing a variable on- the-fly.</P>
<P>
<H2><A NAME="Heading10"></A>Defining a Dump Member Function</H2>
<P>All MFC classes have a Dump() member function. When things go wrong, some error-handling
code calls this function to show you the object's contents. You can write Dump()
functions for your objects, too. Although you won't normally call these functions
yourself, you could do so as part of your own error handling.</P>
<P>MFC classes inherit Dump() from Cobject, where it is defined like this:</P>
<P>
<PRE>virtual void Dump(CDumpContext&amp; dc ) const;
</PRE>
<P>The keyword virtual suggests you should override the method in your derived classes,
and const indicates that Dump() will not modify the object state.</P>
<P>Like trace and assert statements, the Dump() member function disappears in a release
build. This saves users seeing output they can't deal with and makes a smaller, faster,
release version for you. You have to make this happen yourself for any Dump() function
you write, with conditional compilation, as discussed in the &quot;Adding Debug-Only
Features&quot; section of Chapter 24.</P>
<P>In the header file, declare Dump() like this:</P>
<P>
<PRE>class CNewClass : public CObject
{
public:
     // other class stuff
     #ifdef _DEBUG
     virtual void Dump( CDumpContext&amp; dc) const
     #endif
     // ...
};
</PRE>
<P>In the implementation file, the definition, which includes a code body, might
look like this:</P>
<P>
<PRE>#include &quot;cnewclass.h&quot;
#ifdef _DEBUG
void CNewClass::Dump( CDumpContext&amp; dc ) const
{
     CObject::Dump( dc );     // Dump parent;
     // perhaps dump individual members, works like cout
     dc &lt;&lt; &quot;member: &quot; &lt;&lt; /* member here */ endl;
}
#endif
</PRE>
<P>As you see in the code for the Dump() function, writing the code is much like
writing to standard output with the cout object or serializing to an archive. You
are provided with a CDumpContext object called dc, and you send text and values to
that object with the &lt;&lt; operator. If this is unfamiliar to you, read Chapter
7, &quot;Persistence and File I/O.&quot;</P>
<P>
<H3><A NAME="Heading11"></A>An Example Using CDumpContext, CFile, and axfDump</H3>
<P>The sample application in this section uses the MFC debugging class CDumpContext
and the global axfDump object. The debug window output from this demo and the output
CFile code are in Listing D.1. To run this application yourself, create a console
application as described in Chapter 28, &quot;Future Explorations,&quot; and create
an empty C++ source file called Dump.cpp. Enter this code, build, and run a debug
version of the project.</P>
<P>When linking a debug version of this product, if you receive error messages that
refer to _beginthreadex and _endthreadex, you need to change some settings. By default,
console applications are single-threaded, but MFC is multithreaded. By including
afx.h and bringing in MFC, this application is making itself incompatible with the
single-threaded default. To fix this, choose Project Settings and click the C/C++
tab. From the drop-down box at the top of the dialog box, choose Code Generation.
In the drop-down box labeled Use Runtime Library, choose Debug Multithreaded. (Figure
D.15 shows the completed dialog.) Click OK and rebuild the project. You should usually
change the settings for release as well, but because the calls to Dump() aren't surrounded
by tests of _DEBUG, this code won't compile a release version anyway.</P>
<P>
<H4>Listing D.1&#160;&#160;Dump.Cpp--Demonstrating the MFC Debugging Class CDumpContext
and the Output CFile Code</H4>
<PRE>#include &lt;afx.h&gt;
// _DEBUG defined for debug build
class CPeople : public CObject
{
public:
    // constructor
        CPeople( const char * name );
        // destructor
        virtual ~CPeople();
        #ifdef _DEBUG
            virtual void Dump(CDumpContext&amp; dc) const;
        #endif
    private:
        CString * person;
    };
    // constructor
    CPeople::CPeople( const char * name) : person( new CString(name)) {};
    // destructor
    CPeople::~CPeople(){ delete person; }
#ifdef _DEBUG
    void CPeople::Dump( CDumpContext&amp; dc ) const
    {
        CObject::Dump(dc);
        dc &lt;&lt; person-&gt;GetBuffer( person-&gt;GetLength() + 1);
    }
#endif
int main()
    {
        CPeople person1(&quot;Kate Gregory&quot;);
        CPeople person2(&quot;Clayton Walnum&quot;);
        CPeople person3(&quot;Paul Kimmel&quot;);
        // Use existing afxDump with virtual dump member function
        person1.Dump( afxDump );
        // Instantiate a CFile object
        CFile dumpFile(&quot;dumpout.txt&quot;, CFile::modeCreate | 
            CFile::modeWrite);
        if( !dumpFile )
        {
            afxDump &lt;&lt; &quot;File open failed.&quot;;
        }
        else
        {
            // Dump with other CDumpContext
            CDumpContext context(&amp;dumpFile);
            person2.Dump(context);
        }
        return 0;
</PRE>
<PRE>    }
</PRE>
<P>This single file contains a class definition, all the code for the class member
functions, and a main() function to run as a console application. Each of these parts
of the file is explained in the next few paragraphs. The class is a simple wrapper
around a CString pointer, which allocates the CString with new in the constructor
and deletes it in the destructor. It's so simple that it's actually useless for anything
other than demonstrating the Dump() function.</P>
<P>First, the &lt;afx.h&gt; header file is included, which contains the CObject class
definition and provides access to afxDump.</P>
<P>Next, this code defines the class CPeople derived from CObject. Notice the placement
of the override of the virtual Dump() method and the conditional compiler wrap. (Any
calls to Dump() should be wrapped in the same way, or that code will not compile
in a release build.)</P>
<P>Following the constructor and destructor comes the code for CPeople::Dump(). Notice
how it, too, is wrapped in conditional compiler directives. The call to CObject::Dump()
takes advantage of the work done by the MFC programmers, dumping information all
objects keep.</P>
<P>Finally, the main() function exercises this little class. It creates three instances
of the CPeople class and dumps the first one.</P>
<P>For the second CPeople object, this code creates and opens a CFile object by passing
a text string to the constructor. If the open succeeds, it creates a CDumpContextObject
from the file and passes this context to Dump instead of the usual afxDump().</P>
<P>If you run this program, you'll see output like that in Figure D.14. The file
dumpout.txt will contain these lines:</P>
<P>
<PRE>a CObject at $71FDDC
Clayton Walnum
</PRE>
<P><A HREF="javascript:popUp('xduvc14.gif')"><B>FIG. D.14</B></A><B> </B><I>Using
the afxDump context sends your output to the Debug window.</I></P>
<P>The first line of the output, to both the debug window and the file, came from
CObject::Dump() and gives you the object type and the address. The second line is
from your own code and is simply the CString kept within each CPeople.</P>
<P><A HREF="javascript:popUp('xduvc15.gif')"><B>FIG. D.15</B></A><B> </B><I>To use
MFC in a console application, change to the multithreaded runtime library.</I></P>
<P>Now that you've seen the basic tools of debugging in action, you're ready to put
them to work in your own applications. You'll find errors quickly, understand other
people's code, and see with your own eyes just how message-routing and other behind-the-scenes
magic really occur. If you find yourself enjoying debugging, don't worry--no one
else has to know!</P>
<H1></H1>
<CENTER>
<P>
<HR>
<A HREF="../apc/apc.htm"><IMG SRC="../button/previous.gif" WIDTH="128" HEIGHT="28"
ALIGN="BOTTOM" ALT="Previous chapter" BORDER="0"></A><A HREF="../ape/ape.htm"><IMG
SRC="../button/next.gif" WIDTH="128" HEIGHT="28" ALIGN="BOTTOM" ALT="Next chapter"
BORDER="0"></A><A HREF="../index.htm"><IMG SRC="../button/contents.gif" WIDTH="128"
HEIGHT="28" ALIGN="BOTTOM" ALT="Contents" BORDER="0"></A> <BR>
</P>

<P>&#169; <A HREF="../copy.htm">Copyright</A>, Macmillan Computer Publishing. All
rights reserved.
</CENTER>


</BODY>

</HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -