【问题标题】:Each .h file requires a struct defined in the other? (C)每个 .h 文件都需要在另一个文件中定义的结构? (C)
【发布时间】:2012-03-05 03:58:37
【问题描述】:

我有两个头文件,每个都需要在另一个中定义的类型。当我尝试编译时,我收到有关未知类型名称的错误。 (如果我只提供结构声明而不提供定义,我会收到不完整类型错误。)有什么解决方案可以让我正确共享这些结构?

现在,我的代码如下所示(想象一下 #ifndef 预处理器指令等):

<headerA.h>

#include "headerB.h"
typedef struct { 
  mytypeB myB;
} mytypeA;

<headerB.h>

#include "headerA.h"
typedef struct {} mytypeB;
void foo( mytypeA * myA);

【问题讨论】:

    标签: c


    【解决方案1】:

    您应该转发声明 struct mytypeA 而不是包括 headerA.h

    headerB.h 内:

    struct mytypeA; // <<<--- Forward declaration
    
    void foo(struct mytypeA* myA);
    

    这是有效的,因为您没有使用实际的mytypeA,只是一个指向它的指针。你不能用headerA 做同样的事情,因为mytypeA 包含实际的mytypeB

    【讨论】:

      【解决方案2】:

      您可以转发声明一个结构而无需定义整个事物。

      【讨论】:

        【解决方案3】:

        这些 SO 问题可能会对您有所帮助,因为它与您的问题有关。

        undefined C struct forward declaration

        How to declare a structure in a header that is to be used by multiple files in c?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-06-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多