【问题标题】:Struct for multiple files多个文件的结构
【发布时间】:2012-08-19 12:46:00
【问题描述】:

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

//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){...}

.

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

【问题讨论】:

  • 您是否尝试过您发布的示例代码?除了没有引用 #include 文件之外,它看起来还可以工作......
  • 呃...正如您在问题中所说的那样? (只记得包含守卫,typedef 末尾的分号和#include 中的引号)
  • Kerrek 谈到了如何保留结构名称。以下是更多案例的备份链接:stackoverflow.com/questions/228783/…
  • 你的一个标题中没有#endif
  • 这只是一个错字,抱歉。我的文件中确实有所有 #endif

标签: c struct


【解决方案1】:

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

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

    #include "globalstruct.h"
    
  2. 您需要在 typedef 声明的末尾使用分号。

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

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

(感谢@chris 发现 2 号!)

【讨论】:

  • 在头文件中使用GlobalStruct怎么样?我应该在 .c 或 .h 文件中包含 globalstruct.h 吗?还是两者兼而有之?
  • @alexandernst:您在头文件中定义结构,并将头文件包含在所有需要该结构的.c 文件和所有其他需要其完整类型的头文件中。跨度>
  • 好吧,我一定是做错了什么,因为我的 .h 和 .c 文件(以及我的 main.c 文件)中有 #include "globalstruct.h" 并且我仍然出现错误:未知类型名称“GlobalStruct”。有什么问题?
  • @alexandernst,您可能错过了分号:typedef struct tagStruct {...} Struct; <-
【解决方案2】:

在头文件中,#ifdef 应该是#ifndef

【讨论】:

  • 我知道我错过了一些非常愚蠢的东西,但我真的没想到 THAT !谢谢:D
猜你喜欢
  • 2016-12-12
  • 2019-02-13
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 2020-04-25
相关资源
最近更新 更多