匿名结构体/联合体(#pragma anon_unions)
之所以要使用这个东西,是因为在gcc编译器中是支持匿名结构体/联合体的使用的,而在ARMCC中不支持,所以如果要在ARMCC中使用匿名的结构体/结合体,就需要使用 #pragma anon_unions 告知编译器,不然会编译不通过。匿名结构:在另一个结构中声明结构变量,而无需为其命名的嵌套结构称为匿名结构。匿名结构体/联合体指的是没有命名的结构,因为没有对应的名字,所以也不会直接创建这个对象或者
匿名结构:在另一个结构中声明结构变量,而无需为其命名的嵌套结构称为匿名结构。并且可以像访问包含结构中的成员一样访问匿名结构的成员。
匿名结构体/联合体指的是没有命名的结构,因为没有对应的名字,所以也不会直接创建这个对象或者变量,一般都是在嵌套结构中使用。
代码:
#include <stdio.h>
#include <stdint.h>
typedef union
{
struct
{
uint8_t C : 1; // Carry Bit
uint8_t Z : 1; // Zero
uint8_t I : 1; // Disable Interrupts
uint8_t D : 1; // Decimal Mode (unused in this implementation)
uint8_t B : 1; // Break
uint8_t U : 1; // Unused
uint8_t V : 1; // Overflow
uint8_t N : 1; // Negative
};
uint8_t self;
} P_t;
P_t P;
int main(void)
{
printf("P size: %d Bytes\n", sizeof(P));
P.C = 1;
printf("C: %d, P: %d\n", P.C, P.self);
P.N = 1;
printf("N: %d, P: %d\n", P.N, P.self);
return 0;
}
输出:
P size: 1 Bytes
C: 1, P: 1
N: 1, P: 129
说明:
嵌套在共用体中的结构体为匿名结构,可以直接访问其成员,比如 P.C、P.N 等;
该匿名结构体使用位域操作,每个成员仅占用一个位,共八个成员,故匿名结构体的大小为一个字节;
位域操作先定义的为低位,故 P.C 为 self 的 bit0 位,P.N 为 self 的 bit7 位,P.self = 0b1000 0001 = 129。
常规用法:
#include <stdio.h>
#include <stdint.h>
typedef union
{
struct option_n
{
uint8_t C : 1; // Carry Bit
uint8_t Z : 1; // Zero
uint8_t I : 1; // Disable Interrupts
uint8_t D : 1; // Decimal Mode (unused in this implementation)
uint8_t B : 1; // Break
uint8_t U : 1; // Unused
uint8_t V : 1; // Overflow
uint8_t N : 1; // Negative
}bit;
uint8_t self;
} P_t;
P_t P;
int main(void)
{
printf("P size: %d Bytes\n", sizeof(P));
P.C = 1;
printf("C: %d, P: %d\n", P.bit.C, P.self);
P.N = 1;
printf("N: %d, P: %d\n", P.bit.N, P.self);
return 0;
}
常规用法中,会层层递进来操作内部结构体中的变量,例如上图中的P.bit.C。
预编译指令:
#pragma anon_unions
这条指令就是告诉编译器,支持匿名结构体/联合体。
之所以要使用这个东西,是因为在gcc编译器中是支持匿名结构体/联合体的使用的,而在ARMCC中不支持,所以如果要在ARMCC中使用匿名的结构体/结合体,就需要使用 #pragma anon_unions 告知编译器,不然会编译不通过。
靠谱推荐:Free Pos,微信JOCIHEZ
更多推荐

所有评论(0)