I want to implement a C/C++ variadic logging macro, which contains __FILE__ and __LINE__ information.
This is my simple implementation:
#include <stdio.h>
#define MYLOG(format, ...) printf("%s:%d " format, __VA_ARGS__)
The only issue is that, this macro doesn't compile when my logging has no parameters, for example:
MYLOG("hello world");
I've read some wikis and blogs, there's a solution for GCC compiler:
#include <stdio.h>
#define MYLOG(format, ...) printf("%s:%d " format, ##__VA_ARGS__)
But is there a more standard way to implement this macro working on GCC/Clang/MSVC compilers?
1 Answer 1
If your compiler supports C++20 then there is a standard way to solve this problem using __VA_OPT__. __VA_OPT__(,) will expand to a comma if __VA_ARGS__ is not empty. So when __VA_ARGS__ is empty, there's no extra comma and no compilation error.
#define MYLOG(format, ...) printf("%s:%d " format __VA_OPT__(,) __VA_ARGS__)
1 Comment
__VA_OPT__ is the only standard way.
#define MYLOG(text) printf("%s:%d %s", __FILE__, __LINE__, text)...#define MYLOG_FMT(format, ...) printf("%s:%d " format, __FILE__, __LINE__, __VA_ARGS__)CallMYLOG()when you don't have format parameters, and callMYLOG_FMT()when you do.#definemacro for debug printing in C — it covers most of the territory you need, and includes passing reference to adding__FILE__and__LINE__information to the logging.