0

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

#include <iostream>
#define MY_STRING #STRING_IN

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

Compiled with the flag

-DSTRING_IN=foo

I get 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?

463035818_is_not_a_number
  • 88,680
  • 9
  • 76
  • 150

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_a_number
  • 88,680
  • 9
  • 76
  • 150