简体   繁体   中英

Macro argument stringification to wide string literal in C/C++ preprocessor

C preprocessor has a feature called stringification . It's a feature that allows to create a (narrow) string literal from a macro parameter. It can be used like this:

#define PRINTF_SIZEOF(x) printf("sizeof(%s) == %d", #x, sizeof(x))
/*                                  stringification ^^          */

Usage example:

PRINTF_SIZEOF(int);

...might print:

sizeof(int) == 4

How to create a wide string literal from a macro parameter? In other words, how can I implement WPRINTF_SIZEOF ?

#define WPRINTF_SIZEOF(x) wprintf( <what to put here?> )

In order to produce a wide string literal from a macro argument, you need to combine stringification with concatenation .

WPRINTF_SIZEOF can be defined as:

#define WPRINTF_SIZEOF(x) wprintf(L"sizeof(%s) == %d", L ## #x, sizeof(x))
/*                                         concatenation ^^ ^^ stringification */

In order to (arguably) increase readability, you can extract this trick into a helper macro:

#define WSTR(x) L ## #x
#define WPRINTF_SIZEOF(x) wprintf(L"sizeof(%s) == %d", WSTR(x), sizeof(x))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM