C 递归头文件包含问题?

问题描述 投票:0回答:4

假设您必须在两个头文件中定义相关结构,如下所示:

a.h内容:

#include b.h

typedef struct A
{
  B *b;
} A;

b.h内容:

#include a.h

typedef struct B
{
  A *a;
} B;

在这种情况下,这种递归包含是一个问题,但是2个结构必须指向其他结构,如何实现这一点?

c recursion header include
4个回答
5
投票

不要#include a.h 和 b.h,只需前向声明 A 和 B。

a.h:

struct B; //forward declaration
typedef struct A
{
    struct B * b;
} A;

b.h:

struct A; //forward declaration
typedef struct B
{
    struct A * a;
} B;

您可能需要考虑这些类的耦合程度。如果它们耦合得非常紧密,那么它们可能属于同一个标头。

注意:您需要在

#include
文件中同时
.c
a.h 和 b.h 才能执行
a->b->a
等操作。


4
投票

Google C/C++ 指南建议

当前向声明就足够时,不要使用#include

这意味着:

a.h内容:

typedef struct B B;

typedef struct A
{
  B *b;
} A;

b.h内容:

typedef struct A A;

typedef struct B
{
  A *a;
} B;

如果您更喜欢更安全的东西(但编译时间更长),您可以这样做:

a.h内容:

#pragma once
typedef struct A A;

#include "B.h"

typedef struct A
{
  B *b;
} A;

b.h内容:

#pragma once
typedef struct B B;

#include "A.h"

typedef struct B
{
  A *a;
} B;

2
投票

您只需预先定义结构体,这样您仍然可以声明指针:

a.h

typedef struct B_ B;

typedef struct A_
{
  B *b;
} A;

请注意我如何为

typedef
和结构标记使用单独的名称,以使其更清晰。


1
投票

这将在 C: 中剪切它

typedef struct B B;
typedef struct A A;
struct A { B *b; };
struct B { A *a; };

您可以根据需要重新排列

B
A

© www.soinside.com 2019 - 2024. All rights reserved.