How to Use MACro Argument as String Literal

How to use Macro argument as string literal?

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);

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

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))

How to use a string literal as a macro argument?

Something like this could work:

#define STRING_MAP_ENTRY(value, name) \
{value, #value " - " #name}

STRING_MAP_ENTRY(0, ENTRY_1)

the # before a token will stringify it. As for combining them, adjacent string literals will be combined into a single string.

Expand macro inside string literal

#define STRINGIFY2(X) #X
#define STRINGIFY(X) STRINGIFY2(X)
#define A 2

Then STRINGIFY(A) will give you "2". You can concatenate it with other string literals by putting them side by side.

"I have the number " STRINGIFY(A) "." gives you "I have the number 2.".

Convert a macro argument into a string constant and take into account commas

You can treat the argument as a single variadic macro:

#define FOO_VERSION 1,0,0,1

#define STRING_VALUE(...) STRING_VALUE__(__VA_ARGS__)
#define STRING_VALUE__(...) #__VA_ARGS__

This seems to work with gcc and Visual C++.

macro: string literal from char literal

–Summary of the comments to the question–

This seems impossible to achieve. As an alternative, the string literal could be defined and a STRING2CHAR macro be written instead:

#define A "a"
#define STRING2CHAR(s) (*(s))
write(fd, "x=" A "\n", 4);
putchar(STRING2CHAR(A));

or

#define A a
#define XSTR(s) #s
#define SYM2CHAR(sym) (*XSTR(sym))
#define SYM2STRING(sym) XSTR(sym)

The expression *"a" isn't a compile-time constant (so e.g. it cannot be used as an initializer for an object with non-automatic storage duration, a non-VLA array length, a case label, or a bit-field width), though compilers should be able to evaluate it at compile-time (tested with Gcc and Clang).


Suggested by M Oehm and Matt McNabb.

how to make macro replacement text into a string in C / C++

You have to do another pass. Typically:

#include <iostream>   

#define NUMBER 2.847

#define STRING(a) #a
#define XSTRING(a) STRING(a)

int main() {
std::cout << XSTRING(NUMBER) << '\n';
}


Related Topics



Leave a reply



Submit