问题描述
板卡有两个CPU,ARM+MIPS,同时运行三个系统REE(linux) + TEE(SierraTEE) + SEE(TDS)。TEE跟SEE通过RPC进行通信,有enum成员的结构体信息传递会出错,如下结构体:struct sTag {
enum A;
enum B;
int C;
enum D;
};
问题分析
这是由于SierraTEE和TDS使用的是不同的编译器,而enum这种结构占用内存的大小只有在编译的时候由编译器决定的。显然这是由于两个编译器对于enum的分配内存方式不一致导致的。
gcc编译选项对此有相关说明:-fshort-enums
Allocate to an enum type only as many bytes as it needs for the declared range of possible
values. Specifically, the enum type will be equivalent to the smallest integer type which
has enough room.
Warning: the -fshort-enums switch causes GCC to generate code that is not binary compatible
with code generated without that switch. Use it to conform to a non-default application
binary interface.
即若指定了-fshort-enums,编译器会分配满足需求的内存给enum即可,以节省内存;如:若打开了-fshort-enums,sizeof(struct sTag) = 12;
若不打开-fshort-enums,sizeof(struct sTag) = 16;
问题解决
从根本上,尤其是在不同CPU上要使用相同变量作为参数,更应该避免使用enum,因为其size是不能被确定的。但由于TDS中相关的头文件定义和API定义早以确定并广泛使用了,这无法修改。
只要确认两个编译器使用相同的分配策略处理enum结构,我们选择-fno-short-enums,即要求编译器不要采取节省内存的方式,把没一个enum变量都分配为int的大小。