简体   繁体   中英

Help with my printf function

For debugging purposes I would like to have a printf_debug function that would function just like the standard printf function, but would only print if a #DEFINE DEBUG was true

I know I have to use varagrs (...) but I have no idea how to actually achieve that.

Thanks in advance.

Easier to just #define it away. Something like this:

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

I don't what exactly you want to achieve. In case you want a code block to execute only if DEBUG is defined, use the preprocessor directive #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 */
}

You don't need to use vargs, macros will work. Here is an example, which will prints function and line number as well:

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

The ##args here will be replaced by the args list, which likes what vargs does in function call.

You have to use the va_arg macros, they are used to access the variadic variables. A useful link: http://www.cppreference.com/wiki/c/other/va_arg . The reference is for C++, but these macros can be used in C as well.

In your actual implementation you place the code using the variadic variables in a #ifdef block.

But if you're looking for a regular call to printf, dependent on DEBUG a simple #define acting as an alias will do.

C99 compiler only!

#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;
}

to be honest varidic macros are not needed you could just easily write it as this:

#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;
}

Thinking about it, debug information should go to stderr so as not to interfer with stdout, so this one should be favoured:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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