3

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 attempt to compile 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 
KingFish
  • 8,773
  • 12
  • 53
  • 81

2 Answers2

6

#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"
user229044
  • 232,980
  • 40
  • 330
  • 338
4

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.

0___________
  • 60,014
  • 4
  • 34
  • 74
  • Not your downvote, but if you believe this is the correct solution, with the other answer being incorrect, why not vote to close this topic as a [duplicate](https://stackoverflow.com/q/240353/2505965)? – Oka Aug 18 '22 at 22:32