繁体   English   中英

帮助我的printf功能

[英]Help with my printf function

出于调试目的,我想有一个printf_debug函数,它的功能就像标准的printf函数一样,但只有在#DEFINE DEBUG为真时才会打印

我知道我必须使用varagrs(...),但我不知道如何实现它。

提前致谢。

更容易#define它。 像这样的东西:

#ifdef DEBUG
#define printf_debug printf
#else
#define printf_debug while(0)printf
#endif

我不知道你想要达到的目标。 如果您只想在定义DEBUG执行代码块,请使用预处理器指令#ifdef

#include <stdio.h>
#include <stdarg.h>
#define DEBUG

void printf_debug(const char *format, ...) {
  #ifdef DEBUG
  va_list args;
  va_start(args, format);
  vprintf(format, args);
  va_end(args);
  #endif /* DEBUG */
}

您不需要使用vargs,宏将起作用。 这是一个例子,它也会打印功能和行号:

#ifdef DEBUG
#define printf_debug(fmt, args...) printf("%s[%d]: "fmt, __FUNCTION__, __LINE__, ##args)
#else
#define printf_debug(fmt, args...)
#endif

这里的## args将被args列表替换,它类似于vargs在函数调用中的作用。

您必须使用va_arg宏,它们用于访问可变参数变量。 一个有用的链接: http//www.cppreference.com/wiki/c/other/va_arg 引用是针对C ++的,但这些宏也可以在C中使用。

在实际实现中,您可以使用#ifdef块中的可变参数放置代码。

但是,如果你正在寻找对printf的常规调用,依赖于DEBUG一个简单的#define可以作为别名。

仅限C99编译器!

#include <stdio.h>

#define DEBUG

#ifdef DEBUG
 #define debug(...) printf(__VA_ARGS__)
#else
 #define debug while(0)
#endif

int main(int argc, char *argv[])
{
    debug("Only shows when DEBUG is defined!\n");
    return 0;
}

说实话,不需要varidic宏你可以很容易地把它写成:

#include <stdio.h>

#define DEBUG

#ifdef DEBUG
 #define debug printf
#else
 #define debug while(0)
#endif

int main(int argc, char *argv[])
{
    debug("Only shows when DEBUG is defined!\n");
    return 0;
}

考虑到这一点,调试信息应该转到stderr以免干扰stdout,所以这个应该受到青睐:

#include <stdio.h>

#define DEBUG

#ifdef DEBUG
 #define debug(...) fprintf(stderr, __VA_ARGS__)
#else
 #define debug while(0)
#endif

int main(int argc, char *argv[])
{
    debug("Only shows when DEBUG is defined!\n");
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM