I have these two structures...
typedef struct{
MY_SECOND_STRUCT s1;
}MY_FIRST_STRUCT;
typedef struct{
int s1;
}MY_SECOND_STRUCT;
I prefer this order, I dont want to switch them. But compiler dont know MY_SECOND_STRUCT at the momen开发者_开发技巧t and I get error
error: expected specifier-qualifier-list before 'MY_SECOND_STRUCT'
I´ve tried add declaration to the top
struct MY_SECOND_STRUCT;
also change definition to
typedef struct{
struct MY_SECOND_STRUCT s1;
}MY_FIRST_STRUCT;
but it didnt help.
I prefer this order, I dont want to switch them.
You have to switch them.
If MY_FIRST_STRUCT
has a member variable of type MY_SECOND_STRUCT
then MY_SECOND_STRUCT
must be defined and complete (not just declared and incomplete) before the definition of MY_FIRST_STRUCT
.
That order is not possible. You have to switch them.
However, if you declare the member as pointer, then switching is not required:
struct MY_SECOND_STRUCT; //forward declaration is required though
typedef struct{
MY_SECOND_STRUCT * s1; //now its a pointer
}MY_FIRST_STRUCT;
Or, in C++ you can use template as:
template<typename MY_SECOND_STRUCT>
struct MY_FIRST_STRUCT_T
{
MY_SECOND_STRUCT s1;
};
struct MY_SECOND_STRUCT
{
int s1;
};
And when you want to use MY_FIRST_STRUCT
, just use this typedef
:
typedef MY_FIRST_STRUCT_T<MY_SECOND_STRUCT> MY_FIRST_STRUCT;
Use MY_FIRST_STRUCT
now. :-)
At the time you cerate your first struct the compiler hasn't come across the second struct yet. It needs to know how bit MY_SECOND_STRUCT
is because at that time it needs to decide how big to make MY_FISRT_STRUCT
and how to lay out the memory for it. Simply forward declaring struct MY_FIRST_STRUCT
is not enough, that doesn't tell the compiler about the size or contents of the struct. Forward declaring would work if you were using a pointer to a struct, but it's not enough when trying to include the actual structure.
Your only real options are to move MY_SECOND_STRUCT
up above MY_FIRST_STRUCT
or to make MY_FIRST_STRUCT
takes a pointer. It might seem strange at first, but there's not much that can be done about it.
精彩评论