多个文件的结构

时间:2012-08-23 22:59:48

标签: c struct

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

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

然后在GlobalStruct包含globalstruct.h

的任何地方使用//test.c #include globalstruct.h void test(GlobalStruct *gs){...}

例如:

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

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

我该怎么做?

此致

---- ---- EDIT

我想我需要澄清一点问题,因为我完全陷入困境。

//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

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

BTW,我正在使用{{1}}

进行编译

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

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

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

2 个答案:

答案 0 :(得分:4)

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

  1. 在include指令中添加引号:

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

  3. 您不得使用下划线 - 资本名称,因为这些名称是保留的。而是使用类似的东西:

    typedef struct GlobalStruct_struct { /* ... */ } GlobalStruct;
    
  4. (感谢@chris发现第2号!)

答案 1 :(得分:2)

在头文件中,#ifdef应为#ifndef