1. assert 函式

一般在做 trace 時,似乎比較少人用到 assert,assert 裡面放的判斷是,如果「不成立的話」,程式便不會繼續執行下去。以下述程式碼而言

  

#include <stdio.h>
#include <assert.h>
int main()
{
    int a=10, b=0;
    assert(!(b==0));
    printf("%d\n", a/b);
    return 0;
}

 

執行時將出現以下視窗 

DebugAssert (2).png    

console 那裡結果如下

Assertion failed: !(b==0), file d:\vctest\main.c, line 6

但這種方式,是不論為 release mode 或 debug mode,都會顯示此訊息。

一些書之 tips 裡,會提到,在做 release 時,將相關 debug 函式全都拿掉會是較好的做法。

意思是,當程式 release 給 client 時,所有 assert 都拿掉會較佳。

如此一來,debug 完,到時又把 assert 全拿掉又顯得費時,於是用一些條件式鍽譯技巧,

進行轉換。

 


 

 

2. 自定義 __degug.c , __debug.h

 

 

再加入

/* filename : __debug.h */

#ifndef __DEBUG_H__
#define __DEBUG_H__

#ifdef _DEBUG

void _trace(char *fmt, ...);

#define ASSERT(x) {if(!(x)) _asm{int 0x03}}
#define VERIFY(x) {if(!(x)) _asm{int 0x03}} 

#else
#define ASSERT(x)
#define VERIFY(x) x
#endif

#ifdef _DEBUG
#define TRACE _trace

#else
inline void _trace(LPCTSTR fmt, ...) { }
#define TRACE 1 ? (void)0 : _trace
#endif

#endif // __DEBUG_H__

 

/* filename : __debug.c */

#ifdef _DEBUG

#include <stdio.h>
#include <stdarg.h>
#include <windows.h>

void _trace(char *fmt, ...)
{
    char out[1024];
    va_list body;
    va_start(body, fmt);
    vsprintf(out, fmt, body);
    va_end(body); 
    OutputDebugString(out);
}
#endif

 

直接拿一個測試程式碼出來

 

#include <stdio.h>
#include "__debug.h"
int main()
{
    int a=10, b=0;
    ASSERT(!(b==0));
    printf("%d\n", a/b);
    return 0;
}

 

執行結果與上述相仿

DebugAssert (4).png

但這支測試程式碼之 ASSERT ,只在「偵錯」時有作用,在發佈出去「執行」時將不具作用。 

 


 

3. TRACE

  

上述 __debug.h 裡面還提到了 TRACE,一般新手在做 trace 時,

會以 printf 方式輸出到 console 視窗上面去,

這裡的 TRACE 則是直接將結果輸出到 IDE 裡的「輸出」視窗裡面去。

  

#include <stdio.h>
#include "__debug.h"

int main()
{
    int x=0, sum=0;
    for(x=0; x<=10; ++x) {
        sum+=x;
        TRACE("x=%d, sum=%d\n", x, sum);
    }
    return 0;
}

 

輸出結果在 console 視窗看不到,只會在 IDE 裡之「輸出視窗」看到結果

  

DebugTrace (3).png  

 

arrow
arrow
    全站熱搜

    edisonx 發表在 痞客邦 留言(3) 人氣()