32

What I'm trying to do is to #define a macro:

#define a(2)

and later use it inside a string literal: string = "a";.

I want that string to be interpreted not as string but to get the value of a, i.e. 2. I didn't succeed, can anybody help?

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
Amine
  • 347
  • 1
  • 5
  • 12

2 Answers2

42
#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.".

Simple
  • 13,992
  • 2
  • 47
  • 47
  • 7
    Now add the crucial element that adjacent string literals are concatenated and this is an answer. – pmr Dec 17 '13 at 10:47
  • 1
    If you don't want to rely on the concatenation feature, you may try: `STRINGIFY(I have the number A)` (I'm not sure about the dot at the end). – imz -- Ivan Zakharyaschev Dec 17 '18 at 08:14
  • Note the extra indirection with the wrapped expansions, which is required. – BjornW Jan 20 '21 at 13:56
  • I'm using `#include "filename_" STRINGIFY(VERSION) ".hpp"` and I'm getting two errors: `fatal error: filename_: No such file or directory` and `warning: extra tokens at end of #include directive` (pointing at the STRINGIFY) – Mark Jeronimus Apr 01 '22 at 13:34
8

No, you cannot do macro expansion INSIDE string literals (i.e. having the preprocessor to look inside literals for macros to expand).

You can have a macro expansion to produce a string literal using the stringify operator (#). But that's a different thing.

6502
  • 112,025
  • 15
  • 165
  • 265