我有这样的情况:
啊和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.h和B.hinA.h我得到:
error: unknown type name 'TypeB_t'在A.h
和
error: unknown type name 'TypeA_t'在B.h
我在这里发现了一个类似的问题,但它不适用于我的情况。
您定义代码的方式TypeA可以使用对 的前向引用TypeB,但TypeB需要完整的声明TypeA才能编译。
换句话说,您需要做两件事。首先TypeB在a.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)