FLASH和EEPROM存储配置设备信息时可考虑代码可 维护性问题。

假如有这份代码:

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));

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值