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宏(打印宏)