如何使用另一个 C 文件中的结构中的数据?
我在 Main.c 中定义了一个结构“数据”。
我想在另一个文件 app.c
的函数中使用此结构的值。
请建议如何执行此操作。
I have defined a structure "data" in Main.c
.
I want to use the values of this structure in a function of another file app.c
.
Please suggest how to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设您问的是“c”而不是“c#”,因为您的问题指的是“.c”文件而不是“.cs”文件等:
创建一个头文件并将结构放在那里。
在 Main.c 和 app.c 中包含头文件
I assume you are asking about "c" and not "c#" since your question refers to ".c" files and not ".cs" files, etc:
Make a header file and put the struct there.
Include the header file in both Main.c and app.c
通常,您将函数原型定义到受包含防护保护的头文件中:
当不同文件需要包含相同的标头时,包含防护可以防止某些包含冲突。他们保证它只会被包含一次。
然后,您可以将该标头包含到具有 c 扩展名的文件中,该文件实现了定义的原型:
通常每个标头文件都有关联的 ac 文件(这不是强制性的;这是一个约定)。如果您只需要定义结构,您甚至可以不需要与标头关联的 C 文件。如果您还需要实现一些函数原型,那么这是组织代码的好方法。
然后将头文件包含在需要在其中定义的函数或结构的每个其他文件中:
现在可以编译并链接这两个文件(prototype.c、otherfile.c)
Usually you define a function prototype into a header file protected with include guards:
Include guards prevent some including conflicts when different files need to include the same header. They guarantee it will be included only once.
Then you can include that header into a file with c extension that implement the defined prototypes:
Usually every header file has a c file associated (that's not mandatory; it's a convention). If you need only to define structure you can even not need a C file associated with the header. If you have also some function prototypes to implement, that's a good way to organize your code.
Then include the header file in every other file that need the functions or structures defined inside it:
Now it's possible to compile and link together both files (prototype.c, otherfile.c)
既然你说你想在不同的源文件中重用结构的值,我假设你在 main.c 中定义了结构类型的变量,如下所示:
如果你想在 app.c 中使用相同的 foobar,你必须声明该变量也存在,加上 extern:
Since you say you want to reuse the values of the structure in a different source file I assume you defined a variable of your structure type in main.c like:
If you want to use this same foobar in app.c, you have to declare that variable there as well, with the addition extern: