C 中的头文件递归

Ale*_*lex 3 c struct header

我有这样的情况:

Bh

typedef struct TypeA TypeA_t;
struct TypeA {
    ...
    TypeA_t *a;
    void (*doSomething)(TypeB_t *);
};
Run Code Online (Sandbox Code Playgroud)

博赫

typedef struct TypeB TypeB_t;
struct TypeB {
    ...
    TypeB_t *b;
    TypeA_t something;
};
Run Code Online (Sandbox Code Playgroud)

在每个文件中包含头文件的正确方法是什么?

如果我包含A.hinB.hB.hinA.h我得到:

error: unknown type name 'TypeB_t'A.h

error: unknown type name 'TypeA_t'B.h

我在这里发现了一个类似的问题,但它不适用于我的情况。

Bli*_*ndy 5

您定义代码的方式TypeA可以使用对 的前向引用TypeB,但TypeB需要完整的声明TypeA才能编译。

换句话说,您需要做两件事。首先TypeBa.h类定义之前进行前向定义(因为指针可以与部分定义一起使用):

//a.h
typedef struct TypeB TypeB_t;

typedef struct TypeA TypeA_t;
struct TypeA {
...
TypeA_t *a;
void (*doSomething)(TypeB_t*);
};
Run Code Online (Sandbox Code Playgroud)

然后包含a.hfromb.h来获取您的类的声明(因为您使用完整的TypeA类作为字段类型):

// b.h
#include "a.h"

typedef struct TypeB TypeB_t;
struct TypeB {
...
TypeB_t *b;
TypeA_t something;
};
Run Code Online (Sandbox Code Playgroud)