Global define?

Go To Last Post
6 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I have a large structure in one file. Other functions in other files want to know the depth of the structure.

In the file with the structure, the depth is
#define Size = sizeof(mystruct)/sizeof(mystruct[0])
Size is only visible in this one file.

I had no way of making Size visible to all files, so I just hard coded the result of Size in a .h file that was included in all files. This finally burned me as I failed to update the value when the table grew.

How can I make the number of entries in the structure visible to all files?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

If you have a global structure, you normally have the declaration in "project.h" that is visible to every module. So you can use sizeof() in any module.c.

If you are desperate to hide data, you provide a public helper function in the single C file that contains the private declaration and definition. e.g.

int depthofmystruct(void)
{
    return sizeof(mystruct)/sizeof(mystruct[0]);
}

It sounds to me as if you want the 'number of elements' in an array of structures.
'depth' does not seem an appropriate name (to me).

David.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Clearly mystruct isn't a struct but rather an array of somethings. While the details of "something" can be hidden, consider making the array size global in a common .h file.

// in global.h
#define MAX_SOMETHINGS 64
// in hidden.h
mystruct_t mystruct[MAX_SOMETHINGS];

C: i = "told you so";

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
#define Size = sizeof(mystruct)/sizeof(mystruct[0]) 

This is an incorrect define. I bet you wanted:

#define Size sizeof(mystruct)/sizeof(mystruct[0]) 

I would use a function defined where mystruct is defined, and declared in the .h.

Regards,
Steve A.

The Board helps those that help themselves.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I suppose I could put the structure in the project.h file as suggested by david.prentice. I have a vague memory of attempting this in the past but I don't remember what the issue may have been, if any.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

If you:

typedef types foo;
foo bar;

then

sizeof(foo) == sizeof(bar)

So you could put the typedef and the sizeof(foo) in a .h with no code generation worries (oh and an "extern foo bar;" then instantiate bar in just one .c