[英]cyclic references leading to incomplete definition of type 'struct A'
The cyclic reference looks like this.循环引用看起来像这样。 A -> B -> C -> A
A -> B -> C -> A
I've forward declared A within C to resolve the earlier issue but then IntelliSense is not working or compiler is unable to reach out the fields of A.我已在 C 中转发声明 A 以解决较早的问题,但 IntelliSense 无法正常工作或编译器无法访问 A 的字段。
Edit included guards.编辑包括警卫。
ah啊
#ifndef CYCLIC_A_H
#define CYCLIC_A_H
#include "B.h"
typedef struct A A;
struct A {
B *b;
int value;
};
#endif //CYCLIC_A_H
bh bh
#ifndef CYCLIC_B_H
#define CYCLIC_B_H
#include "C.h"
typedef struct B B;
struct B {
C *c;
};
#endif //CYCLIC_B_H
c.h c.h
#ifndef CYCLIC_C_H
#define CYCLIC_C_H
// #include "A.h" // this causes issue as well
struct A;
typedef struct C C;
struct C {
struct A *a;
};
#endif //CYCLIC_C_H
main.c main.c
#include "C.h"
int main() {
struct C *c = malloc(sizeof(C));
c->a->value = 42; // problem
return 0;
}
In your code, the #include "Ch"
incorporates the text from that file (and only that file) into the body of the main.c
file.在您的代码中,
#include "Ch"
将该文件(并且仅该文件)中的文本合并到main.c
文件的正文中。 The trouble then is that there is no actual definition of the A
structure provided.那么问题是没有提供
A
结构的实际定义。
Now, while you can declare (and even do some stuff with) a pointer to an undefined structure - so long as you have declared it as a struct
- (as you have in C.h
), you cannot access any of that structure's members without the full definition.现在,虽然您可以声明(甚至做一些事情)指向未定义结构的指针 - 只要您已将其声明为
struct
- (就像您在C.h
中所做的那样),您无法访问该结构的任何成员没有完整的定义。
So, when you change the header that you #include
, from C.h
to Ah
, the pre-processor inserts the text from that header and all headers it itself includes into the body of main.c
. So, when you change the header that you
#include
, from C.h
to Ah
, the pre-processor inserts the text from that header and all headers it itself includes into the body of main.c
. Thus, the contents of all three headers are thus incorporated, and you then have the full definitions of the A
, B
and C
structures.因此,所有三个标头的内容都被合并,然后您就有了
A
、 B
和C
结构的完整定义。
Note: As pointed out in the comments, you also need to complete your "// problem" line, with a proper assignment: c->a->value = 42; // (or whatever)
注意:正如评论中指出的那样,您还需要完成“//问题”行,并进行适当的分配:
c->a->value = 42; // (or whatever)
c->a->value = 42; // (or whatever)
. c->a->value = 42; // (or whatever)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.