如何从另一个源文件使用定义的结构?

我使用Linux作为我的编程平台和C语言作为我的编程语言。

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

struct test_st { int state; int status; }; 

所以我想要这个结构在我的其他源文件(例如othersrc)中使用。 是否有可能在另一个源文件中使用这个结构而不把这个结构放在一个头文件中?

谢谢

您可以在其他othersrc.c使用指向它的指针,而不包含它:

othersrc.c:

 struct foo { struct test_st *p; }; 

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

main.h:

 struct test_st { int state; int status; }; 

main.c中:

 #include "main.h" 

othersrc.c:

 #include "main.h" 

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

您可以在每个源文件中定义结构,然后将该实例变量声明为全局变量,并将其作为一个外部变量:

 // File1.c struct test_st { int state; int status; }; struct test_st g_test; // File2.c struct test_st { int state; int status; }; extern struct test_st g_test; 

链接器然后将做的魔术,两个源文件将指向相同的变量。

但是,复制多个源文件中的定义是一种不好的编码习惯,因为在更改的情况下,您必须手动更改每个定义。

简单的解决方案是将定义放在头文件中,然后将其包含在使用该结构的所有源文件中。 要通过源文件访问结构的同一个实例,仍然可以使用extern方法。

 // Definition.h struct test_st { int state; int status; }; // File1.c #include "Definition.h" struct test_st g_test; // File2.c #include "Definition.h" extern struct test_st g_test; 

把它放在一个头文件中是声明源文件之间共享类型的正常方法。

除此之外,你可以将main.c作为头文件并将其包含在另一个文件中,然后只编译另一个文件。 或者你可以在这两个文件中声明相同的结构,并给自己留下一个提示,以在两个地方改变它。

C支持单独编译 。

把结构声明放到一个文件中, #include "..."在源文件中。

 // use a header file. It's the right thing to do. Why not learn correctly? //in a "defines.h" file: //---------------------- typedef struct { int state; int status; } TEST_ST; //in your main.cpp file: //---------------------- #include "defines.h" TEST_ST test_st; test_st.state = 1; test_st.status = 2; //in your other.ccp file: #include "defines.h" extern TEST_ST test_st; printf ("Struct == %d, %d\n", test_st.state, test_st.status); 

别名TEST_ST我相信成为没有typeof的全球性,从而让您访问其结构。 对不起,如果我错了。

头文件/ *在file1.c和file2.c中都包含这个头文件

 strcut a { }; struct b { }; 

所以头文件包含了两个结构的声明。

 file 1.c 

strcut a xyz[10]; – >这里定义一个struct

在这个文件中使用struct b

 extern struct b abc[20]; /* now can use in this file */ 

file2.c中

 strcut b abc[20]; /* defined here */ 

使用file1.c中定义的strcut

 use extern struct a xyz[10]