Search code examples
cstructtypedefgameboygbdk

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. Each room in my game needs to have different portals, but each portal needs to reference a room. 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; 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 ***

Solution

  • Reorder the definitions and write a forward declaration for the Room and Portal types:

    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.

    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;

    If for some reason you cannot use the same identifier for the struct tag and the typedef, you should declare the structures this way:

    typedef struct Room_s Room;
    typedef struct Portal_s Portal;
    
    struct Portal_s {
        Room *destinationRoom;
    };
    
    struct Room_s {
        Portal portals[10];
    };