如何使用另一个源文件中定义的结构? [英] How to use a defined struct from another source file?

查看:113
本文介绍了如何使用另一个源文件中定义的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Linux作为我的编程平台,并使用C语言作为我的编程语言.

I am using Linux as my programming platform and C language as my programming language.

我的问题是,我在主源文件(main.c)中定义了一个结构:

My problem is, I define a structure in my main source file( main.c):

struct test_st
{
   int state;
   int status;
};

所以我希望这个结构可以在我的其他源文件(例如othersrc)中使用.是否可以在另一个源文件中使用此结构而不将其放在头文件中?

So I want this structure to use in my other source file(e.g. othersrc.). Is it possible to use this structure in another source file without putting this structure in a header?

推荐答案

您可以在othersrc.c中使用指向它的指针而无需将其包括在内:

You can use pointers to it in othersrc.c without including it:

othersrc.c:

othersrc.c:

struct foo
{
  struct test_st *p;
};

,但是否则您需要以某种方式包括结构定义.一个好的方法是在main.h中定义它,并将其包含在两个.c文件中.

but otherwise you need to somehow include the structure definition. A good way is to define it in main.h, and include that in both .c files.

main.h:

struct test_st
{
   int state;
   int status;
};

main.c:

#include "main.h"

othersrc.c:

othersrc.c:

#include "main.h"

当然,您可能会找到比main.h更好的名称

Of course, you can probably find a better name than main.h

这篇关于如何使用另一个源文件中定义的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆