1

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?

asked Jan 17, 2020 at 5:39
7
  • What about simply using 2 different macros? #define MYLOG(text) printf("%s:%d %s", __FILE__, __LINE__, text) ... #define MYLOG_FMT(format, ...) printf("%s:%d " format, __FILE__, __LINE__, __VA_ARGS__) Call MYLOG() when you don't have format parameters, and call MYLOG_FMT() when you do. Commented Jan 17, 2020 at 5:44
  • @RemyLebeau, It really solve the issue, but I'm just looking for a killer solution. Commented Jan 17, 2020 at 5:52
  • 1
    Take a good look at #define macro 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. Commented Jan 17, 2020 at 5:55
  • stackoverflow.com/a/8673872/918959 Commented Jan 17, 2020 at 6:25
  • 1
    Also there is no such language as C/C++. Either something is C or is not, something is C++ or not. A minority of code is in the intersection. What it is that you want? Commented Jan 17, 2020 at 6:27

1 Answer 1

2

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__)
answered Jan 17, 2020 at 5:49
Sign up to request clarification or add additional context in comments.

1 Comment

It looks __VA_OPT__ is the only standard way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.