4

I have following code:

#include <stdio.h>


#ifdef COMP_DEF
static const char * x = COMP_DEF;
#else
static const char * x = "NULL";
#endif

int main(int argc, char ** argv)
{
    printf("%s\n", x);
    return 0;
}

What I want is to compile this program with two ways. First with compiler parameter:

-DCOMP_DEF=FOO_BAR

and second way without this. I expect, my program would print FOO_BAR and NULL. But when I try to compile I get following errors:

:0:10: error: 'FOO_BAR' undeclared here

(not in a function) main.c:5:25: note: in expansion of macro 'COMP_DEF' static const char * x = COMP_DEF;

Is it possible to print/store in variable compiler passed macrodefine value?

Community
  • 1
  • 1
shjeff
  • 405
  • 4
  • 17
  • 2
    What is `FOO_BAR`? `-DCOMP_DEF=FOO_BAR` translates to `static const char * x = FOO_BAR;` which then needs a definition for `FOO_BAR`. If it's supposed to be a string, then you need to write, `-DCOMP_DEF=\"FOO_BAR\"` to make sure it goes to the pre-processor as a string, not a pre-processor variable name that has to be resolved. So then you get `static const char * x = "FOO_BAR";`. – lurker Dec 01 '17 at 12:03
  • Or look up some stringification topic like https://stackoverflow.com/questions/2653214/stringification-of-a-macro-value. – dbrank0 Dec 01 '17 at 12:08
  • `-DCOMP_DEF=\"FOO_BAR\"` works for me, but I prefer using -`DCOMP_DEF=FOO_BAR` and `#` in program. – shjeff Dec 01 '17 at 12:22

1 Answers1

6

You should try this common trick usually called stringification:

#define STR_IMPL(x) #x
#define STR(x) STR_IMPL(x)

#ifdef COMP_DEF
static const char * x = STR(COMP_DEF);
#else
static const char * x = "NULL";
#endif

# followed by argument name in macro expands to string literal containing passed argument. If you do just

#define STR(x) #x

this would make STR(COMP_DEF) expand to "COMP_DEF". To avoid this you need another level of macro expansion.

  • 1
    This is what I was looking for. I was trying using `#` but I didn't try to expand it twice, directly. – shjeff Dec 01 '17 at 12:21