2

Is there a cross-platform approach to wrapping fprintf() so I that I can have a simple logging function for dumping logs to either files or the console, and utilizes a simple C printf() style format string and arguments list?

Right now, I'm doing something like so:

#define logIssue(fmt, ...) do { \
    fprintf(stderr, "MY_PREFIX:%s:%s:%d > " fmt "\n", __FUNCTION__, __FILE__, __LINE__, ##__VA_ARGS__); \
} while(0);

This works in GCC, and if I remove the leading ##, it works in GCC and Visual Studio 2005 (yes, I have to have this working on VS2005 through 2015), but it fails in Visual Studio versions prior to 2012 when I don't actually have a variable arguments list, ie:

logIssue("Problem with test#%d.", iTestID); // Succeeds
logIssue("General problem."); // Fails

I've read into this issue at length, including the following:

These offer potential solutions, but I can't seem to integrate them with my fprintf() macro.

Is there any straightforward way to have this wrapper macro work in Linux (GCC) and Windows (MSVC 2005 and onward) via macro tricks?

Thank you.

Community
  • 1
  • 1
Cloud
  • 18,753
  • 15
  • 79
  • 153

1 Answers1

4

There is no need for extensions:

#define logIssue(...) do {      
    fprintf(stderr, "MY_PREFIX:%s:%s:%d > ", __func__, __FILE__, __LINE__);
    fprintf(stderr, __VA_ARGS__ );
    fputs( "", stderr);
} while(0)

This works with both calls, and is C99 compliant:

logIssue("Problem with test#%d.", iTestID);
logIssue("General problem.");
2501
  • 25,460
  • 4
  • 47
  • 87
  • Thank you. I swapped the final `fputs` call with `fprintf(stderr, "\n")` and I'm all set. :) – Cloud Feb 02 '16 at 19:35