I am trying to compile a very simple C program:
# program test.c
#include <stdio.h>
int main()
{
printf("HELLO WORLD \"%s\"\n\n", FOO);
}
and compiled with
gcc -o prog -D FOO=bar test.c
Basically what I am looking to have the following output:
HELLO WORLD "bar"
When I run the above, I get the error
<command line>:1:13: note: expanded from here
#define FOO bar
I'm even going so far as to do the following (and yes, I know this is not good):
#indef FOO
define ZZZ sprintf("%s", FOO)
#endif
CodePudding user response:
#define FOO bar
makes no sense in your example; what is the bare word bar
?
If you want to replace it with the string "bar"
, then you need to produce
#define FOO "bar"
You can achieve this by adding quotes to your CLI flag, which typically should be escaped:
gcc test.c -D FOO=\"bar\" -o prog
./prog
HELLO WORLD "bar"
CodePudding user response:
You need to stringify it.
#define STR(x) XSTR(x)
#define XSTR(x) #x
#include <stdio.h>
int main()
{
printf("HELLO WORLD \"%s\"\n\n", STR(FOO));
}
output:
HELLO WORLD "bar"
https://godbolt.org/z/cqd9GP5zb
Two macros have to be used as we need to expand the macro first and then stringify it.