我有一个非常大的程序没有编译,我怀疑它与跨结构的循环依赖有关。当我像下面这样编码时,它不会编译
foo.h
#ifndef FOO
#define FOO
#include "bar.h"
typedef struct _foo Foo;
struct _foo{
Bar *bar;
}
#endif
bar.h
#ifndef BAR
#define BAR
#include "foo.h"
typedef struct _bar Bar;
struct _bar{
Foo *foo;
}
#endif
但如果我完全搞砸我的设计并创建一个 common.h 文件,并将所有结构声明放在那里,它似乎可以工作。
common.h
#ifndef COMMON
#define COMMON
typedef struct _foo Foo;
typedef struct _bar Bar;
#endif
foo.h
#ifndef FOO
#define FOO
#include "common.h"
#include "bar.h"
struct _foo{
Bar *bar;
}
#endif
bar.h
#ifndef BAR
#define BAR
#include "common.h"
#include "foo.h"
struct _bar{
Foo *foo;
}
#endif
这似乎是一个非常糟糕的设计。此外,我认为标题保护是为了防止循环包含引起的问题。我应该使用 common.h 方法,还是我做错了什么导致我的第一个解决方案失败?
最佳答案
不同文件中的相互递归结构没有问题。
这里的主要问题是循环包含不起作用。然而,解决这个问题很容易,因为两个 header 都不能包含另一个 header 。
如果你跳过 typedef
,你可以这样做:
// In a.h
struct a {
struct b *ptr;
};
和
// In b.h
struct b {
struct a *ptr;
};
或者
如果你想使用 typedef,你只需要跳过在结构定义中使用它。
// In a.h
struct a {
// Have to use 'struct b' instead of 'b' because we can't guarantee
// that the typedef for b is visible yet.
struct b *ptr;
};
typedef struct a a;
和
// In b.h
struct b {
// Have to use 'struct a' instead of 'a' because we can't guarantee
// that the typedef for a is visible yet.
struct a *ptr;
};
typedef struct b b;
关于c - 在两个不同的头文件中的两个结构中包含循环依赖是错误的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45203743/