1 问题: 很多时候为了节省存储空间,使用#pragma pack命令来进行数据对齐操作,但是没有细致的去判断是否支持struct递归嵌套。刚用dev c++做了验证,如下:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef struct _SYS_CONFIG_0_T
{
uint8_t flag;
uint32_t data;
}SYS_CONFIG_0_T;
#pragma pack(1)
typedef struct _SYS_CONFIG_1_T
{
uint8_t flag;
uint32_t data;
}SYS_CONFIG_1_T;
#pragma pack()
typedef struct _SYS_MANAGER_0_T
{
SYS_CONFIG_0_T cfg;
uint32_t data;
}SYS_MANAGER_0_T;
#pragma pack(1)
typedef struct _SYS_MANAGER_1_T
{
SYS_CONFIG_0_T cfg;
uint32_t data;
}SYS_MANAGER_1_T;
#pragma pack()
#pragma pack(1)
typedef struct _SYS_MANAGER_2_T
{
SYS_CONFIG_1_T cfg;
uint32_t data;
}SYS_MANAGER_2_T;
#pragma pack()
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
printf("%d\r\n",sizeof(SYS_CONFIG_0_T));
printf("%d\r\n",sizeof(SYS_CONFIG_1_T));
printf("%d\r\n",sizeof(SYS_MANAGER_0_T));
printf("%d\r\n",sizeof(SYS_MANAGER_1_T));
printf("%d\r\n",sizeof(SYS_MANAGER_2_T));
return 0;
}
2 验证:运行结果如下:
3 结论:#pragma pack并没有做递归嵌套,因此需要在每一个结构体定义时添加该预编译命令。