7

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 ?

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
Adam M-W
  • 3,509
  • 9
  • 49
  • 69

3 Answers3

5

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;
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Will this work if I pass in a callback function that uses for example: `int callback(X * x, void * ctx)`, or will the compiler complain that `X` is different from `struct X`? – Adam M-W Jul 30 '11 at 22:24
  • Sorry, I fixed it -- I generally prefer to give the `struct` and its typedef different names so you can unambiguously refer to both as needed. See the edit. – Kerrek SB Jul 30 '11 at 22:27
5

Just forward declare your typedefs

typedef struct X X;
typedef struct CallbackData CallbackData;

and then declare the structs later.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
0

Yes, you can forward declare the struct and use it in the declaration of MyCallbackFunction where you don't need it to be a complete type.

struct X;
typedef int (MyCallbackFunction)(struct X * x, void * ctx);
CB Bailey
  • 755,051
  • 104
  • 632
  • 656