C++ 输出代码所在的文件、行数以及函数名称

在输出调试信息的时候,经常会用到这几个宏。首先看一段示例代码,再来介绍这几个宏:

[cpp] view plain copy
 
 print?在CODE上查看代码片派生到我的代码片
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3.   
  4. //替换函数名  
  5. #ifndef _DEBUG  
  6. #define LOGFUNC(...) ((void)0)  
  7. #else  
  8. #define LOGFUNC(...) (printf(__VA_ARGS__))  
  9. #endif  
  10.   
  11. //宏前面加上##的作用在于:当可变参数的个数为0时,这里的## 起到把前面多余的","去掉的作用  
  12. #define DEBUG_INFO(format, ...) printf("File:%s, Line:%d, Function:%s, %s",   
  13.     __FILE__, __LINE__ , __FUNCTION__, ##__VA_ARGS__);  
  14.   
  15. void show_debug_info()  
  16. {  
  17.     DEBUG_INFO("%s", "hello world");  
  18. }  
  19.   
  20. int main()  
  21. {  
  22.     LOGFUNC("%s ", "this is test");  
  23.     show_debug_info();  
  24.     system("pause");  
  25.     return 0;  
  26. }  


1) __VA_ARGS__ 是一个可变参数的宏,总体来说就是将左边宏中 ... 的内容原样抄写在右边 __VA_ARGS__ 所在的位置。

2) __FILE__ 宏在预编译时会替换成当前的源文件名

3) __LINE__ 宏在预编译时会替换成当前的行号

4) __FUNCTION__ 宏在预编译时会替换成当前的函数名称

5)类似的宏还有__DATE__, __TIME__,__STDC__, __TIMESTAMP__等,可以当作一个变量来使用。

关于宏##的有关解析,在另一篇文章有介绍:http://www.cnblogs.com/fnlingnzb-learner/p/6823575.html

上述代码中定义的DEBUG_INFO宏,就是输出控制台的调试信息。比如说,我们通过 OutputDebugString 输出调试信息这样写:

[cpp] view plain copy
 
 print?在CODE上查看代码片派生到我的代码片
  1. #ifdef _DEBUG  
  2. #define OUTPUT_DEBUGW(fmt, ...) PrintDebugStringW(_T(__FILE__),__LINE__, fmt, __VA_ARGS__)  
  3. #else  
  4. #define OUTPUT_DEBUGW ((void)0)  
  5. #endif  
  6.   
  7. void PrintDebugStringW(const wchar_t *file, int lineno, const wchar_t *pszFmt, ...)  
  8. {  
  9.     va_list vlArgs = NULL;  
  10.     va_start(vlArgs, pszFmt);  
  11.     size_t nLen = _vscwprintf(pszFmt, vlArgs) + 1;  
  12.     wchar_t *strBuffer = new wchar_t[nLen];  
  13.     _vsnwprintf_s(strBuffer, nLen, nLen, pszFmt, vlArgs);  
  14.     va_end(vlArgs);  
  15.     //OutputDebugStringW(strBuffer);  
  16.   
  17.     wchar_t buf[4096];  
  18.     swprintf_s(buf, 4096, L"%s<%d>: tid[%d] : %s ", file, lineno, GetCurrentThreadId(), strBuffer);  
  19.     OutputDebugStringW(buf);  
  20.     delete [] strBuffer;  
  21. }  
原文地址:https://www.cnblogs.com/fnlingnzb-learner/p/6823572.html