Search code examples
cstructarmembeddedanonymous

C global anonymous struct / union


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 variable with two uint32 variables in C, using anonymous structures in the hope of avoiding pointer arithmetic to access members.

Is what I am trying to do possible? It could be that using a named union is just as fast, but now I'm just intrigued if it can be done without. The following does not compile successfully:

http://goo.gl/ejx37y

#include <stdint.h>

volatile union {
  uint64_t ab;
  struct { uint32_t a, b; };
};

int main(void)
{
  a = 1;
};

Solution

  • 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;