gpt4 book ai didi

C递归头文件包含问题?

转载 作者:太空狗 更新时间:2023-10-29 15:20:50 25 4
gpt4 key购买 nike

假设您必须在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com