【发布时间】:2020-11-17 10:47:21
【问题描述】:
我有两个文件 main.c 和 header.c。
main.c 有一些宏STR 我想根据文件中的一些#define 有条件地定义其值。
案例 1:
当我在main.c 文件中包含header.c 时,程序运行良好,如下所示:
main.c
#include<stdio.h>
#define _flag_b
#include "header.c"
void main(){
printf("%s", STR);
}
header.c
#ifndef _flag_a
#define STR "flag a is activated.\n"
#endif
#ifndef _flag_b
#define STR "flag b is activated.\n"
#endif
编译
anupam@g3:~/Desktop/OS 2020/so$ gcc main.c
anupam@g3:~/Desktop/OS 2020/so$ ./a.out
flag a is activated.
案例 2:
但由于某种原因,我想在编译命令中包含header.c,而不是在main.c 中。如下所示,这为我创造了这个问题:
main.c
#include<stdio.h>
#define _flag_b
// #include "header.c"
void main(){
printf("%s", STR);
}
header.c
#ifndef _flag_a
#define STR "flag a is activated.\n"
#endif
#ifndef _flag_b
#define STR "flag b is activated.\n"
#endif
编译
anupam@g3:~/Desktop/OS 2020/so$ gcc main.c header.c
main.c: In function ‘main’:
main.c:7:15: error: ‘STR’ undeclared (first use in this function)
7 | printf("%s", STR);
| ^~~
main.c:7:15: note: each undeclared identifier is reported only once for each function it appears in
header.c:6: warning: "STR" redefined
6 | #define STR "flag b is activated.\n"
|
header.c:2: note: this is the location of the previous definition
2 | #define STR "flag a is activated.\n"
|
我对这个问题做了很多研究,并且能够理解为什么会出现这个问题。但我无法解决这个问题。
请帮助我更好地理解这个问题并提出一些解决方案。也帮我改写问题。
【问题讨论】:
-
你为什么要这样做?标头应包含在内,而不是编译。
-
注意
str不是变量;它是一个宏。为避免混淆,约定使用大写标识符:#define STR -
在我们项目的测试文件中,我有类似的测试结构,他们希望根据定义的适当宏来定义不同的函数。
-
命令行定义请见4.1 Defining macros。
标签: c compilation macros ifndef