假设您必须在 2 个头文件中定义相关结构,如下所示:
a.h内容:
#include b.h
typedef struct A
{
B *b;
} A;
b.h内容:
#include a.h
typedef struct B
{
A *a;
} B;
在这种情况下,递归包含是一个问题,但是2个结构必须指向其他结构,如何实现?
最佳答案
不要 #include a.h 和 b.h,只需转发声明 A 和 B。
嗯:
struct B; //forward declaration
typedef struct A
{
struct B * b;
} A;
b.h:
struct A; //forward declaration
typedef struct B
{
struct A * a;
} B;
您可能想考虑这些类的耦合程度。如果它们紧密耦合,那么它们可能属于同一个 header 。
注意:您需要在.c
文件中#include
a.h 和b.h 来执行a->b->a
.
关于C递归头文件包含问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3768966/