Wednesday, April 29, 2009

How to predeclare typedefs for self-referential typedefs

Sometimes you need to have a typedef that refers to itself through a struct member, or there is a circular reference. Here is how to predeclare the typedef so you can use it before it is fully defined. It's basically 3 parts. First declare the struct, then declare the typedef, then define the struct using the typedef.


struct fileinfo;
struct cached_block;

typedef struct fileinfo FILEINFO;
typedef struct cached_block CACHED_BLOCK;

struct fileinfo {
FILEINFO *fi_next; /* list of all files */
CACHED_BLOCK *fi_blks; /* cached blocks for this file */
/* ... */
};

struct cached_block {
int cb_lbn; /* logical block number */
CACHED_BLOCK *cb_next; /* next cached block for this file */
FILEINFO *cb_file; /* file containing this block */
/* ... */
};

2 comments:

Anonymous said...

That was helpful! Cheers!

Unknown said...

Thanks! I was worried this is not possible.