【发布时间】:2020-07-05 04:51:27
【问题描述】:
如果我所在的机器是小端,我想以某种方式typedef一个结构,如果它是大端,我想以其他方式。我试过了:
unsigned int i = 1;
char *c = (char*)&i;
if (*c)
{
/*Little endian"*/
typedef struct
{
unsigned long A : A_BIT_SIZE;
unsigned long R : R_BIT_SIZE;
unsigned long E : E_BIT_SIZE;
unsigned long funct : FUNCT_BIT_SIZE;
unsigned long opsource : OPSOURCE_BIT_SIZE;
unsigned long sourcetype : SOURCETYPE_BIT_SIZE;
unsigned long opdest : OPDEST_BIT_SIZE;
unsigned long desttype : DESTTYPE_BIT_SIZE;
unsigned long opcode : OPCODE_BIT_SIZE;
}command_byte;
}
else
{
/*Big endian"*/
typedef struct
{
unsigned long opcode : OPCODE_BIT_SIZE;
unsigned long desttype : DESTTYPE_BIT_SIZE;
unsigned long opdest : OPDEST_BIT_SIZE;
unsigned long sourcetype : SOURCETYPE_BIT_SIZE;
unsigned long opsource : OPSOURCE_BIT_SIZE;
unsigned long funct : FUNCT_BIT_SIZE;
unsigned long E : E_BIT_SIZE;
unsigned long R : R_BIT_SIZE;
unsigned long A : A_BIT_SIZE;
}command_byte;
}
它可以编译,但我不确定这是否是在 if 语句中定义结构的有效方法。我也不确定当我实际使用该结构时它是否会起作用。也会在头文件上工作吗?如果满足条件,定义结构的正确方法是什么?
【问题讨论】:
-
@kabanus 我知道在不同架构之间会损害谁,我的问题是关于 if 语句中结构的定义
-
@avigood2
#if IS_BIG_ENDIAN .... #ELSE?有些答案有这样的结构。 -
stackoverflow.com/a/9283155/6881240 有一个例子。而不是
#error定义你的结构。 -
@avivgood2 目标机器的字节序必须在 compile 时知道,因此将它放在运行时评估的
if ... else ...中没有意义.你当然不希望 same 可执行文件在 both 小端和大端机器上运行,所以这样做你总是有一块死代码为特定目标编译时从不执行。
标签: c if-statement struct typedef c89