Reputation: 71
I am trying to port some old code over from a 20 year old DOS system to a GNU Linux system. In several of their header files, (which are included all over the place), they have structs of structs that they declare and initialize. I am getting warnings when I compile with the way the legacy code was written. Any tips on how I can get this to work with staying inside the same header file?
The following is a simplified example I made of what they are doing.
struct A
{
struct B temp1;
struct C temp2;
};
struct B
{
int temp3;
int temp4;
int temp5;
};
struct C
{
int temp6;
int temp7;
int temp8;
};
//These are the variables in how they are related to the initialization below
//struct A test_one = {{temp3,temp4,temp5},{temp6,temp7,temp8}};
struct A test_one = {{1,2,3},{4,5,6}};
Upvotes: 4
Views: 23073
Reputation: 7466
You shouldn't instantiate any structures in header files. If you do a different instance will be created in each C file you include the header in which is usually not the desired effect.
In a C file to do this you would have to do the following.
void foo(){
struct A parent;
struct B child_b;
struct C child_c;
child_b.temp3 = 3;
child_b.temp4 = 4;
child_b.temp5 = 5;
child_c.temp6 = 6;
child_c.temp7 = 7;
child_c.temp8 = 8;
parent.temp1 = child_b;
parent.temp2 = child_c;
}
I would strong consider making helper functions similar to this
void initB(struct B* s, int x, int y, int z){
s->temp3 = x;
s->temp4 = y;
s->temp5 = z;
}
If you would like the keep the array initialization syntax then consider using a union.
Upvotes: 6
Reputation: 320381
The code you posted is not compilable, since it is illegal to use incomplete type to declare struct
members. I assume that you simply misarranged your struct
definitions: the definitions for B
and C
should go first.
Having said that, the only warning this code can generate is the "warning" from linker that might complain about multiple definitions of the same object test_one
, if the header file is included in multiple translation units. In C this is technically illegal, although many compilers allow it as a popular compiler extension.
So, what "warnings" are you getting?
Upvotes: 0
Reputation: 1189
Declare struct B and C before A, i.e. :
struct B { int temp3; int temp4; int temp5; };
struct C { int temp6; int temp7; int temp8; };
struct A { struct B temp1; struct C temp2; };
Upvotes: 1