c语言输出文件名函数名和行号

来源:互联网 发布:pat考试 知乎 编辑:程序博客网 时间:2024/04/27 14:31

http://blog.csdn.net/shanzhizi/article/details/8983768

在后台程序运行出问题时,详尽的日志是抓错不可缺少的帮手,这里提供一个能自动记录日志触发点文件名、行号、函数名的方法,关键是利用C99新增的预处理标识符__VA_ARGS__

先介绍几个编译器内置的宏定义,这些宏定义不仅可以帮助我们完成跨平台的源码编写,灵活使用也可以巧妙地帮我们输出非常有用的调试信息。


ANSI C标准中有几个标准预定义宏(也是常用的):


__LINE__:在源代码中插入当前源代码行号;


__FILE__:在源文件中插入当前源文件名;


__DATE__:在源文件中插入当前的编译日期


__TIME__:在源文件中插入当前编译时间;


__STDC__:当要求程序严格遵循ANSI C标准时该标识被赋值为1;


__cplusplus:当编写C++程序时该标识符被定义。


代码:


[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #define LOG(level, format, ...) /  
  2.     do { /  
  3.         fprintf(stderr, "[%s|%s@%s,%d] " format "/n", /  
  4.             level, __func__, __FILE__, __LINE__, ##__VA_ARGS__ ); /  
  5.     } while (0)  
  6.   
  7. int main()  
  8. {  
  9.     LOG(LOG_DEBUG, "a=%d", 10);  
  10.     return 0;  
  11. }  
  12.   
  13. 运行结果:  
  14. [DEBUG|main@a.c,17] a=10  

限制是format不能是变量,必须是常量字符串,如果要记录一个变量字符串,不能像printf那样printf(s)了,要LOG("DEBUG", "%s", s)。


另外还有一种:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //============================================================================  
  2. // Name : debug.cpp  
  3. // Author : boyce  
  4. // Version : 1.0  
  5. // Copyright : pku  
  6. // Description : Hello World in C++, Ansi-style  
  7. //============================================================================  
  8. #include <stdio.h>  
  9.   
  10. #define __DEBUG__  
  11.   
  12. #ifdef __DEBUG__  
  13. #define DEBUG(format,...) printf("File: "__FILE__", Line: %05d: "format"\n", __LINE__, ##__VA_ARGS__)  
  14. #else  
  15. #define DEBUG(format,...)  
  16. #endif  
  17.   
  18. int main(int argc, char **argv) {  
  19.     char str[]="Hello World";  
  20.     DEBUG("A ha, check me: %s",str);  
  21.     return 0;  
  22. }  
0 0
原创粉丝点击