代码之家  ›  专栏  ›  技术社区  ›  Ahmed Al-haddad

C struct-错误:两个文件之间的类型名未知

  •  0
  • Ahmed Al-haddad  · 技术社区  · 7 年前

    我有3个文件:

    -文件1具有表1结构和作用于表2结构的函数

    // header file table 1
    #include "table_2.h" 
    typedef struct{...}table1;
    
    void * doSomethingGivenTable2(table2 * t2);
    

    -文件2具有表2结构和作用于表1结构的函数

    // header file table 2
    #include "table_1.h"
    typedef struct{...}table2;
    
    void * doSomethingGivenTable1(table1 * t1);
    

    -文件3同时使用文件1和2中的结构

    #include "table_1.h"
    #include "table_2.h" 
    // this is fine because I am including both of them in a separate file
    

    在文件3中发生的事情是可以的,但是文件1和文件2产生 error: unknown type name 因为我在另一个文件中包含了每个文件的头。我还定义了使用其他结构的函数。我能把这两个函数都放在各自的位置上修复吗?如果没有,那我还有什么选择呢?

    谢谢

    4 回复  |  直到 7 年前
        1
  •  3
  •   Ian Abbott    7 年前

    你需要结构标签这样你就可以 typedef 不完整结构类型的标识符。避免定义相同的 类型定义 标识符多次 类型定义 声明可以移动到公共头文件中,如下所示:

    表四公共.h 以下内容:

    #ifndef TABLE_COMMON_H_INCLUDED
    #define TABLE_COMMON_H_INCLUDED
    
    typedef struct table1 table1;
    typedef struct table2 table2;
    
    #endif
    

    表1.h 以下内容:

    #ifndef TABLE_1_H_INCLUDED
    #define TABLE_1_H_INCLUDED
    
    #include "table_common.h"
    
    struct table1 {
       ...
    };
    
    void * doSomethingGivenTable2(table2 * t2);
    
    #endif
    

    表2.h 以下内容:

    #ifndef TABLE_2_H_INCLUDED
    #define TABLE_2_H_INCLUDED
    
    #include "table_common.h"
    
    struct table2 {
       ...
    };
    
    void * doSomethingGivenTable1(table1 * t1);
    
    #endif
    

    笔记 以下内容:

    1. 这个 table1 在里面 struct table1 是结构标记。我对结构标记及其关联的 类型定义 标识符。可以使用相同的名称,因为结构标记的命名空间与其他标识符的命名空间不同。但是,不要求结构标记名与typedef标识符匹配,这样可以根据需要使它们不同。

    2. 我编写的头文件使用了一个常见的预处理器技巧,以避免同一头文件包含多次时出现问题。为这个技巧定义的宏称为“保护宏”。

        2
  •  2
  •   Chris Turner    7 年前

    你可以把 typedef 从实际出发 struct 像这样的定义。这允许编译器知道 table1 是一个数据类型,它可以找到,但它会得到它的完整定义,所以不用担心它还不知道它到底是什么。

    #ifndef TABLE1_H
    #define TABLE1_H
    
    typedef struct table1_s table1;
    
    #include "table2.h"
    
    struct table1_s
      {
      // contents of struct
      };
    
    #endif
    

    作为旁白,如果您的函数只使用(例如) table2 ,它们应该在与 表2 ,不是 表1 是的。

        3
  •  1
  •   Hongyu Wang    7 年前

    在相反表的头中声明结构名称,如

    typedef struct table1 table1;

    在表2.h内,反之亦然。

        4
  •  1
  •   Jay    7 年前

    您需要使用forward声明。

    在文件1中,添加以下语句:

    typedef struct tbl2 table2;
    

    在文件2中,添加以下语句:

    typedef struct tbl1 table1;
    

    在文件3中,添加以下语句:

    typedef struct tbl1 table1;
    typedef struct tbl2 table2;
    

    这就是所谓的forward声明,它告诉编译器这些结构在其他地方是可用的,不要抱怨。