Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to nest global structure variables?

Status
Not open for further replies.

alchemista

Programmer
Aug 16, 2002
5
GB
Hello, I'm trying to declare some global variables that are structures. However, some of them have nested structures and the compiler complains that the initializer is not a constant type. I thought this may be because the compiler may pad a structure, however it should be able to know this when compiling. Also, I tried using the -fpack-struct option of gcc and still I get the same error. Here's a sample of what I'm trying to do:

typedef struct {
float a;
float b;
} struct1_t;

static struct1_t NULL_STRUCT = {0.0, 0.0};

typedef struct {
float a;
struct1_t b;
} struct2_t;

static struct2_t NULL_STRUCT2 = {0.0, NULL_STRUCT};

However, this will not work. I get initializer not constant on trying to initialize the NULL_STRUCT2. How can I do such a thing in C? I'm using the gcc compiler btw.

Thanks!
 
One work-around will be to replace the line
static struct1_t NULL_STRUCT = {0.0, 0.0};
with
#define NULL_STRUCT {0.0, 0.0 }

cheers
amit
crazy_indian@lycos.com

to bug is human to debug devine
 
I did think about that except for that if I then want to do some normal assignments, I don't think it'd work?

For example...

struct1_t a;

a = NULL_STRUCT;

or would that always work?

Thanks for the reply.
 
a = NULL_STRUCT;
will always work as it will be handled by
the main C compiler

static struct2_t NULL_STRUCT2 = {0.0, NULL_STRUCT};
wont work as it is expanded by the preprocessor.

cheers
amit
crazy_indian@lycos.com

to bug is human to debug devine
 
The NULL_STRUCT defined this way:
Code:
static struct1_t NULL_STRUCT = {0.0, 0.0};
is NOT a constant, it is a variable (so your compiler complains).

I would use:
Code:
#define NULL_STRUCT_INIT {0.0, 0.0}
const static struct1_t NULL_STRUCT = NULL_STRUCT_INIT;
This way you can use NULL_STRUCT_INIT to initialize static variable and the NULL_STRUCT variable to use for affectations other than initializations.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top