简体   繁体   English

在GBDK C中转发typedef结构的声明

[英]Forward declaration of typedef structs in GBDK C

I'm using GBDK C to create a Game for the original Game Boy, and I have run in to a little problem. 我正在使用GBDK C为原版Game Boy创建游戏,我遇到了一个小问题。 Each room in my game needs to have different portals , but each portal needs to reference a room. 我的游戏中的每个房间都需要有不同的portals ,但每个portal需要引用一个房间。 Here is a cut-back version of the code: 这是代码的缩减版本:

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

typedef struct {
    Room *destinationRoom;
} Portal;

Any suggestions on how to achieve this? 有关如何实现这一目标的任何建议? I tried adding a forward declaration of struct Portal; 我尝试添加struct Portal;的前向声明struct Portal; to the top of the file but it didn't help. 到文件的顶部,但它没有帮助。


Using the following code: 使用以下代码:

typedef struct Room Room;
typedef struct Portal Portal;

struct Room {
    Portal portals[10];
};

struct Portal {
    Room *destinationRoom;
};

Gives me this error: 给我这个错误:

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

Reorder the definitions and write a forward declaration for the Room and Portal types: 重新排序定义并为RoomPortal类型编写前向声明:

typedef struct Room Room;
typedef struct Portal Portal;

struct Portal {
    Room *destinationRoom;
};

struct Room {
    Portal portals[10];
};

Note that I separated the typedef Portal from the actual struct Portal definition for consistency, even though it is not strictly necessary. 请注意,我将typedef Portal与实际的struct Portal定义分开以保持一致性,即使它不是绝对必要的。

Also note that this style is compatible with C++, where the typedef is implicit but can be written explicitly this way, or with a simple forward declaration like struct Room; 另请注意,此样式与C ++兼容,其中typedef是隐式的,但可以通过这种方式显式编写,或者使用简单的前向声明(如struct Room;

If for some reason you cannot use the same identifier for the struct tag and the typedef , you should declare the structures this way: 如果由于某种原因你不能对struct标签和typedef使用相同的标识符,你应该用这种方式声明结构:

typedef struct Room_s Room;
typedef struct Portal_s Portal;

struct Portal_s {
    Room *destinationRoom;
};

struct Room_s {
    Portal portals[10];
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM