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

dom*_*lao 7 c linux

我使用Linux作为编程平台,使用C语言作为编程语言.

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

struct test_st
{
   int state;
   int status;
};
Run Code Online (Sandbox Code Playgroud)

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

lor*_*ova 16

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

// 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;
Run Code Online (Sandbox Code Playgroud)

然后链接器将执行魔术,两个源文件将指向同一个变量.

但是,在多个源文件中复制定义是一种糟糕的编码习惯,因为如果发生更改,您必须手动更改每个定义.

简单的解决方案是将定义放在头文件中,然后将其包含在使用该结构的所有源文件中.要跨源文件访问结构的同一实例,您仍然可以使用该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;
Run Code Online (Sandbox Code Playgroud)

  • @kuhaku:您应该在头文件中定义结构。复制定义是一种非常糟糕的编程习惯,因为如果发生更改,您必须手动更改每个定义。 (2认同)

Mat*_*hen 13

您可以使用指针,othersrc.c而不包括它:

othersrc.c:

struct foo
{
  struct test_st *p;
};
Run Code Online (Sandbox Code Playgroud)

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

main.h:

struct test_st
{
   int state;
   int status;
};
Run Code Online (Sandbox Code Playgroud)

main.c中:

#include "main.h"
Run Code Online (Sandbox Code Playgroud)

othersrc.c:

#include "main.h"
Run Code Online (Sandbox Code Playgroud)

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


小智 5

// 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);
Run Code Online (Sandbox Code Playgroud)