开发平台(Platform)(Ex: Win10, Linux, ...)
Online GDB
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
GCC
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
None
问题(Question):
使用test.i 出现错误
喂入的资料(Input):
None
预期的正确结果(Expected Output):
test.i=1
错误结果(Wrong Output):
error: invalid use of undefined type 'struct A'
程式码(Code):(请善用置底文网页, 记得排版,禁止使用图档)
main.c
extern struct DATA test;
int main()
{
test.i=1;
return 0;
}
test.c
struct DATA
{
int i;
};
struct DATA test={0};
补充说明(Supplement):
None
1F:→ wulouise: main.c怎麽知道你在test.c declare DATA?03/01 23:16
我原本以为只要test.c有delcare 後compile 在link 的时候就可以让main.c去extern stru
ct DATA且使用,看来这是错误的理解。
也就是说我必须也要在main.c中delcare struct DATA,让main.c知道有这个delcare,这时
候extern 才可以知道这个test变数的型态是struct DATA。
这要理解不知道有没有问题。如有问题还请大大多指点。谢谢!
※ 编辑: OnlyCourage (114.36.205.245 台湾), 03/01/2024 23:37:09
2F:推 lc85301: 你怎麽把文修成这个样子…03/01 23:42
3F:→ OnlyCourage: 靠..我能恢复吗..还是只能删掉重发..03/01 23:59
4F:→ OnlyCourage: 抱歉03/01 23:59
※ 编辑: OnlyCourage (114.36.205.245 台湾), 03/02/2024 00:03:33
※ 编辑: OnlyCourage (114.36.205.245 台湾), 03/02/2024 00:09:54
5F:→ OnlyCourage: 我已经尽量恢复了 不好意思 03/02 00:10
※ 编辑: OnlyCourage (114.36.205.245 台湾), 03/02/2024 00:11:07
6F:→ tinlans: C 语言的 struct definition 不会被编译到 object file 03/02 03:45
7F:→ tinlans: 里面去,所以在 linking time 完全遗失这项资讯。 03/02 03:45
8F:→ tinlans: 但你的问题主要不在於这件事上,而是你在 main.c 没有告 03/02 03:47
9F:→ tinlans: 知 compiler 说 DATA 这个 identifier 是什麽东西,缺乏 03/02 03:47
10F:→ tinlans: 了 DATA 的 declaration。 03/02 03:48
11F:→ tinlans: 又因为你在 main.c 尝试存取 test.i 也就是 DATA 的成员 03/02 03:49
12F:→ tinlans: ,此处需要 DATA 的 definition,否则 compiler 不知道 i 03/02 03:50
13F:→ tinlans: 的 type 以及它的 address offset 是多少,所以报错。 03/02 03:51
14F:→ tinlans: 你遇到的问题不是 linking-time error 而是 compile-time 03/02 03:55
15F:→ tinlans: error,所以一开始的思路就错了,有些基础需要重新加强。 03/02 03:55
16F:→ tinlans: 宣告(declaration)和定义(definition)这两个词汇也得好好 03/02 03:57
17F:→ tinlans: 重新理解,找不到适当的文章的话,问看看 ChatGPT。 03/02 03:57
18F:→ tinlans: 另外,你对 extern 这个关键字的理解也有问题,它修饰的 03/02 04:04
19F:→ tinlans: 对象是 test 不是 struct DATA test 整段,也不是 struct 03/02 04:04
20F:→ tinlans: DATA,这只是告诉 compiler 说 test 被 define 在别处。 03/02 04:05
21F:→ OnlyCourage: 大概懂意思了,谢谢两位大大的指教,我会再去多钻研 03/03 14:35
22F:→ OnlyCourage: 。感谢~~ 03/03 14:35