C语言,调试必备的DEBUG宏定义

1.

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

//仅仅是打印函数名字替换 DEBUG <--> printf
#define DEBUG(format, ...) printf(format, ##__VA_ARGS__)

//替换打印函数,在打印出来的内容加上前缀
#define XFUNC_PRINT(format, arg...) printf("XFUNC: " format "", ##arg)

//名字替换,并在打印出来的内容加上前缀,同时加入定位的功能。
#define TRC_P(fmt, args...) fprintf(stderr,"  TRC_P(%s:%d):\t" fmt, __func__, __LINE__, ##args)

//名字替换,并在打印出来的内容加上前缀,同时加入定位的功能,并让打印的前缀具备特殊颜色(\033[1;32m  \033[0m这些表示颜色,\t一定程度上使屏幕输出对齐)
#define TRC_PG(fmt, args...) fprintf(stderr, "\033[1;32m  TRC_PG(%s:%d):\t\033[0m" fmt, __func__, __LINE__, ## args)

//名字替换,并在打印出来的内容加上前缀,同时加入定位的功能,并让打印的前缀具备特殊颜色
#define TRC_PR(fmt, args...) fprintf(stderr, "\033[1;31m  TRC_PR(%s:%d):\t\033[0m" fmt, __func__, __LINE__, ## args)

int main(void)
{
    int i= 0;

    DEBUG("hello,%d\n",i++);
    XFUNC_PRINT("hello,%d\n",i++);
    TRC_P("hello,%d\n",i++);
    TRC_PG("hello,%d\n",i++);
    TRC_PR("hello,%d\n",i++);

    return 0;
}

/*
[root@localhost jz2440]# gcc test.c ;./a.out 
hello,0
XFUNC: hello,1
  TRC_P(main:27):       hello,2
  TRC_PG(main:28):      hello,3  ----这里前缀是绿色的
  TRC_PR(main:29):      hello,4  ----这里前缀是红色的
*/

2.

#include <stdio.h>
//以十六进制打印一个数val的值,输出格式为val=0x...
#define HEX_PI(VAL)\
do{\
    printf(#VAL"=%#x,fuc:%s,line:%d\n", VAL, __FUNCTION__, __LINE__);\
}while(0)
//以十进制打印一个数val的值,输出格式为val=...
#define DEC_PI(VAL)\
do{\
    printf(#VAL"=%#d,fuc:%s,line:%d\n", VAL, __FUNCTION__, __LINE__);\
}while(0)
    
void main(void)
{
    int i = 123;
    int j = 123;
    HEX_PI(i);
    HEX_PI(j);    
    
    DEC_PI(i);
    DEC_PI(j);
}


//i=0x7b,fuc:main,line:17
//j=0x7b,fuc:main,line:18
//i=123,fuc:main,line:20
//j=123,fuc:main,line:21

 

3. 配合宏开关在编译前静态指定打印等级

#if CUR_PLEVEL > 5

#define TRC_PR(fmt, args...) fprintf(stderr," TRC_P(%s:%d):\t" fmt, __func__, __LINE__, ##args)

#endif

 

4. 想要动态地指定打印等级,要使用类似内核打印的宏定义

见另一篇文章: 似linux内核的分等级DEBUG宏(打印宏)http://www.cnblogs.com/mylinux/p/5906576.html

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值