我的调试输出 _TRACE 第三版

在第二版的基础上增加了非法检查功能  另外使用_WINDOWS宏来区分控制台和Windows程序



#include <stdlib.h>
#include <stdio.h>
#include <crtdbg.h> 
class __CTrace
{
#ifdef _WINDOWS
  #define dbgOutputA(str) OutputDebugStringA(str)
  #define dbgOutputW(str) OutputDebugStringW(str)
#else
  #define dbgOutputA(str) printf_s("%s", str)
  #define dbgOutputW(str) wprintf_s(L"%s", str)
#endif

#if (defined UNICODE || defined _UNICODE)
  #define dbgOutput dbgOutputW
#else //ASNI
  #define dbgOutput dbgOutputA
#endif

  LPCTSTR szFileName;
  int fileLine; 
  _invalid_parameter_handler oldHandler;
  int oldCrtAssertMode;

  static void TraceInvalidParameterHandler(const wchar_t* expression,
    const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved)
  {
    wchar_t wchBuffer[1024];
    swprintf_s(wchBuffer, 
      L"Invalid trace parameter detected in function %s, file %s(%d), Expression: %s\r\n",
      function, file, line, expression);
    dbgOutputW(wchBuffer);
  }
  
public:
  __CTrace(LPCTSTR szFile, int nLine)
  {
    szFileName = szFile;
    fileLine = nLine;

    //Disable invalid format assert error
    oldHandler = _set_invalid_parameter_handler(TraceInvalidParameterHandler);
    // Disable the message box for assertions.
    oldCrtAssertMode = _CrtSetReportMode(_CRT_ASSERT, 0);
  }

  virtual ~__CTrace()
  {
    _CrtSetReportMode(_CRT_ASSERT, oldCrtAssertMode);
    _set_invalid_parameter_handler(oldHandler);
  }

  void __cdecl operator()(LPCTSTR format, ...) const
  {
    int ivsp, iLen = 0;
    TCHAR szDbgOut[4096];
    
    iLen += _stprintf_s(szDbgOut + iLen, _countof(szDbgOut) - iLen, 
      _T("%s(%d) "), szFileName, fileLine);
    
    va_list arg; 
    va_start(arg, format);
    ivsp = _vstprintf_s(szDbgOut + iLen, _countof(szDbgOut) - iLen,  format, arg);
    va_end(arg);
    if(ivsp < 0  && errno == EINVAL)
    {
      _tcscpy_s(szDbgOut + iLen, _countof(szDbgOut) - iLen, 
        _T("Invalid trace parameter detected\r\n"));
    }

    dbgOutput(szDbgOut);
  }
};

#ifdef _DEBUG
  #define _TRACE __CTrace(_T(__FILE__), __LINE__)
#else
  #define _TRACE(...)  __noop
#endif

测试代码

  _TRACE(_T("myTrace %d\n"), 10);
  _TRACE(_T("%\n"), 10);


调试输出

d:\vc_project\dlg3\dlg3\dlg3.cpp(106) myTrace 10
Invalid trace parameter detected in function _woutput_s_l, file f:\dd\vctools\crt_bld\self_x86\crt\src\output.c(1120), Expression: ("Incorrect format specifier", 0)
d:\vc_project\dlg3\dlg3\dlg3.cpp(107) Invalid trace parameter detected



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值