Reputation: 107
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?
Upvotes: 2
Views: 7145
Reputation: 16841
The macro MARCO
is literally replaced by the string you entered and only then is the code compiled. Since there are no quotes around the string (the double quotes in two of the examples are interpreted as delimiters by the shell), the abcde
is not interpreted as a string, but as an identifier. Since it isn't defined, the code fails to compile.
Upvotes: 2
Reputation: 1601
you can also use like this...
-DMACRO="\"abcde\""
Ref: How do I pass a quoted string with -D to gcc in cmd.exe?
Upvotes: 2
Reputation: 753785
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.
Upvotes: 16