tags:

views:

102

answers:

1

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

Thanks

+4  A: 

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.

Arthur Shipkowski
thank you so much Arthur. you must be a expert in C.further question:I perfer the second option. when I'm using STRINGIZE_VALUE_OF(name), it translate it to "1", in the case that I have gcc -Dname=Mary -DMary. is there anyway to let gcc stop interprite Mary
richard
Richard, after much review I do not believe I can come up with a way that works in the above example. Unfortunately, your choices are no expansion (e.g. gives you "name") and full expansion (e.g. name->Mary->1 if Mary is defined as 1). Depending on your exact usage case there may be ways around this -- if Mary can become a const int rather than a define, for example.
Arthur Shipkowski
thanks again. I'll go wuth first option.
richard