C中的共依赖定义

Pyr*_*AVR 3 c conventions

假设我们在struct上有一个函数指针,它有一个struct本身作为第一个参数,一个典型的回调场景.

typedef void (*callback_type)(my_struct_type *mst, int whatever);

typedef struct {
    // lots of fun stuff
    callback_type notify_me;
} my_struct_type;
Run Code Online (Sandbox Code Playgroud)

typedef正如人们所料,这会在第一个上产生编译器错误.error: unknown type name my_struct_type.反转定义会产生相同的结果,但未知类型是callback_type.

简单的解决方案是执行以下操作:

typedef struct my_struct_type_S {
    // lots of fun stuff
    void (*notify_me)(my_struct_type_S *mst, int whatever);
} my_struct_type;
Run Code Online (Sandbox Code Playgroud)

但是,这样做会省略函数指针类型定义,以后可以很容易地引用它,并用于静态类型检查,漂亮的错误消息等等.

有关如何解决此问题的任何建议?

编辑"可能重复":此方案涉及typedefs对许多人来说晦涩的函数指针.我认为这是一个很好的例子,此外,接受的答案非常干净,清晰,简单.

dbu*_*ush 5

您可以通过为struct提供标记并使用struct的forward声明来完成此操作.然后,您可以将typedef用于函数指针,然后完成结构的定义.

typedef struct my_struct_type_S my_struct_type;

typedef void (*callback_type)(my_struct_type *mst, int whatever);

struct my_struct_type_S {
    // lots of fun stuff
    callback_type notify_me;
};
Run Code Online (Sandbox Code Playgroud)