我有一个非常大的程序无法编译,我怀疑它与跨结构的循环依赖关系有关。当我像下面这样编码时,它不会编译
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方法,还是我做错了什么导致我的第一个解决方案失败?
不同文件中相互递归结构没有问题。
这里的主要问题是圆形夹杂物不起作用。不过,解决这个问题很容易,因为两个标头都不能包含另一个标头。
如果您跳过typedef
, 你可以这样做:
// In a.h
struct a {
struct b *ptr;
};
and
// 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;
and
// 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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)