1. 程式人生 > >MFC 利用控制檯輸出除錯資訊(轉)

MFC 利用控制檯輸出除錯資訊(轉)

  在MFC程式中,可以使用TRACE巨集或者OutPutDebugString()函式輸出除錯資訊,TRACE巨集可以在除錯時像Output視窗輸出除錯資訊,OutPutDebugString()函式的輸出則可以用DebugView捕獲(DebugView也可以捕獲TRACE巨集的輸出,其官網在 這裡 ,具體使用請參考官網的說明),另外也可以通過AfxMessageBox()或者MessageBox()彈窗輸出,但畢竟太多繁瑣,每彈出一個視窗便要確認一次。引入日誌庫也是個好辦法,同時也可以通過分析日誌檔案瞭解應用程式的執行狀況,這是終極大殺器,我們還需要更輕量級的方法。

  控制檯除錯資訊輸出,即是在程式執行時,開啟一個Console視窗,將自己編寫的除錯資訊輸出到Console中,便於瞭解當前程式的執行狀況,幫助除錯,僅需簡單幾行程式碼即可搞定,不需要動用日誌庫這樣重量級的東東。

  本文以一個基於對話方塊的MFC程式為例,看看如何給應用程式加上控制檯輸出。

  1、例項工程名為Demo,在CDemoDlg.cpp中加入標頭檔案 #include "conio.h" 

  2、在CDemoDlg::OnInitDialog() {...}函式中加入AllocConsole();

  3、在需要輸出除錯資訊的地方,呼叫 cprintf() (在VS2005後應該用 _cprintf 代替,下文有說明)函式輸出資訊,用法同 printf() 函式類似;

  4、若需要關閉控制檯輸出,呼叫 FreeConsole();

在MSDN(MSDN Library Visual Studio 2008 SP1)中,AllocConsole()函式的原型為:

?
1 BOOL WINAPI AllocConsole(void);

  Return Value:

  If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

  Remarks:

  A process can be associated with only one console, so the AllocConsole

 function fails if the calling process already has a console. A process can use the FreeConsole function to detach itself from its current console, then it can call AllocConsole to create a new console or AttachConsole to attach to another console.

  If the calling process creates a child process, the child inherits the new console.

  AllocConsole initializes standard input, standard output, and standard error handles for the new console. The standard input handle is a handle to the console's input buffer, and the standard output and standard error handles are handles to the console's screen buffer. To retrieve these handles, use the GetStdHandle function.

  This function is primarily used by graphical user interface (GUI) application to create a console window. GUI applications are initialized without a console. Console applications are initialized with a console, unless they are created as detached processes (by calling the CreateProcess function with the DETACHED_PROCESS flag).

  MSDN中對於cprintf()的解釋,很簡短,只有一句話

  "This POSIX function is deprecated beginning in Visual C++ 2005. Use the ISO C++ conformant _cprintf or security-enhanced _cprintf_s instead."

  從VS2005開始,用 _cprintf 或 _cprintf_s 函式代替 cprintf ,So then,再來看下 _cprintf 的解釋,更加簡短了:Formats and prints to the console.

按照我的理解,就是 _cprintf 是像控制檯輸出格式化資訊,c 即是console的意思,而 printf 是標準輸出,不一定是控制檯視窗了。

http://blog.csdn.net/liuxizhen2009/article/details/8557888

http://www.cnblogs.com/zhaomzs/archive/2013/01/23/2873764.html