c - 多个文件的结构

标签 c struct

我需要定义一个结构,比方说

//globalstruct.h
typedef struct _GlobalStruct {
    int a, b;
} GlobalStruct

然后只需包含 globalstruct.h

即可在任何我想要的地方使用 GlobalStruct

例如:

//test.c
#include globalstruct.h
void test(GlobalStruct *gs){...}

我该怎么做?

问候

----编辑----

我想我需要再澄清一点我的问题,因为我完全被困住了。

//main.c
#include "gstruct.h"
#include "a.h"
#include "b.h"

...
void something(GlobalStruct *gs){...}

.

//gstruct.h
#ifdef gstruct_h
#define gstruct_h
typedef struct _GlobalStruct{
    int a, b;
} GlobalStruct;
#endif

.

//a.h
#ifdef a_h
#define a_h
#include "gstruct.h"
GlobalStruct a_something(...);
#endif

.

//a.c
#include "gstruct.h"
#include "a.h"
GlobalStruct a_something(...){...}

.

//b.h
#ifdef b_h
#define b_h
#include "gstruct.h"
GlobalStruct b_something(...);
#endif

.

//b.c
#include "gstruct.h"
#include "b.h"
GlobalStruct b_something(...){...}

.

这样可以吗?因为如果是的话,我就错过了一些非常愚蠢/小/愚蠢的东西。

顺便说一句,我正在使用 gcc main.c a.c b.c -o the_thing

进行编译

---第二次编辑----

我刚刚创建了一个在线示例,您可以查看、下载并试用。 它已准备好编译,但会在编译时失败。

https://compilr.com/alexandernst/c-headers

最佳答案

你快到了。需要修复三个错误:

  1. 为包含指令添加引号:

    #include "globalstruct.h"
    
  2. 在 typedef 声明的末尾需要一个分号。

  3. 您不能使用下划线大写的名称,因为它们是保留的。而是使用类似的东西:

    typedef struct GlobalStruct_struct { /* ... */ } GlobalStruct;
    

(感谢@chris 发现了第二名!)

关于c - 多个文件的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12101167/

相关文章:

用 C 创建 ADT 集

C套接字Web服务器不在浏览器中显示html,仅发送HTTP响应

c - 可靠地计算磁盘已满时 fwrite 写入的字节数

c - 结构的第 16 个字节上的 16bit int 跳过一个字节

c - 将空值分配给指针的地址

c - 程序不会在 getch() 处暂停

c - 这个C宏是什么意思?

c - 将结构的一部分加载到另一个结构中

c - typedef 可能未声明或不明确

arrays - 在一个 slice 中解码 2 个不同的结构