c - 在两个不同的头文件中的两个结构中包含循环依赖是错误的吗?

标签 c struct c-preprocessor header-files

我有一个非常大的程序没有编译,我怀疑它与跨结构的循环依赖有关。当我像下面这样编码时,它不会编译

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/

相关文章:

struct - 选项类型是否小于包装类型加上 boolean 值?

C++ 预处理器指令限制

c - 将 PATH 环境变量拆分为单独的文件路径

c - 加载时初始化、运行时初始化、编译时初始化

json - 我无法使用从请求中获取的数据创建结构

C++ 预处理器在类关键字之后和类名之前定义

C++ __COUNTER__ 定义

c - 写入 - 读取二进制文件中的结构

c - GNU GDB : customize watchpoint output format

c - 如何从函数内将指针(指向结构)设为 NULL