1

Is there a way to put a define like this:

#define PUTVAL 0x00

#define foo(x) ("x")

int main()
{
    char *szFoo = foo(PUTVAL);

    return 0;
}

and get it modified by a macro, that szFoo would point to a stringliteral containing "0x00" isntead of "x" ?

dhein
  • 6,431
  • 4
  • 42
  • 74
  • Why don't you set `szFoo` equal to `PUTVAL`? Put some quotes around `0x00`. – Engineer2021 Jun 30 '14 at 10:03
  • @staticx I don't get what you mean, sry. – dhein Jun 30 '14 at 10:04
  • I don't get it, do you want `szFoo` to be equal to `"PUTVAL"` or to be equal to `"0"` ? – Antoine C. Jun 30 '14 at 10:04
  • @staticx Well ofc, it would work for this example, but I'm asking for a macro that fits my needs, not a workarround. – dhein Jun 30 '14 at 10:05
  • I want to get a stringliteral, containing what ever is handed over to the macro put between `"` so I could do `printf (foo(sdgsfdgfdgd))`and the output would simply be `sdgsfdgfdgd` – dhein Jun 30 '14 at 10:07

1 Answers1

5

Yes, you have to use two levels of macro and it is called stringification:

http://gcc.gnu.org/onlinedocs/cpp/Stringification.html

 #define xstr(s) str(s)
 #define str(s) #s
 #define foo 4
 str (foo)
      ==> "foo"
 xstr (foo)
      ==> xstr (4)
      ==> str (4)
      ==> "4"
ouah
  • 142,963
  • 15
  • 272
  • 331
  • 1
    Please edit a minimal version of the answer into the actual answer, just linking is not very good form. – unwind Jun 30 '14 at 10:07
  • That looks to me like a compiler extension, isn't it? – dhein Jun 30 '14 at 10:08
  • crazy :D but would be awesome anyway if you could add a minimal example – dhein Jun 30 '14 at 10:10
  • @Zaibis it isn't `#` has been around forever (seems that way anyway). the double layer of macros it to force the expansion of the initial input expression *before* applying the stringizer preprocessor operation (which happens in the second macro). – WhozCraig Jun 30 '14 at 10:11
  • 1
    Stringification was added in c89/c90 IIRC. – joop Jun 30 '14 at 10:11
  • Got a moment to get it. But this is realy nice, thanks. – dhein Jun 30 '14 at 10:17