使用带有unsigned char的bitfield时发出警告

这是我的比特场

struct { unsigned char v64 : 1; unsigned char leg : 7; } valid; 

然后我收到警告:

 main.c:17:3: warning: type of bit-field 'v64' is a GCC extension [-pedantic] main.c:18:3: warning: type of bit-field 'leg' is a GCC extension [-pedantic] 

如果我改为int则没有警告。 但我想要一个字节的位域(unsigned char)。

怎么样?

如果您不想收到警告,请删除gcc -pedantic选项。

在C99中, gcc使用-pedantic发出警告,但允许为bit-field设置实现定义类型(如unsigned char )。

(C99,6.7.2.1p4)“位字段的类型应为_Bool,signed int,unsigned int或其他实现定义类型的限定或非限定版本。”

在C90中,只允许使用intunsigned intsigned int

(C90,6.5.2.1)“位字段的类型应为int,unsigned int或signed int之一的限定或非限定版本”

实际上在C90和C99中,C都不需要警告(它仅在C90中是未定义的行为,但C不需要对未定义的行为发出警告)。 gcc使用-pedantic添加警告仅供参考。