你如何创建一个调试只有采用可变参数列表的功能?如printf() [英] How do you create a debug only function that takes a variable argument list? Like printf()

查看:119
本文介绍了你如何创建一个调试只有采用可变参数列表的功能?如printf()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想作一个调试日志记录功能,用相同的参数为的printf 。而是一个可由$ P $对处理器被移除期间优化构建

I'd like to make a debug logging function with the same parameters as printf. But one that can be removed by the pre-processor during optimized builds.

例如:

Debug_Print("Warning: value %d > 3!\n", value);

我看着复杂的宏,但这些并非适用于所有平台。 GCC 支持他们, MSVC 没有。​​

推荐答案

我仍然这样做旧的方式,通过定义一个宏(X跟踪,下同)其关联到一个无操作或具有可变参数的函数调用名单。在内部,调用vsnprintf这样可以保持与printf语法:

I still do it the old way, by defining a macro (XTRACE, below) which correlates to either a no-op or a function call with a variable argument list. Internally, call vsnprintf so you can keep the printf syntax:

#include <stdio.h>

void XTrace0(LPCTSTR lpszText)
{
   ::OutputDebugString(lpszText);
}

void XTrace(LPCTSTR lpszFormat, ...)
{
    va_list args;
    va_start(args, lpszFormat);
    int nBuf;
    TCHAR szBuffer[512]; // get rid of this hard-coded buffer
    nBuf = _vsnprintf(szBuffer, 511, lpszFormat, args);
    ::OutputDebugString(szBuffer);
    va_end(args);
}

然后一个典型的#ifdef开关:

Then a typical #ifdef switch:

#ifdef _DEBUG
#define XTRACE XTrace
#else
#define XTRACE
#endif

好了,可以清理了不少,但它的基本思想。

Well that can be cleaned up quite a bit but it's the basic idea.

这篇关于你如何创建一个调试只有采用可变参数列表的功能?如printf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆