Don Hall Don Hall - 3 months ago 12
C Question

gcc macro define option doesn't work for string

Sample code:

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


When I try to use
gcc
-D
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
-DMARCO=abcde
,
-DMARCO="abcde"
,
-D MARCO="abcde"
; all failed with that error.

Does this
-D
option only support integers?

Answer

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));
    return(0);
}

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

Comments