c - GBDK C 中 typedef 结构的前向声明

标签 c struct typedef gameboy gbdk

我正在使用 GBDK C 为原版 Game Boy 创建游戏,但遇到了一个小问题。我游戏中的每个房间都需要有不同的 portal,但每个 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 ***

最佳答案

重新排序定义并为 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];
};

关于c - GBDK C 中 typedef 结构的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33059819/

相关文章:

c++ - 二维结构类型数组,我做错了什么?

c++ - 发送新类型作为参数

c++ - 将 typedef 制作为文件或子类的本地文件

c - C 语言中的句子反转?

objective-c - 初始化 C 结构数组 - Objective C - OpenGLES

java - 关于else if实现的问题

c++ - 比较来自外部 API 的相同类型的两个结构

c++ - Typedef Student 不工作

iphone - 在 Objective-C 类之间共享 C 函数

c - 使用 for 循环从数组中删除对象