Home > Net >  C and MSVC #define directive with optional arguments
C and MSVC #define directive with optional arguments

Time:03-17

I'm having trouble trying to get a macro that I'm writing to function correctly. I've read the docs and can't find anything online to help with what I'm looking for.

I am attempting to write a macro that is used for info and debugging purposes. The exact macro should look like:

INFODUMP("Some format string here with a variable %f", someVariableInCode);

Which would expand to:

std::printf("INFO: Some format string here with a variable %f\n" someVariableInCode);

The macro that I have written that doesn't function correctly is:

#define INFODUMP(s, ...) std::printf("INFO: %s\n", s, __VA_ARGS__)

While technically, this macro is functioning, it doesn't do the formatting.

For example, I have:

INFODUMP("Size of width buffer: %i, size of height buffer: %i", wCells.size(), hCells.size());

And in the console when the program is ran, I get:

INFO: Size of width buffer: %i, size of height buffer: %i

So the macro works, it just isn't formatting the string. It's kind of like formatting it with s correctly, but not any of the optional arguments afterwards.

If I had to guess, it has something to do with strings and how they are formatted during runtime. If that's the case, I'm still completely lost on what to look up.

Notes:

  • I'm using Visual Studio 2022 Community with the Visual C (v143) compiler (latest).
  • While researching online, the __VA_OPT__ preprocessor variable isn't a thing anymore, I don't believe, but I could be entirely wrong.

CodePudding user response:

That's not how printf() works.

Your macro expands:

INFODUMP("%d", 42);

To:

std::printf("INFO: %s\n", "%d", 42)

You need:

 #define INFODUMP(s, ...) std::printf("INFO: " ## s ## "\n", __VA_ARGS__)

Which will then expand:

INFODUMP("%d", 42);

To:

std::printf("INFO: %d\n", 42)
  • Related