Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C typedef function prototype with struct attempting to reference before defined.

Tags:

c

struct

I need to reference a struct that's not yet defined because the struct actually conatins the typedef'd function prototype.

For example,

typedef int (MyCallbackFunction)(X * x, void * ctx);

typedef struct CallbackData {
  MyCallbackFunction * callback;
  void * ctx;
} CallbackData;

typedef struct X {
  char a;
  int b;
  int c;
  double d;

  CallbackData e;
} X;

What's the valid way to actually write this code/header ?

like image 900
Adam M-W Avatar asked Jul 30 '11 22:07

Adam M-W


2 Answers

Just forward declare the relevant types - and you can make the function pointer part of the typedef:

struct X_;

typedef int (*MyCallbackFunction)(struct X_ * x, void * ctx);

typedef struct CallbackData_ {
  MyCallbackFunction callback;
  void * ctx;
} CallbackData;

typedef struct X_ {
  char a;
  int b;
  int c;
  double d;

  CallbackData e;
} X;
like image 196
Kerrek SB Avatar answered Sep 23 '22 09:09

Kerrek SB


Just forward declare your typedefs

typedef struct X X;
typedef struct CallbackData CallbackData;

and then declare the structs later.

like image 31
Jens Gustedt Avatar answered Sep 21 '22 09:09

Jens Gustedt