Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?> )
like image 389
cubuspl42 Avatar asked Oct 16 '16 12:10

cubuspl42


People also ask

How to convert macro parameters to string literals?

Thank you. The number-sign or "stringizing" operator ( #) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.

What is stringification of macro parameters?

When a macro parameter is used with a leading #, the preprocessor replaces it with the literal text of the actual argument, converted to a string constant. Unlike normal parameter replacement, the argument is not macro-expanded first. This is called stringification .

How do I convert a macro argument to a string constant?

Sometimes you may want to convert a macro argument into a string constant. Parameters are not replaced inside string constants, but you can use the ‘ # ’ preprocessing operator instead. When a macro parameter is used with a leading ‘ # ’, the preprocessor replaces it with the literal text of the actual argument, converted to a string constant.

What is stringification in C++?

This is called stringification . There is no way to combine an argument with surrounding text and stringify it all together. Instead, you can write a series of adjacent string constants and stringified arguments. The preprocessor will replace the stringified arguments with string constants.


1 Answers

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))
like image 123
cubuspl42 Avatar answered Oct 14 '22 07:10

cubuspl42