Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interlinked struct and callback in C

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?

like image 979
AbhinavChoudhury Avatar asked Dec 19 '22 22:12

AbhinavChoudhury


1 Answers

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.

like image 163
Kninnug Avatar answered Dec 27 '22 20:12

Kninnug