【发布时间】:2015-12-28 20:42:59
【问题描述】:
在这里设置场景 - 我有 2 个 .c 文件,将其命名为 a.c 和 b.c。
然后,每个 .c 文件都有 2 个头文件,a.h(它具有所有函数原型和所有声明为 extern type name; 的全局变量)和 b.h,它只有 b.c 的函数原型b.c 不包含全局变量。
我想在b.c中访问a.c的全局变量,所以我在b.c中添加了声明#include "a.h"。
唯一的问题是,我仍然无法访问a.c 在b.c 中的全局变量,例如如果我想打印。我在a.c 中有一个全局变量int i;,如果我这样做:
i = 5;
printf("%d", i); 在b.c 中,我收到一条错误消息,指出尚未声明变量 i。我做错了什么?
代码:
交流:
#include "b.h"
int i;
int main() {
executeMethod();
return 0;
}
b.c:
#include "a.h"
void executeMethod() {
i = 10;
printf("%d", i);
啊哈:
int main();
extern int i;
b.h:
void executeMethod();
制作文件:
CFLAGS=-墙 -g
all: main
main: a.c b.c a.h b.h
gcc $(CFLAGS) -o main a.c b.c a.h b.h
clean:
rm -f main
也尝试过不使用 makefile: gcc -o main a.c b.c a.h b.h
谢谢。
编辑:如果我在我的 b.c 文件之上定义 extern int i; 它可以工作,但假设我有 60 个变量,我宁愿将它们放在 header.h 文件中并且只使用 #include "header.h" 而不是写 50 extern声明。
【问题讨论】:
-
你需要发布你的代码,这样我们才能看到你做错了什么。
-
如果能附上minimal reproducible example就太好了?
-
我已经阅读了 - 以及其他来源。一些消息来源建议我可以使用头文件来实现这一点,这就是我想要做的。
-
@Barmar 我已经这样做了。
-
重要问题 - 你是如何编译/链接它的?生成文件?