How to define a string literal in gcc command line?

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?


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.


to avoid the shell "eating" the quotes and other characters, you might try single quotes, like this:

gcc -o test test.cpp -DNAME='"Mary"'

This way you have full control what is defined (quotes, spaces, special characters, and all).


Most portable way I found so far is to use \"Mary\" - it will work not only with gcc but with any other C compiler. For example, if you try to use /Dname='"Mary"' with Microsoft compiler, it will stop with an error, but /Dname=\"Mary\" will work.


In Ubuntu I was using an alias that defines CFLAGS, and CFLAGS included a macro that defines a string, and then I use CFLAGS in a Makefile. I had to escape the double quote characters and as well the \ characters. It looked something like this:

CFLAGS='" -DMYPATH=\\\"/home/root\\\" "'