Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different macro stringification rules in Clang and MSVC

I found there is a difference in macro stringification in MSVC and Clang. Is it possible to write a stringification macro in Clang that works the same as stringification in MSVC?

#define __IN_QUOTES(str) #str
#define IN_QUOTES(str) __IN_QUOTES(str)

#define HELLO_WORLD Hello world

int main()
{
#ifdef _MSVC_LANG
    printf("%s", "MSVC\r\n");
#else
    printf("%s", "CLANG\r\n");
#endif
    printf("%s", IN_QUOTES(HELLO_WORLD));

    return 0;
}

This code works same in both Clang and MSVC, but if I write line 3 as

#define HELLO_WORLD Hello, world

it will be compilable in MSVC (with "Hello, world") in output, but not compilable in Clang with an error "too many arguments provided to function-like macro invocation". The question is it possible to write IN_QUOTES macro that could produce "Hello, world" in both Clang and MSVC? I've tried

#define IN_QUOTES((str)) __IN_QUOTES(str)

It returns "(Hello, world)" in Clang and in MSVC, but for me is interesting to obtain it without parentheses.

like image 798
Dmitry Avatar asked Feb 03 '26 20:02

Dmitry


1 Answers

The following is correct, and should work on any conformant C99 compiler:

#define __IN_QUOTES(...) #__VA_ARGS__
#define IN_QUOTES(str) __IN_QUOTES(str)

It works with the MSVC versions I found on Compiler Explorer (as well as with Clang and GCC).

Note that it will not accurately preserve whitespace, but there's not a lot you can do about that.

(I had to change the #ifdef to #ifdef _MSC_VER; none of the on-line compilers I tried seemed to define _MSVC_LANG.)

like image 103
rici Avatar answered Feb 05 '26 12:02

rici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!