简体   繁体   English

struct作为全局变量

[英]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? 因此,如果我们在main之前声明并定义一个结构,并想在与该文件位于同一根目录的其他文件中使用该结构,是否需要在该文件中再次声明它? 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? 特别是我想共享一个数组,其元素是该结构的内存,因此我需要在另一个文件中使用shm_get,是否需要再次声明那些结构?

btw, is it in C 顺便说一句,在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? 因此,如果我写了另一个要共享BufferB的文件,我知道应该再声明一次BufferB并再次使用相同的初始键来调用shm_get,但是我应该再声明一次结构吗? and where? 在哪里?

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. 如果仅使用指向该结构的指针,则该结构声明不必是可见的,但对于sizeof(itemB)起作用或通过名称可以访问任何结构成员,它必须是可见的。

If the struct definition is needed in multiple files then usually the definition is placed in a common file called a header which is #include d from the files which need to see the definition. 如果在多个文件中需要struct定义,则通常将定义放置在称为文件的通用文件中,该文件是需要查看定义的文件的#include d。

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. 可以将定义复制粘贴到需要的任何地方,但这冒着一个定义被更新而另一个定义不保持同步的风险,这将违反一个定义规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM