自定义的用于C语言的TRACE和DUMP

关键词:C语言 调试
1.C语言调试时,可能需要用printf打印调试信息,但是又不希望在release版本中起作用。
    a)最不可取的作法,先写着,然后Release时注释掉。
    b)在打印调试信息的地方
          #ifdef _DEBUG
             printf(...) ;
         #endif
    c)比较好的做法,使用宏定义
         #ifdef _DEBUG
         #define TRACE printf
         #else
         #define TRACE 1?(void)0:printf
         #endif
2.调试时,可能还想打印出一个变量的内存二进制值(用十六进制表示),这时可以定义一个dump函数,然后对这个函数使用上面的宏。
        #ifdef _DEBUG
         #define DUMP dump
         #else
         #define DUMP 1?(void)0:dump
         #endif

        void dump(unsigned char *p, size_t len)
        {
             
        }
完整的代码如下:
debug.h
下载: debug.h
  1. /*
  2. *debug.h
  3. *by Albert Song(http://www.albertsong.com)
  4. */
  5.  
  6. #ifndef _DEBUG_H_
  7. #define _DEBUG_H_
  8.  
  9. #include <stdio.h>
  10.  
  11. #ifdef _DEBUG
  12. #define TRACE printf
  13. #define DUMP dump
  14. #else
  15. #define TRACE 1?(void)0:printf
  16. #define DUMP 1?(void)0:dump
  17. #endif
  18.  
  19. #define BYTE_IN_ROW 40
  20.  
  21. #ifdef __cplusplus
  22. extern "C" {
  23. #endif
  24.  
  25. void dump(unsigned char *p, size_t len)
  26. {
  27.     unsigned int i=0;
  28.     for(i=0;i<len;i++)
  29.     {
  30.         printf("%02X ",*p++);
  31.         if((i+1)%BYTE_IN_ROW==0) printf("\n");
  32.  
  33.     }
  34.     printf("\n");
  35. }
  36.  
  37. #ifdef __cplusplus
  38. }
  39. #endif
  40.  
  41.  
  42. #endif //_DEBUG_H

TestDebug.c
下载: TestDebug.c
  1. /*
  2. *TestDebug.c
  3. *by Albert Song(http://www.albertsong.com)
  4. */
  5.  
  6. #include <string.h>
  7.  
  8. #include "debug.h"
  9.  
  10.  
  11. int main(void)
  12. {
  13.     int a=256;
  14.     char b[]="JKLMN";
  15.     char c;
  16.  
  17.     TRACE("info a=%d,b=%s\n",a,b);
  18.     TRACE("info b2=%.*s\n",2,b);
  19.     DUMP((unsigned char*)&a,sizeof(a));
  20.     DUMP((unsigned char*)b,strlen(b));
  21.  
  22.     //end
  23.     printf("Press any key to continue...");
  24.     scanf("%c",&c);
  25.     return 0;
  26. }

     
参考链接:
http://www.hcn.zaq.ne.jp/no-ji/lib/assert.txt
http://oshiete1.goo.ne.jp/qa100283.html
http://zh.wikipedia.org/wiki/ASCII
标签: C语言
评论: 0 | 引用: 0 | 阅读: 441
发表评论
昵 称: (必须)
密 码: (未注册用户可不填)
网 址: 邮 箱:
验证码: 验证码图片 选 项:
头 像:
内 容: