Echo
Echo

Reputation: 11

struct as global variable

so if we declare and define a struct before main and want to use this struct in other file which are in the same root as this one, do we need to declare it again in that file? Especially I want to share the memory of a array whose element is the struct so I need to use the shm_get in another file, do I need to declare those struct again?

btw, is it in C

code will be like this:

 typedef struct {
 char y1;
 char y2;
 char y3;
 int x;
 } itemB;

int main(){...
itemB* BufferB;

then i share the memory

shmem2 = shm_get(542421, (void**)&BufferB, 30*sizeof(itemB));

so if i write another file which want to share the BufferB, I know should declare one more time BufferB and call the shm_get again use the same initial key, but should I declare a struct one more time? and where?

Upvotes: 0

Views: 128

Answers (1)

M.M
M.M

Reputation: 141618

The struct declaration does not have to be visible if you are only using a pointer to the struct, but it does need to be visible for sizeof(itemB) to work, or for you to be able to access any of the struct members by name.

If the struct definition is needed in multiple files then usually the definition is placed in a common file called a header which is #included from the files which need to see the definition.

It would be possible to copy-paste the definition to wherever it is needed, but that runs the risk of one definition being updated without the other definition being kept in sync, which would violate the One Definition Rule.

Upvotes: 1

Related Questions