sizeof for extern struct

C

CptDondo

I've got a question on the proper handling of sizeof.

I have two files; a.c and b.c

In b.c I have:

struct Key en_keys[] = {
{EN_ENTER, DELAY, NULL},
};

in a.c I have

extern struct Key en_keys[];

and later, in a.c I do

foo = sizeof(en_keys);

Of course the compiler promptly pukes since sizeof is computed at
compile time and it doesn't know the size until link time....

So - what's the proper / recommended / sensible way to deal with this?
The number of elements in en_keys[] could change and I really don't want
to have to redo all of the size info.
 
P

Punkie

afaik you cant have the sizeof value at compile time because it is in
another code unit.

If you dont really need the exact value at compile time:
b.c
int theSize = sizeof(en_keys);
a.c
extern int theSize;
Typically you dont use the value, unless you use it for eg template
parameter instantiation..


Or duplicate the struct def in a.c
As long as they are idential it should be fine. Just dont try to compare the
types.
 
I

Ian Collins

CptDondo said:
I've got a question on the proper handling of sizeof.

I have two files; a.c and b.c

In b.c I have:

struct Key en_keys[] = {
{EN_ENTER, DELAY, NULL},
};

in a.c I have

extern struct Key en_keys[];

and later, in a.c I do

foo = sizeof(en_keys);

Of course the compiler promptly pukes since sizeof is computed at
compile time and it doesn't know the size until link time....

So - what's the proper / recommended / sensible way to deal with this?
The number of elements in en_keys[] could change and I really don't want
to have to redo all of the size info.

Either add an extern const variable for the number of keys, or if the
the array is built at run time, end it with a NULL, as you appear to be
doing.
 
I

Ian Collins

Punkie wrote:

Please retain the context of the thread you are replying to.
afaik you cant have the sizeof value at compile time because it is in
another code unit.

If you dont really need the exact value at compile time:
b.c
int theSize = sizeof(en_keys);

The type of sizeof is size_t.
a.c
extern int theSize;
Typically you dont use the value, unless you use it for eg template
parameter instantiation..
This is C....
Or duplicate the struct def in a.c
As long as they are idential it should be fine. Just dont try to compare the
types.

Not a good idea, one then has to maintain two or more copies of the same
array.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top