structs pointing to each other; compile problem
Hei!
I have defined two structure types. Each has a parameter that is a pointer to the other structure, and, of course, it does not compile. How can I come over this problem? This structure definition will result in a very efficient coding, so I would like to keep it.
Example:
typedef struct Item_s{
int param1;
int param2;
std::list<EntryList_T::iterator> entryPtrList;
}Item_T;
typedef std::list<Item_T> ItemList_T;
typedef struct Entry_s{
uint id;
ItemList_T::iterator item_iter;
}Entry_T;
typedef std::list<Entry_T> EntryList_T;
Re: structs pointing to each other; compile problem
Your answer is forward referencing.
Code:
// struct B is referenced
// this tells the compiler there is a struct B, but the compiler doesn't know
// what's in there. The compiler will resolve the content of struct B later.
typedef struct B;
typedef struct _A
{
B *ptrToStructB;
}A;
typedef struct _B
{
A *ptrToStructA;
}B;
Re: structs pointing to each other; compile problem
Hi!
Thank you for your answer, but I cannot make it work. I get en error:
error: invalid redeclaration of type name "Entry_T" (declared at line 159)
Is this compiler dependent or ..?
Re: structs pointing to each other; compile problem
Skizmo made a typing error: the forward reference should be
struct B;
(without the "typedef").
Re: structs pointing to each other; compile problem
Forward referencing will not work unless you modify your code to use pointers as shown by Skizmo.
But even if you do use pointers I believe that it will still be impossible to use *EntryList_T::interator as a template argument. In order to know that EntryList_T has an iterator the class must be previously defined - the same problem you have now.
I would suggest re-thinking the problem to see if you can come up with a more elegant design for your application's data objects.
Re: structs pointing to each other; compile problem
Hello again and thank your for your help!
But, ... I cannot make forward reference work even if I make as simple as the example your had:
struct B;
typedef struct _A
{
B *ptrToStructB;
}A;
typedef struct _B
{
A *ptrToStructA;
}B;
I still get th error:
error: invalid redeclaration of type name "B" (declared at line 159)
}B;
So, is this something with the compiler (I use Intel 9.1) or a compiler option that I should change?
Regards,
Elise
Re: structs pointing to each other; compile problem
Try removing the 'typedef' altogether. You are 'forward' defining 'B' as plain struct (telling the compiler), and then you are using typedef keyword to define B (based on _B).
Re: structs pointing to each other; compile problem
Removing typedef helps.
It compiles now.
Thank you!
Re: structs pointing to each other; compile problem