Following a C tutorial, I’ve encountered a type dependency that I don’t know how to resolve. So far, we had this:
typedef long SetStringPtr( char * );
typedef long GetStringPtr( char *, long );
typedef struct {
SetStringPtr * SetString;
GetStringPtr * GetString;
} IExampleVtbl;
typedef struct {
const IExampleVtbl * lpVtbl;
DWORD count;
char buffer[80];
} IExample;
No problem. Now, it’s changing to include a THIS pointer:
typedef long SetStringPtr( IExample *, char * );
typedef long GetStringPtr( IExample *, char *, long );
typedef struct {
SetStringPtr * SetString;
GetStringPtr * GetString;
} IExampleVtbl;
typedef struct {
const IExampleVtbl * lpVtbl;
DWORD count;
char buffer[80];
} IExample;
The definitions depend on each other in a circular way. The cl.exe compiler shows lots of syntax errors because by the time I use IExample it hasn’t been declared yet. How can I resolve this?
Compile with cl.exe /W4.
Update
Thanks – three moreless equivalent answers at the same time, I could have chosen any one of them.
So, to resume, what choices do you have to make when solving this problem? First, naming convention – append _t to typedefs, or _s (or Struct) to structs? Probably a matter of taste. Then, whether you want to have the forward definition as part of a typedef or as part of a struct. Probably also a matter of taste. Here’s the problem in another form and three ways to solve it:
/* won't compile */
typedef struct {
B * b;
C * c;
} A;
typedef struct {
A * a;
C * c;
} B;
typedef struct {
A * a;
B * b;
} C;
First solution:
struct B_s;
struct C_s;
typedef struct {
struct B_s * b; // typedef not available yet
struct C_s * c; // ditto
} A;
typedef struct {
A * a;
struct C_s * c; // ditto
} B;
typedef struct {
A * a;
B * b;
} C;
Second solution:
typedef struct B_s B;
typedef struct C_s C;
typedef struct {
B * b;
C * c;
} A;
// typedef struct ... B => change to:
struct {
A * a;
C * c;
} B_s;
// typedef struct ... C => change to:
struct {
A * a;
B * b;
} C_s;
And the third (and most symmetrical) solution:
struct A_s;
struct B_s;
struct C_s;
typedef struct A_s A;
typedef struct B_s B;
typedef struct C_s C;
struct {
B * b;
C * c;
} A_s;
struct {
A * a;
C * c;
} B_s;
struct {
A * a;
B * b;
} C_s;
1 Answer