我有這個示例代碼,當我嘗試修復其中一個 GCC 警告時會引發錯誤
#include <stdint.h>
//
typedef union someStruct
{
uint64_t All;
struct
{
uint64_t Foo : 40;
uint64_t Bar : 24;
} Field;
} someStruct;
#define bits_64 ((uint64_t)(-1))
//
typedef union bits
{
uint64_t oneBit: 1;
uint64_t twoBits: 2;
uint64_t threeBits: 3;
uint64_t fourBits: 4;
uint64_t fiveBits: 5;
uint64_t sixBits: 6;
uint64_t sevenBits: 7;
uint64_t fourtyBits: 40;
uint64_t All;
} bits;
#define bits_40 (((bits)(-1)).fourtyBits)
//
int main()
{
someStruct x;
someStruct y;
x.Field.Foo = bits_64; //-Woverflow warning
//trying to fix the warning with using the bits union
y.Field.Foo = bits_40; // but this throws the error msg below
/*
<source>:30:19: error: cast to union type from type not present in union
30 | #define bits_40 (((bits)(-1)).fourtyBits)
| ^
*/
return 0;
}
如何使用聯合來定義任意數量的位并將其分配給任何結構欄位?
PS 我不能使用列舉和/或定義聯合變數;我必須以這種方式使用宏來適應代碼庫。
uj5u.com熱心網友回復:
你#define的 forbits_40應該是這樣的:
#define bits_40 (((bits){.All = -1)).fourtyBits)
你也可以這樣做:
#define bits_40 ((1ULL << 40) - 1)
并完全跳過bits結構。或者你可以定義一個BIT_MASK宏如下:
#define BIT_MASK(bits) ((1uLL << bits) - 1)
:
:
x.Field.Foo = BIT_MASK(40);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448230.html
