0

I am trying to find the best way to exclude my debug strings from making it to my release build. Currently, I'm outputting debug strings via syslog, and I have the current setup in my debug.c file:

#ifdef DEBUG
void init_debug(void)
{
    openlog("MyAppName", LOG_PERROR, LOG_SYSLOG);
}
#else
void init_debug(void){}
#endif

#ifdef DEBUG
void debug(const char* format, ...)
{
    va_list args;
    va_start(args, format);
    vsyslog(LOG_DEBUG, format, args);
    va_end(args);
}
#else
void debug(const char* format, ...){}
#endif

So, you can see that the functions will be empty when I build the release version. However, when I call the function, I would do something like:

#include "debug.h"

int main(int argc, const char* argv[])
{
    init_debug();
    debug("Number of arguments: %d", argc);
}

However, this of course makes my strings appear in the release build as they're still htere. The easy solution is to do something like:

#include "debug.h"

int main(int argc, const char* argv[])
{
    init_debug();
#ifdef DEBUG
   debug("Number of arguments: %d", argc);
#endif
}

But that's incredibly verbose, and hard to read (especially when it's grouped up with real code).

Are there other, more elegant solutions?

  • What happens if you replace the empty debug functions with just empty preprocessor "functions" `#define debug(...)` ? (That's actually dangerous if you ever have side-effects in the parameters you pass to debug) – Mat Jan 17 '22 at 17:02
  • Consider the techniques described in [`#define` macro for debug printing in C?](https://stackoverflow.com/q/1644868/15168). You'd need to adapt them a little, but the emphasis would be on 'a little'. You hide the conditional code (`#ifdef DEBUG` / `#else` / `#endif`) inside the header. You invoke the functions unconditionally in the source, but the header controls whether they expand to operational code or not. – Jonathan Leffler Jan 17 '22 at 17:06
  • Maybe `#define NDEBUG` / `#include ` ... `assert((argc == 3) && "wrong number of arguments");` or similar – pmg Jan 17 '22 at 17:09
  • 1
    @Mat: debug code should be read-only code with no side-effects, precisely so that there is no problem if the code is removed. If the debugging code modifies what it operates on, it is no longer just debugging code. – Jonathan Leffler Jan 17 '22 at 17:10
  • @Mat that perfectly worked! If you want to add that as an answer, I'll accept it. Thank you! – Axel Persinger Jan 17 '22 at 17:13
  • Note the caveats documented in the "`#define` macro for debug printing in C" question before going with the 'empty preprocessor macros for non-debug builds'. Specifically, be aware that debug code easily gets out of sync with the surrounding code unless it is compiled frequently. – Jonathan Leffler Jan 17 '22 at 17:17

0 Answers0