I need to define a structure and a callback function type in C as follows:
typedef void (*callback)(struct XYZ* p);
struct {
int a;
int b;
callback cb;
} XYZ;
Now this code won't compile because each definition requires the other. What I mean is, if the callback definition comes first, it won't compile because it requires the struct to be defined. Similarly if the struct is defined first, it requires the callback to be defined. Maybe this is a stupid question, but is there a clean way to resolve such issues?
Currently my idea would be to use a void * as callback argument, and typecast it to struct XYZ inside the callback. Any ideas?
Declare the struct
(without defining it yet) before the function typedef
:
struct XYZ;
typedef void (*callback)(struct XYZ* p);
struct XYZ { // also fixed an error where your struct had no name
int a;
int b;
callback cb;
};
Similar to declaring a function-prototype and calling it before its definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With