【问题标题】:Extern typedefs in CC中的外部类型定义
【发布时间】:2013-01-20 11:17:34
【问题描述】:

我有 4 个文件:

啊哈:

typedef struct {
    int a;
} A;

b.h:

#include "a.h"
typedef struct {
    A a;
    int b;
} B;

c.h:

#include "a.h"
typedef struct {
    A a;
    double c;
} C;

直流电:

#include "b.h"
#include "c.h"
//Here I want to use types A, B and C

int 和 double 只是示例,我遇到的真正问题要复杂得多。
关键是应该可以通过简单的转换将类型 B 和 C 转换为 A。
我要解决的问题是它说 A 类型被多次包含,这是可以理解的,因为 d.c 包含 b.h 包含 a.h,但 a.h 也包含在 c.h 中。
有没有办法做到这一点?

【问题讨论】:

  • 您正在寻找“包括警卫”。
  • 投射?除非你喜欢切片。您可能需要考虑使用包含保护,因为您似乎没有循环引用,所以这应该可以解决而无需花哨。
  • 不,我已经阅读了stackoverflow.com/questions/3227654/… 上的问题,但无法真正弄清楚如何在我的代码中实现这一点。

标签: c include typedef


【解决方案1】:

啊。

#ifndef A_H_INCLUDED
#define A_H_INCLUDED
typedef struct {
    int a;
} A;
#endif

b.h

#ifndef B_H_INCLUDED
#define B_H_INCLUDED
#include "a.h"
typedef struct {
    A a;
    int b;
} B;
#endif

c.h

#ifndef C_H_INCLUDED
#define C_H_INCLUDED
#include "a.h"
typedef struct {
    A a;
    double c;
} C;
#endif

d.c

#include "a.h" // if you're going to use type A specifically do #include the proper file
#include "b.h"
#include "c.h"
//Here I want to use types A, B and C

【讨论】:

    【解决方案2】:

    使用包含守卫,如下所示:

    #ifndef A_INCLUDED
    #define A_INCLUDED
    typedef struct {
      int a;
    } A;
    #endif
    

    在每个 .h 文件中,每个文件都有唯一的保护名称

    【讨论】:

    • 感谢您的回答。这个 ifndef、define 和 endif 到底是做什么的? (我用谷歌搜索,但我并没有真正找到答案......)编辑:哦,太愚蠢了 - 在维基百科上找到:en.wikipedia.org/wiki/Include_guard;谢谢大家的帮助!!!
    • 不客气,请接受其中一个答案来解决您的问题
    猜你喜欢
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多