0

I am trying to pass a string as a parameter when compiling to this code:

#include <iostream>
#define MY_STRING #STRING_IN

int main(int argc, char** argv) {
    std::cout << MY_STRING;
}

It is compiled with the flag:

-DSTRING_IN=foo

I get the following error:

error: stray '#' in program

 #define MY_STRING #STRING_IN

                   ^

note: in expansion of macro 'MY_STRING'

     std::cout << MY_STRING;

                  ^~~~~~~~~

[...]

Compiler returned: 1

See also here.

How can I pass a parameter via -D... and then turn that into a string?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185

1 Answers1

3

Well, I tried many combinations before posting here, just not the correct one... It works when I stringify the token like this:

#include <iostream>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define MY_STRING TOSTRING(STRING_IN)

int main(int argc, char** argv) {
    std::cout << MY_STRING;
}

See also here for the more general case.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185