单个 C 头文件中的循环依赖。需要前向声明吗?

标签 c struct

#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 个月了,我有点脑子放屁了。

编辑:修复了代码中的一些拼写错误。

最佳答案

您可以在定义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/

相关文章:

ios - 为结构创建变量 (Swift)

c - 全局变量和结构体数组

c - 为什么文件描述符 1 和 2 可以在手动输入时读取,但在输入重定向时却不能读取?

c - 我怎样才能让我的程序测试哥德巴赫假设在 5 秒内优化

c - 为什么我的 DEBUG_PRINT 宏没有在包含它的 c 文件中被调用

c++ - C++函数引用

c - 如何输入可变长度字符串并输出用户定义长度字符串?

C fprintf 程序输出 -1.#J 而不是实数

c - 为什么需要 offsetof 宏?

c# - 如何在其方法中获取结构的地址?