首页 > C/C++开发工具专区 > VC技术 > 软件运行中输出数据到调试器
2006
07-02

软件运行中输出数据到调试器

我们知道,Window系统中有一种称为Debuger的工具,可以捕获应用程序输出的调试信息,这是由OutputDebugString函数实现的。为什么要有这样一种调试机制呢?有果必有因:当一个大型程序中存在着一个非常隐蔽的错误(所谓隐蔽,指的是我从运行过程中发现程序不正常,但是即使检查源代码,也很难发现何处存在错误),于是乎,我们在运行过程中添加一些输出语句,把中间结果或者程序状态输出出来,根据大量的结果来推测程序究竟出错在何处。这种情况是绝非程序断点能够搞定的,因为有时候你断无可断。由于我们输出的debug信息只能由debuger来接受,所以,即使程序发布之后,也无须去掉这些调试点,这样对以后排错也很有利。

闲言少叙,书归正传,来看看MSDN怎么说:

OutputDebugString
The OutputDebugString function sends a string to the debugger for display.

VOID OutputDebugString(
  LPCTSTR lpOutputString   // string to be displayed
);
Parameters
lpOutputString
[in] Pointer to the null-terminated string to be displayed.
Return Values
This function does not return a value.

Remarks
If the application has no debugger, the system debugger displays the string. If the application has no debugger and the system debugger is not active, OutputDebugString does nothing.

Requirements
  Windows NT/2000 or later: Requires Windows NT 3.1 or later.
  Windows 95/98/Me: Requires Windows 95 or later.
  Header: Declared in Winbase.h; include Windows.h.
  Library: Use Kernel32.lib.
  Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also
Basic Debugging Overview, Debugging Functions


写的很清楚了,就这么一个简单的函数而已。看看偶的示范代码吧:

#include “stdafx.h”
#include <windows.h>
#include <stdio.h>

void WINAPI DebugString(LPCSTR format, …)
{
va_list arglist;
char buffer[1024];

va_start (arglist,format);
vsprintf(buffer, format, arglist);
va_end (arglist);

strcat(buffer, “\n”);

OutputDebugString (buffer);
}

int main(int argc, char* argv[])
{
    int i;
printf(“Hello World!\n”);

    for (i=0; i<3; i++)
        DebugString( “Hello: %d”, i);
return 0;
}

是不是很简单?很方便?哈哈


留下一个回复