C global anonymous struct / union

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

    You define a union without an instance, which means that there is no union object containing the members. You could probably do something like this:

    main.h:

    typedef union {
      uint64_t ab;
      struct { uint32_t a, b; };
    } u_t;
    
    extern u_t u;
    

    main.c:

    u_t u = { .a = 1; };
    

    And if you really wanted to (in main.h):

    #define a u.a
    #define b u.b
    #define ab u.ab
    

    If you do use #defines, be wary that they affect any declaration/use of the identifiers (a, b, ab), even those in a different scope. I recommend that instead you just access the values explictly via the u object (as u.a, u.b, u.ab).

    I have removed volatile from the declarations because I highly doubt you really needed it. But you can certainly add it back if you wish.

    (Note: the question originally had code split across two files, main.h and main.c. My answer correspondingly has code for two files. However, these could be combined into one easily).

提交回复
热议问题