fprintf宏

最近在调试程序,使用printf函数和调试信息都不能在终端输出,所以使用比较笨的方法。将调试信息写到文件中,再查看文件。由于要多次使用fprintf函数,所以将其写成宏。

参考链接:

    http://www.cnblogs.com/alexshi/archive/2012/03/09/2388453.html

“…”表示零个或多个参数,后面使用__VA_ARGS__把参数传递给宏。当宏的调用展开时,实际的参数就传递给 fprintf()了。

将宏定义成一个函数,这样一来每次都会执行一次完成的操作,当在同一个函数内部多次使用同一个宏的时候,其中函数定义的局部变量不会和其他的函数冲突,如果不定义成函数的话,编译器就会报错。

debug.h

 1 #ifndef _DEBUG_H_
 2 #define _DEBUG_H_
 3 
 4 #define DEBUG(info,...) \
 5 {                       \
 6     FILE *fp;           \
 7     fp = fopen("log", "a+");\
 8     fprintf(fp, "%d,%s", \
 9             __LINE__, __func__);\
10     fprintf(fp,info,  __VA_ARGS__);\
11     fclose(fp);         \
12 }
13 
14 #endif

 

debug.c

1 #include <stdio.h>
2 #include "debug.h"
3 
4 int main()
5 {
6     DEBUG("hello\n");
7     return 0;
8 }

编译

gcc debug.c

出现如下问题

 

而将main函数中更改,增加一个参数。改为DEBUG("hello\n",123);

再次编译,编译通过,运行程序,查看生成的文件,已经将内容写到里面。

上网查阅,解决问题方法1,可变参数前面加上“##”,如果可变参数为空,那么“##”可以使编译器去掉前面的空格。

 1 #ifndef _DEBUG_H_
 2 #define _DEBUG_H_
 3 
 4 #define DEBUG(info,...) \
 5 {                       \
 6     FILE *fp;           \
 7     fp = fopen("log", "a+");\
 8     fprintf(fp, "%d,%s", \
 9             __LINE__, __func__);\
10     fprintf(fp,info, ## __VA_ARGS__);\
11     fclose(fp);         \
12 }
13 
14 #endif

当可变参为零,DEBUG("hello\n");编译通过。

解决方法2,更改宏如下所示,再次只打印一个字符串就,不会有问题。

 1 #ifndef _DEBUG_H_    
 2 #define _DEBUG_H_
 3 
 4 #define DEBUG(...) \
 5 {                       \
 6     FILE *fp;           \  
 7     fp = fopen("log", "a+");\
 8     fprintf(fp, "%d,%s", \
 9             __LINE__, __func__);\
10     fprintf(fp,__VA_ARGS__);\
11     fclose(fp);         \
12 }
13 
14 #endif

DEBUG("hello\n");编译通过

但是当可变参为零,即

DEBUG();

出现如下错误

 

posted @ 2015-09-07 23:50  SuperTao1024  阅读(472)  评论(0编辑  收藏  举报