Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to be able to:

#define DEBUG_MODE 1

In order to turn on and off the printf() function calls inside all of my code. I know how to do this if it's set up as such:

if (DEBUG_MODE) printf("Hello World
");

However, that takes foresight and setting it up line by line.

Is there like a find and replace feature within macros that exists or can be built that can replace a given expression - like printf(); - with an empty string (or anything else you might want)?

#define DEBUG_MODE replace("printf(some_regular_expression);", ""); // where "" is empty string 

I'm sure this is not possible let alone with regex, but it doesn't hurt to ask.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
326 views
Welcome To Ask or Share your Answers For Others

1 Answer

While such a beast could be constructed by various shenanigans, I would strongly advise against it. It's not available in standard C and your IDE will hate you.

The typical method is defining something like debug_printf to be either printf (or more recently, fprintf(stderr, ...)) or a macro that expands to nothing.

I recommend tolerating the extra level of indirection and just going ahead and writing

#include <stdio.h>
#include <stdarg.h>
void debug_printf(const char *fmt, ...)
{
#if !defined(DEBUG)
    if (loglevel < LOG_DEBUG) return;
#endif
    va_list ap;
    va_start(ap, &fmt);
    vfprintf(stderr, fmt, ap);
}

where loglevel is a global variable and LOG_DEBUG is a macro and both are defined by you. The idea is you can turn these statements back on at runtime by passing a parameter to the program. This is often useful if a significant amount of work has been put into the debug prints.

Once having done so, you can use your IDE search & replace once to update all the call sites that your regex would have matched.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...