0

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?

2
  • 1
    You need to tag the language you are using. Commented Mar 2, 2015 at 2:21
  • And also share a bit of the code you've tried. Commented Mar 2, 2015 at 2:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

so it is okay if I declare the struct before the main in every files that I need it or I can just put them in the main? @Matt McNabb
Your program must only have one main so that comment doesn't make sense
I have several files which run individual, but they only share the specific memory which is the BufferB who contains the items. @Matt McNabb
@Echo OK, as explained in my answer, you could copy-paste the itemB definition to every file but it would be safer to put it in a common file such as itemB.h and do #include "itemB.h" before main() in each program

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.