我有一个AVR程序,它将一组(通常小于8)位标志存储在一个静态状态变量中(它包含在一个包含模块的各种其他状态字段的结构中)。
如果这样做或多或少有效率:

#define STATUS_ENABLED 0x01

struct DeviceState {
    uint8_t status;
}

static struct DeviceState myState;

//and somewhere in the program...
myState.status |= STATUS_ENABLED;

或者使用压缩位字段:
struct DeviceState {
    uint8_t enabled : 1;
}

static struct DeviceState myState;

//and somewhere in the program...
myState.enabled = 1; // could use TRUE/FALSE if defined

最佳答案

对于avr gcc 4.3.3,在实现上似乎没有区别:

#define STATUS_ENABLE

struct DeviceState {
    uint8_t status;
    uint8_t enabled : 1;
}

static struct DeviceState myState;

//and this code...
myState.status |= STATUS_ENABLED;
myState.enabled = 1;

生成以下程序集代码:
    myState.status |= STATUS_ENABLE;
00003746  LDS R24,0x20B5            Load direct from data space
00003748  ORI R24,0x01              Logical OR with immediate
00003749  STS 0x20B5,R24            Store direct to data space

    myState.enabled = TRUE;
0000374B  LDS R24,0x20B4            Load direct from data space
0000374D  ORI R24,0x01              Logical OR with immediate
0000374E  STS 0x20B4,R24            Store direct to data space

所以同样的指示(除了地址!).

08-16 14:17