C 语言可变参数宏(用于调试)

测试代码:

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>   

#define __DEBUG__
#ifdef __DEBUG__

#define DEBUG(format, ...) printf("文件:"__FILE__ "\n行号:%d\n输出:"format"\n", __LINE__, ##__VA_ARGS__)

#else
#define DEBUG(format, ...)
#endif

1
2
3
4
5
6
7
8
int main(int argc, char **argv) 
{
char str[] = "Hello World";
float a = 889.5;
DEBUG("A ha, check me: %s%.2f", str, a);

return 0;
}

运行测试输出结果:

1
2
3
4
文件:e:\cdoc\c 语言练习\c 语言练习\c_exercise.c
行号:15
输出:A ha, check me: Hello World889.50
请按任意键继续. . .

原始的测试行:

1
#define DEBUG(format,...) printf("File: "__FILE__"\nLine: %05d \n"format"\n", __LINE__, ##__VA_ARGS__)

%05d 输出占 5 格, 前面不足的, 补零. 如果 %5d, 占 5 格, 不足补空格.

format 参数名, 前后相同就行了, __VA_ARGS__是可变参数宏, 宏参数对应前面的三个点(省略号), ##的意思是,如果可变参数(format, 就是后面的%s)被忽略或为空,将使预处理器(preprocessor )去除掉它前面的那个逗号。   

__LINE__:在源代码中插入当前源代码行号;
__FILE__:在源文件中插入当前源文件名;

另外: ...只能放最后. 经测试, format 只能放第一个逗号前,且挨着逗号, ...和对应的_VA_ARGS_只能放在最后

也不用管多了, 就按照这个格式来就是了.


参考:
[1]: http://blog.csdn.net/hinyunsin/article/details/6546670
[2]: http://blog.csdn.net/jinzhilong580231/article/details/8774259
[3]: http://blog.csdn.net/hinyunsin/article/details/6546670
[4]: http://blog.chinaunix.net/uid-22878837-id-2110544.html

感谢支持!