KingFish
KingFish

Reputation: 9153

Printing out a Variable from Compiler options

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 

Upvotes: 3

Views: 116

Answers (2)

0___________
0___________

Reputation: 67476

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.

Upvotes: 4

user229044
user229044

Reputation: 239240

#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"

Upvotes: 6

Related Questions