Вопрос

I have a macro I use for debugging.

#define diagnostic_arg(message,...) fprintf(stderr,message,__VA_ARGS__)

I've found that I need to use wide-chars in my program, so I would like to change just my macro and have everything work:

#define diagnostic_arg(message,...) fwprintf(stderr,message,__VA_ARGS__)

However, I need wide character strings, which are defined by putting an L in front of the string's beginning quote mark:

#define diagnostic_arg(message,...) fprintf(stderr,Lmessage,__VA_ARGS__)

Now obviously, the above line doesn't work. But if I use L message, that won't work either. So how do I write Lmessage and have it do what I would like?

Это было полезно?

Решение

You can use the token pasting operator ##:

#define diagnostic_arg(message,...) fprintf(stderr,L##message,__VA_ARGS__)

However, it might be better to use TEXT macro (if you are in Visual Studio) which will do the right thing whether UNICODE is defined or not:

#define diagnostic_arg(message,...) fprintf(stderr,TEXT(message),__VA_ARGS__)

If you're not, TEXT can be defined like this:

#ifdef UNICODE
#define TEXT(str) L##str
#else
#define TEXT(str) str
#endif

However, if you plan on using other #defines as the first argument to this macro (and really even if you don't plan on it), you will need another layer of indirection in the macro so the definition will be evaluated instead of pasted together with L as text. See Mooing Duck's answer for how to do that, his is actually the correct way to do this, but I'm not deleting this answer because I want to keep my 80 rep.

Другие советы

I vaguely recall the answer being something along the lines of

//glues two symbols together that can't be together
#define glue2(x,y) x##y
#define glue(x,y) glue2(x,y) 
//widens a string literal
#define widen(x) glue(L,x)

#define diagnostic_arg(message,...) fprintf(stderr,widen(message),__VA_ARGS__)

Glue sometimes needs to be two macros (as I've shown), for bizzare reasons I don't quite understand, explained at the C++faq

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top