Why can this type not be resolved?

可紊 提交于 2021-02-10 18:46:26

问题


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?


回答1:


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.




回答2:


The declaration typedef struct mb32_packet_t ... mb32_packet_s; makes mb32_packet_t a tag that only works after the keyword struct and makes mb32_packet_s a type name that works on its own. To make mb32_packet_t a type name, swap them in the declaration or use mb32_packet_t in both places.




回答3:


In your typedef struct... code, the mb32_packet_t is a structure tag, not the name of the defined type, which is mb32_packet_s. You can use the tag in a variable declaration, but only if you also include the struct keyword.

To declare a variable of the type without the struct keyword, you need to use the type's actual name, as follows:

mb32_packet_s packet; // Note the "_s" rather than "_t" and the end.


来源:https://stackoverflow.com/questions/60487844/why-can-this-type-not-be-resolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!