首页 > 解决方案 > 头文件中的 typedefed 结构在包含该文件的其他头文件中不可识别

问题描述

typedef在头文件中有一个 ed 结构

数据结构.h:

#if !defined(__DATA__STRUCTURE__HEADER__)
#define __DATA__STRUCTURE__HEADER__
#include <stdbool.h>
#include "tokenizer.h"
/*arraylist implemtation*/
#define INIT_SIZE 4
#define GROWING_FACTOR 2
typedef struct
{
    char** enumerable_items;
    int size;
    int first_free_index;
}list; 
list init_list(void);
bool add_to_end(list collection, char* added_item);
char* get_item_at_index(list access_list, int access_index);
void free_list(list memory_to_free);
list remove_item(list, char *);
/*more....*/
#endif

在我包含的第二个文件中,file_1.h我声明了一个方法,它的一个参数来自liststruct 类型。

标记器.h:

#if !defined(__TOKENIZER__HEADER__)
#define __TOKENIZER__HEADER__
#include <stdbool.h>
#include "data_structure.h"
#define WORD_SIZE 24
typedef enum {none, asm_command, ignore, instruction}asm_line_type;

typedef struct
{
    char *label;
    char *op_name;
    struct list operands;
    bool is_instruction;
    unsigned int adress : WORD_SIZE;
    int line_number;
}asm_line_data;
#define NOT_FOUND {NULL, none, -1, false, -1}

bool match(char* command, char* match_template);
struct asm_command_syntax get_instruction_operand_amount(char *command, struct asm_command_syntax match_template);
asm_line_data *get_data(struct asm_command_syntax* command_syntax, struct list commands);
asm_line_data *tokenize(struct list string_commands, long *);
void validate_commas(struct list);
int get_word_amount(char* spaces_text);
struct asm_command_syntax classify(char* command);
#endif

两个头文件都包含保护。

当我用gcc( ansi C) 编译程序时,我得到以下编译器错误:

file_2.h:22:25: error: unknown type name ‘list’
   22 | void foo(list);

我用过很多次,错误都是一样的listtokenizer.h

当我尝试将typedefed 结构移动到tokenizer.h,然后包含tokenizer.h在 中时data_stracture.h,它在 中运行良好,但是每当我在那里使用时,我都会tokenizer.h遇到相同的错误。data_stracture.hlist

尝试添加 struct 关键字也不起作用,会产生以下错误:

tokenizer.h:12:17: error: field ‘operands’ has incomplete type
   12 |     struct list operands;
      |                 ^~~~~~~~

我怎样才能防止这样的错误?

标签: ccompiler-errorsheader-filestypedef

解决方案


正如@StoryTeller-Unslander Monica 所说,您的代码的基本问题是循环包含。

据我所知,您只需要文件struct list中的声明tokenizer.h

您可以做的是创建一个单独的头文件,比方说structure.h,在那里声明结构并将其包含在data_structure.h和中tokenizer.h

结构.h

typedef struct list{ //adding list here means you can use both list and struct list
    //...
}list; 

数据结构.h

#include "structure.h"

并删除#include "tokenizer.h"以及结构声明。

分词器.h

#include "structure.h"

并删除#include "data_structure.h".


推荐阅读