【问题标题】:Forward declaration of typedef structs in GBDK CGBDK C 中 typedef 结构的前向声明
【发布时间】:2023-03-12 19:35:01
【问题描述】:

我正在使用 GBDK C 为原始 Game Boy 创建游戏,但遇到了一个小问题。我游戏中的每个房间都需要有不同的portals,但每个portal 都需要引用一个房间。这是代码的缩减版:

typedef struct {
    Portal portals[10];
} Room;

typedef struct {
    Room *destinationRoom;
} Portal;

关于如何实现这一点的任何建议?我尝试在文件顶部添加 struct Portal; 的前向声明,但没有帮助。


使用以下代码:

typedef struct Room Room;
typedef struct Portal Portal;

struct Room {
    Portal portals[10];
};

struct Portal {
    Room *destinationRoom;
};

给我这个错误:

parse error: token -> 'Room' ; column 11
*** Error in `/opt/gbdk/bin/sdcc': munmap_chunk(): invalid pointer: 0xbfe3b651 ***

【问题讨论】:

  • 注意 typedef 是完全不相关的。

标签: c struct typedef gameboy gbdk


【解决方案1】:

重新排序定义并为RoomPortal 类型编写前向声明:

typedef struct Room Room;
typedef struct Portal Portal;

struct Portal {
    Room *destinationRoom;
};

struct Room {
    Portal portals[10];
};

请注意,为了保持一致性,我将 typedef Portal 与实际的 struct Portal 定义分开,尽管这不是绝对必要的。

另请注意,这种风格与 C++ 兼容,其中 typedef 是隐式的,但可以以这种方式显式编写,或者使用简单的前向声明,如 struct Room;

如果由于某种原因您不能为struct 标记和typedef 使用相同的标识符,您应该这样声明结构:

typedef struct Room_s Room;
typedef struct Portal_s Portal;

struct Portal_s {
    Room *destinationRoom;
};

struct Room_s {
    Portal portals[10];
};

【讨论】:

  • 不幸的是,这并没有解决我的问题(见编辑)
  • @bashaus:您没有重新排序定义。 struct Portal 必须先定义,以便在定义 struct Room 时知道其大小。
  • GBDK C 要求我的 struct 和 typedef 也有不同的名称,所以我的 struct RoomStructtypedef struct RoomStruct Room
  • 不幸的是GBDK C有这样的要求,C语言为struct标签和typedef和变量名保留了单独的命名空间。 GBDK C 不再维护,所以你必须忍受它。代码现在可以编译了吗?
  • 是和否 - typedef 和结构不再是问题(这意味着问题已得到解答)。我遇到的下一个问题是关于结构内部结构的文字声明。我决定将其拆分,以便首先创建每个门户对象,然后创建房间对象。谢谢你的提问:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多