除 int 之外的其他类型的位域?
我有一个代码,它使用如下声明的位字段,
typedef struct my{
const char *name;
uint8_t is_alpha : 1;
uint8_t is_hwaccel : 1;
uint8_t x_chroma_shift;
uint8_t y_chroma_shift;
} mystr;
uint8_t
被类型定义为 unsigned char
。
使用此位字段在 MS-VS 2008 中构建代码会发出如下警告:
imgconvert.c(60) : warning C4214: nonstandard extension used : bit-field types other than int.
- 使用除 int 之外的类型的位字段时是否存在任何问题/潜在问题?为什么会出现警告?
- C99 C 语言规范是否允许除 int 类型位字段之外的其他类型?
I have a code which uses bit-fields declared as follows
typedef struct my{
const char *name;
uint8_t is_alpha : 1;
uint8_t is_hwaccel : 1;
uint8_t x_chroma_shift;
uint8_t y_chroma_shift;
} mystr;
uint8_t
is typedef'ed to unsigned char
.
Building the code in MS-VS 2008 using this bit fields gives a warning as below:
imgconvert.c(60) : warning C4214: nonstandard extension used : bit-field types other than int.
- Is there any problems/potential issues in using bit fields of type other than int? Why the warning?
- Are other than int type bit-fileds they allowed by C99 C language specification?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于位字段是低级的,因此如果您使用非标准类型,可能会出现可移植性问题。因此出现了警告——请注意,它仍然是警告而不是错误。
来自C99草案:
Since bit-fields are low-level, there may be issues with portability if you are using non-standard types. Hence the warning -- note it is still a warning and not an error.
From the draft of C99:
为什么不使用
int
?位域的实际实现因编译器而异。如果您想编写可移植代码,请使用int
。如果要创建小型结构、固定字节数的结构或位位于固定位置的结构,请不要使用位域。创建一个名为flags
的uint8_t
成员,并定义用作位掩码的宏。Why not use
int
? The actual implementation of bitfields varies from compiler to compiler. If you want to write portable code, useint
. If you want to create a small structure, or a structure of a fixed number of bytes, or a structure where the bits are in a fixed position, don't use bitfields. Create auint8_t
member called something likeflags
and define macros to use as bitmasks.正如其他人提到的有关可移植性问题等,如果您不知道,您可以通过警告杂注禁用警告:
https://learn.microsoft.com/en- us/cpp/preprocessor/warning?view=vs-2019
此外,您还可以在项目属性中禁用特定警告,但它们是项目范围内的。这样您就可以按数据类型控制它们。
然后,如果您不能 100% 确定 MSVC 将为这些生成什么样的二进制代码,请在调试器中运行它并查看“反汇编视图”(在访问它的位置进行中断),或者加载您的可执行文件(使用 PDB文件)在 IDA Pro、Ghidra 等反汇编器中。
As others have mentioned about portability issues et al, if you didn't know you can just disable the warning via the warning pragma:
https://learn.microsoft.com/en-us/cpp/preprocessor/warning?view=vs-2019
Also you can disable specific warnings in your project properties but then they are project wide. This way you can control them per data type.
Then if you are ever not sure 100% what kind of binary code MSVC will generate for these either run it in the debugger and look at the "disassembly view" (break on where it gets accessed), or load up your executable (with PDB file for symbols) in a disassembler like IDA Pro, Ghidra, etc.