Don Hall Don Hall - 5 months ago 27
C Question

gcc macro define option doesn't work for string

Sample code:

printf("%d\n", MARCO);
// printf("%s\n", MARCO);

When I try to use
option, I found the following command works:

gcc -D MARCO=12345 test.c

but when I change 12345 to a string:

gcc -D MARCO=abcde test.c

an error occurs:

error: ‘abcde’ undeclared (first use in this function)

I have tried
-D MARCO="abcde"
; all failed with that error.

Does this
option only support integers?


The trouble is that double quotes are recognized by the shell and removed, unless you prevent the shell from doing so by escaping the double quotes (with backslashes) or enclosing them in single quotes (which is what I'd use):

gcc -DMARCO='"abcde"' test.c

The single quotes are stripped by the shell but that means that the double quotes are seen by the C preprocessor. You need to use the %s format, of course.

By changing the macro, you can stringify a non-quoted name on the command line:

#include <stdio.h>
#define STRINGIFY(x) #x
#define MACRO(x)     STRINGIFY(x)
int main(void)
    printf("%s\n", MACRO(MARCO));

Compile that with gcc -o testprog -DMARCO=abcde test.c and you will find it produces the correct answer.