简体   繁体   English

gcc宏定义选项不适用于字符串

[英]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选项时,我发现以下命令有效:

gcc -D MARCO=12345 test.c

but when I change 12345 to a string: 但是当我将12345更改为字符串时:

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" ; 我试过-DMARCO=abcde-DMARCO="abcde" ,- -D MARCO="abcde" ; all failed with that error. 所有这一切都失败了。

Does this -D option only support integers? 这个-D选项只支持整数吗?

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): 问题是shell会识别双引号并将其删除,除非您通过转义双引号(使用反斜杠)或将它们用单引号括起来阻止shell执行此操作(这是我使用的):

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. 单引号被shell剥离,但这意味着C预处理器可以看到双引号。 You need to use the %s format, of course. 当然,您需要使用%s格式。

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. gcc -o testprog -DMARCO=abcde test.c编译它,你会发现它产生了正确的答案。

The macro MARCO is literally replaced by the string you entered and only then is the code compiled. MARCO实际上被您输入的字符串取代,然后才编译代码。 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. 由于字符串周围没有引号(两个示例中的双引号被shell解释为分隔符),因此abcde不会被解释为字符串,而是解释为标识符。 Since it isn't defined, the code fails to compile. 由于未定义,因此代码无法编译。

you can also use like this... 你也可以这样使用......

-DMACRO="\\"abcde\\""

Ref: How do I pass a quoted string with -D to gcc in cmd.exe? 参考: 如何将带-D的带引号的字符串传递给cmd.exe中的gcc?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM