#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_t
,stage_table_context_t
引用stage_table_function_t
。
显然,位置在这里并不重要,因为任何一个方向都会导致问题。似乎我需要转发声明阶段表上下文结构,但不确定如何使用 typedef 来执行此操作。
对这个愚蠢的问题表示歉意,我已经离开 C 6 个月了,我有点脑子放屁了。
编辑:修复了代码中的一些拼写错误。
最佳答案
您可以在定义struct
之前对其进行声明:
/* declaration */
struct foo;
.....
/* definition */
struct foo
{
....
};
在任何地方编写 struct foo
都是该结构的声明,因此您不必将其放在单独的行中,您可以将其放在 typedef、指针声明等中。
请注意,有时,例如在 struct foo
类型的变量声明中,您还需要定义(以计算变量大小);
/* declare struct foo ..*/
struct foo;
/* .. or declare struct foo ..*/
typedef struct foo foo;
/* .. or declare struct foo ..*/
struct foo *p;
/* .. or declare struct foo */
int bar (struct foo *p);
/* Not valid since we don't have definition yet */
struct foo f1;
/* definition */
struct foo
{
....
};
/* Valid */
struct foo f2;
在你的情况下,你没有给结构命名;您刚刚创建了一个 typedef
,它是匿名结构的别名。因此,要转发声明您的结构,您必须为其命名:
/*
forward declare the `struct stage_table_context_t` and give it a typedef alias
with the same name as the structs name
*/
typedef struct stage_table_context_t stage_table_context_t;
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;
struct stage_table_context_t{
uint32_t error_number;
stage_t* current_stage;
} stage_table_context_t;
关于单个 C 头文件中的循环依赖。需要前向声明吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56718874/