首页 > 解决方案 > 单个 C 头文件中的循环依赖。需要前向声明吗?

问题描述

#ifndef STAGE_TABLE_DEFINITION_HEADER
#define STAGE_TABLE_DEFINITION_HEADER

typedef stage_table_context_t* (*stage_table_function_t)(stage_table_context_t*);

typedef struct {
    const char* stage_name;
    stage_table_function_t* function;
} stage_t;

typedef struct {
    uint32_t error_number;
    stage_t* current_stage;
} stage_table_context_t;

#endif 

上出现未知类型错误stage_table_context_t

函数指针stage_table_function_t指代stage_table_context_tstage_table_context_t指代stage_table_function_t

显然定位在这里并不重要,因为任何一个方向都会导致问题。似乎我需要转发声明舞台表上下文结构,但不确定如何使用 typedef 来执行此操作。

为这个愚蠢的问题道歉,我已经离开 C 6 个月了,我有点脑子放屁。

编辑:修正了代码中的一些错字。

标签: cstruct

解决方案


你只需要告诉编译器stage_table_context_t应该是struct; 这样,您就隐含地向前声明了struct stage_table_context_t,实际的定义可能会在以后出现。请注意, typedef 没有定义 a struct,它只是引入了一个别名。所以实际的定义是struct stage_table_context_t { ...,不管你是否为它引入别名(也不管你为别名使用哪个名字)。

typedef struct stage_table_context_t* (*stage_table_function_t)(struct stage_table_context_t*);

typedef struct {
    const char* stage_name;
    stage_table_function_t* function;
} stage_t;

struct stage_table_context_t {
    uint32_t error_number;
    stage_t* current_stage;
};

// optional (if you want to use "stage_table_context_t" as an alias for "struct stage_table_context_t"):
typedef struct stage_table_context_t stage_table_context_t;

推荐阅读