How to define a string literal in gcc command line?

richard picture richard · Mar 9, 2010 · Viewed 61.4k times · Source

In gcc command line, I want to define a string such as -Dname=Mary, then in the source code I want printf("%s", name); to print Mary.
How could I do it?

Answer

Arthur Shipkowski picture Arthur Shipkowski · Mar 9, 2010

Two options. First, escape the quotation marks so the shell doesn't eat them:

gcc -Dname=\"Mary\"

Or, if you really want -Dname=Mary, you can stringize it, though it's a bit hacky.

#include <stdio.h>

#define STRINGIZE(x) #x
#define STRINGIZE_VALUE_OF(x) STRINGIZE(x)


int main(int argc, char *argv[])
{
    printf("%s", STRINGIZE_VALUE_OF(name));
}

Note that STRINGIZE_VALUE_OF will happily evaluate down to the final definition of a macro.