C global anonymous struct / union

前端 未结 6 1135
一个人的身影
一个人的身影 2021-01-26 14:53

I have a uint64 variable which often only requires high or low 32 bit access. I am using a 32-bit ARM Cortex M0, and to help with speed and I am trying to overlap the uint64 var

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-26 14:59

    You could get fancy and use assembly to achieve what you want, or use C++.

    In assembly

                    EXPORT AB
                    EXPORT A
                    EXPORT B
    AB
    A               SPACE 4
    B               SPACE 4
    

    In C:

    extern uint64_t AB;
    extern uint32_t A;
    extern uint32_t B;
    

    Then do what you want.

    In C++, something like this:

    union MyUnionType
    {
        uint64_t ab;
        struct 
        {
            uint32_t a;
            uint32_t b;
        };
    } ;
    
    MyUnionType MyUnion;
    
    uint64_t &ab = MyUnion.ab;
    uint32_t &a  = MyUnion.a;
    uint32_t &b  = MyUnion.b;
    

    But, to be honest, this is all wasted effort. Accessing a or MyUnion.a is going to have the same code generated by the compiler. It knows the size and offsets of everything, so it's not going to calculate anything at runtime, but just load from the right address it knows ahead of time.

提交回复
热议问题