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?
是否有一种跨平台的方法来包装fprintf()所以我可以使用简单的日志记录功能将日志转储到文件或控制台,并使用简单的C printf()样式格式字符串和参数列表?
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:
这适用于GCC,如果我删除了领先的##,它可以在GCC和Visual Studio 2005中运行(是的,我必须在VS2005到2015年使用它),但它在2012年之前的Visual Studio版本中失败了实际上有一个变量参数列表,即:
logIssue("Problem with test#%d.", iTestID); // Succeeds
logIssue("General problem."); // Fails
I've read into this issue at length, including the following:
我已经详细阅读了这个问题,包括以下内容:
- Standard alternative to GCC's ##VA_ARGS trick?
- MSVC doesn't expand VA_ARGS correctly
- the problem about different treatment to VA_ARGS when using VS 2008 and GCC
GCC ## VA_ARGS技巧的标准替代品?
MSVC无法正确扩展VA_ARGS
使用VS 2008和GCC时对VA_ARGS的不同处理问题
These offer potential solutions, but I can't seem to integrate them with my fprintf()
macro.
这些提供了潜在的解决方案,但我似乎无法将它们与我的fprintf()宏集成。
Is there any straightforward way to have this wrapper macro work in Linux (GCC) and Windows (MSVC 2005 and onward) via macro tricks?
有没有直接的方法让这个包装器宏通过宏技巧在Linux(GCC)和Windows(MSVC 2005及以后版本)中工作?
Thank you.
1 个解决方案
#1
3
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:
这适用于两个调用,并且符合C99:
logIssue("Problem with test#%d.", iTestID);
logIssue("General problem.");
#1
3
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:
这适用于两个调用,并且符合C99:
logIssue("Problem with test#%d.", iTestID);
logIssue("General problem.");