假如有这份代码:
struct device_config {
unsigned int device1_enable; /* 设备1的使能信息 */
unsigned int device2_enable; /* 设备2的使能信息 */
unsigned int device3_enable; /* 设备3的使能信息 */
unsigned int device4_enable; /* 设备4的使能信息 */
unsigned int device1_type; /* 设备1的类型 */
unsigned int device2_type; /* 设备2的类型 */
unsigned int device3_type; /* 设备3的类型 */
unsigned int device4_type; /* 设备4的类型 */
}__attribute__((packed));
struct device_config device_cfg;
/* device_cfg这个结构体变量是存放在EEPROM和FLASH等存储设备中的,每次上电MCU都会读取FLASH或EEPROM中的数据到改结构体中*/
假如现在需要往device_config中加入一个 设备5的使能信息这个成员。
代码如下,那么就会出现一个问题,现在的device_config结构体比以前的要大了。假如device_config的紧连着的地址处有其他的代码。那么加入这个会出现
数据错乱的问题。
struct device_config {
unsigned int device1_enable; /* 设备1的使能信息 */
unsigned int device2_enable; /* 设备2的使能信息 */
unsigned int device3_enable; /* 设备3的使能信息 */
unsigned int device4_enable; /* 设备4的使能信息 */
unsigned int device5_enable; /* 设备5的使能信息 */ /* new add的 */
unsigned int device1_type; /* 设备1的类型 */
unsigned int device2_type; /* 设备2的类型 */
unsigned int device3_type; /* 设备3的类型 */
unsigned int device4_type; /* 设备4的类型 */
}__attribute__((packed));
上面的问题归类到底还是代码可维护性的问题,为了解决上述问题,我们应该在开始设计这个结构体的时候,加入保留字节。
代码如下
struct device_config {
unsigned int device1_enable; /* 设备1的使能信息 */
unsigned int device2_enable; /* 设备2的使能信息 */
unsigned int device3_enable; /* 设备3的使能信息 */
unsigned int device4_enable; /* 设备4的使能信息 */
unsigned char reserved_1[50]; /* 保留 */
unsigned int device1_type; /* 设备1的类型 */
unsigned int device2_type; /* 设备2的类型 */
unsigned int device3_type; /* 设备3的类型 */
unsigned int device4_type; /* 设备4的类型 */
}__attribute__((packed));
那么再加入 设备信息5这个成员5的时候就很方便的修改代码了。
struct device_config {
unsigned int device1_enable; /* 设备1的使能信息 */
unsigned int device2_enable; /* 设备2的使能信息 */
unsigned int device3_enable; /* 设备3的使能信息 */
unsigned int device4_enable; /* 设备4的使能信息 */
unsigned int device
unsigned char reserved_1[50 - 4]; /* 保留 */
unsigned int device1_type; /* 设备1的类型 */
unsigned int device2_type; /* 设备2的类型 */
unsigned int device3_type; /* 设备3的类型 */
unsigned int device4_type; /* 设备4的类型 */
}__attribute__((packed));