Search code examples
cstructtypedefesp32

Why can this type not be resolved?


I have the following code in my C header file:

typedef struct mb32_packet_t {
  uint8_t compid;
  uint8_t servid;
  uint8_t payload[248];
  uint8_t checksum;
} __attribute__((packed)) mb32_packet_s;

Doing the following works:

struct mb32_packet_t packet;

When using this:

mb32_packet_t packet;

I get:

Type 'mb32_packet_t' could not be resolved
Unknown type name 'mb32_packet_t'; use 'struct' keyword to refer to the type

Isn't typedef struct intended for exactly this purpose, i.e. to be able to omit the struct keyword when defining variables of this type?


Solution

  • Your alias defined by typedef is called mb32_packet_s. So you need to use it as

    mb32_packet_s packet;
    

    or

    struct mb32_packet_t packet;
    

    You can also rename the alias to mb32_packet_t:

    typedef struct mb32_packet_t {
      uint8_t compid;
      uint8_t servid;
      uint8_t payload[248];
      uint8_t checksum;
    } __attribute__((packed)) mb32_packet_t;
    

    Then you can do both (original name without alias)

    struct mb32_packet_t packet;
    

    and (with alias)

    mb32_packet_t packet;
    

    This way, the names of both alias and the struct are identical, but technically, struct mb32_packet_t and mb32_packet_t are two different things that however refer to the same type.