1

I'm trying to write an overhead-free logging macro in C.

My first idea is:

#define debug_print(...) \
  { \
    printf(_LOG_FMT, _LOG_ARGS); \
    printf(__VA_ARGS__); \
    printf("\n"); \
  }

But this has the problem that I have to call printf three times (overhead).

My second idea is:

#define _LOGFUNCTION(LEVEL, message, ...) \
    printf(_LOG_FMT message "\n", _LOG_ARGS, __VA_ARGS__)

But now I can't pass it a simple string to log. It'll complain about zero arguments in VA_ARGS.

Is there a way to fix both of these problems?

Thanks a ton for your help!

James Pinkerton
  • 161
  • 2
  • 14
  • 1
    Unrelated to your problem, but don't make up your own symbol names starting with an underscore and an upper-case letter (like for example `_LOGFUNCTION`, and more). Such names and symbols are reserved for the compiler and standard library implementation everywhere. – Some programmer dude Nov 02 '18 at 01:16
  • 2
    As for your problem, it's a known problem and the solution depends on your compiler. See e.g. [Standard alternative to GCC's ##__VA_ARGS__ trick?](https://stackoverflow.com/questions/5588855/standard-alternative-to-gccs-va-args-trick) for more information (and how to solve it, but note that for a non-GCC solution it's complex and non-trivial). – Some programmer dude Nov 02 '18 at 01:19
  • What's the recommended naming for a private variable? Is __LOGFUNCTION OK? – James Pinkerton Nov 02 '18 at 02:00
  • No, leading double-underscore is *also* reserved. You should generally not have leading underscore at all. – Some programmer dude Nov 02 '18 at 03:01

1 Answers1

1

Found the answer form the comment above!

#define BAR_HELPER(fmt, ...) printf(fmt "\n%s", __VA_ARGS__)
#define BAR(...) BAR_HELPER(__VA_ARGS__, "")

https://stackoverflow.com/a/8673872/5531233

Thanks again Some programmer dude!

James Pinkerton
  • 161
  • 2
  • 14