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\n", "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] :\t%s\n", file, lineno, GetCurrentThreadId(), strBuffer);  
  19.     OutputDebugStringW(buf);  
  20.     delete [] strBuffer;  
  21. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM