在输出调试信息的时候,经常会用到这几个宏。首先看一段示例代码,再来介绍这几个宏: [cpp] - #include <stdlib.h>
- #include <stdio.h>
- //替换函数名
- #ifndef _DEBUG
- #define LOGFUNC(...) ((void)0)
- #else
- #define LOGFUNC(...) (printf(__VA_ARGS__))
- #endif
- //宏前面加上##的作用在于:当可变参数的个数为0时,这里的## 起到把前面多余的','去掉的作用
- #define DEBUG_INFO(format, ...) printf('File:%s, Line:%d, Function:%s, %s', \
- __FILE__, __LINE__ , __FUNCTION__, ##__VA_ARGS__);
void show_debug_info() - {
- DEBUG_INFO('%s', 'hello world');
- }
- int main()
- {
- LOGFUNC('%s\n', 'this is test');
- show_debug_info();
- system('pause');
return 0; - }
1) __VA_ARGS__ 是一个可变参数的宏,总体来说就是将左边宏中 ... 的内容原样抄写在右边 __VA_ARGS__ 所在的位置。 2) __FILE__ 宏在预编译时会替换成当前的源文件名 3) __LINE__ 宏在预编译时会替换成当前的行号 4) __FUNCTION__ 宏在预编译时会替换成当前的函数名称 5)类似的宏还有__DATE__, __TIME__,__STDC__, __TIMESTAMP__等,可以当作一个变量来使用。 关于宏##的有关解析,在另一篇文章有介绍: l 上述代码中定义的DEBUG_INFO宏,就是输出控制台的调试信息。比如说,我们通过 OutputDebugString 输出调试信息这样写: [cpp] - #ifdef _DEBUG
- #define OUTPUT_DEBUGW(fmt, ...) PrintDebugStringW(_T(__FILE__),__LINE__, fmt, __VA_ARGS__)
- #else
- #define OUTPUT_DEBUGW ((void)0)
- #endif
void PrintDebugStringW(const wchar_t *file, int lineno, const wchar_t *pszFmt, ...) - {
- va_list vlArgs = NULL;
- va_start(vlArgs, pszFmt);
- size_t nLen = _vscwprintf(pszFmt, vlArgs) + 1;
- wchar_t *strBuffer =
new wchar_t[nLen]; - _vsnwprintf_s(strBuffer, nLen, nLen, pszFmt, vlArgs);
- va_end(vlArgs);
- //OutputDebugStringW(strBuffer);
- wchar_t buf[4096];
- swprintf_s(buf, 4096, L'%s<%d>: tid[%d] :\t%s\n', file, lineno, GetCurrentThreadId(), strBuffer);
- OutputDebugStringW(buf);
delete [] strBuffer; - }
|