在后台程序运行出问题时,详尽的日志是抓错不可缺少的帮手,这里提供一个能自动记录日志触发点文件名、行号、函数名的方法,关键是利用C99新增的预处理标识符__VA_ARGS__
先介绍几个编译器内置的宏定义,这些宏定义不仅可以帮助我们完成跨平台的源码编写,灵活使用也可以巧妙地帮我们输出非常有用的调试信息。
ANSI C标准中有几个标准预定义宏(也是常用的):
__LINE__:在源代码中插入当前源代码行号;
__FILE__:在源文件中插入当前源文件名;
__DATE__:在源文件中插入当前的编译日期
__TIME__:在源文件中插入当前编译时间;
__STDC__:当要求程序严格遵循ANSI C标准时该标识被赋值为1;
__cplusplus:当编写C++程序时该标识符被定义。
代码:
- #define LOG(level, format, ...) /
- do { /
- fprintf(stderr, "[%s|%s@%s,%d] " format "/n", /
- level, __func__, __FILE__, __LINE__, ##__VA_ARGS__ ); /
- } while (0)
- int main()
- {
- LOG(LOG_DEBUG, "a=%d", 10);
- return 0;
- }
- 运行结果:
- [DEBUG|main@a.c,17] a=10

#define LOG(level, format, ...) /
do { /
fprintf(stderr, "[%s|%s@%s,%d] " format "/n", /
level, __func__, __FILE__, __LINE__, ##__VA_ARGS__ ); /
} while (0)
int main()
{
LOG(LOG_DEBUG, "a=%d", 10);
return 0;
}
运行结果:
[DEBUG|main@a.c,17] a=10
限制是format不能是变量,必须是常量字符串,如果要记录一个变量字符串,不能像printf那样printf(s)了,要LOG("DEBUG", "%s", s)。
另外还有一种:
- //============================================================================
- // Name : debug.cpp
- // Author : boyce
- // Version : 1.0
- // Copyright : pku
- // Description : Hello World in C++, Ansi-style
- //============================================================================
- #include <stdio.h>
- #define __DEBUG__
- #ifdef __DEBUG__
- #define DEBUG(format,...) printf("File: "__FILE__", Line: %05d: "format"\n", __LINE__, ##__VA_ARGS__)
- #else
- #define DEBUG(format,...)
- #endif
- int main(int argc, char **argv) {
- char str[]="Hello World";
- DEBUG("A ha, check me: %s",str);
- return 0;
- }
转自:http://blog.youkuaiyun.com/shanzhizi/article/details/8983768