C global anonymous struct / union

前端 未结 6 1122
一个人的身影
一个人的身影 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 15:10

    It's simply not possible to do like that. A global variable (like the ones you declare in the header file) are not the same as members of an anonymous structure or union, that simply wont work.

    And having anonymous structures or unions won't help with pointer arithmetic, the structure will still sit somewhere in memory, and the compiler uses offsets from the structures base-address to find out where the members are. However, since both the base-address and member offsets are know at time of compilation, the compiler will generally be able to generate code to access the member directly, just like any other variable. Look at the generated code if you are unsure.

    So skip the nonsense with anonymous structures, define them properly in the header files, and declare variables of those structures in the header files too, while defining those variables in some source file.

    So for the header file:

    union you_union
    {
        uint64_t ab;
        struct { uint32_t a, b; };
    };
    
    extern union your_union your_union;
    

    And in a source file

    union your_union your_union;
    

提交回复
热议问题