Gcc: accessing and initializing unions and bitfields within a struct

I have a structure consisting of union, variable and bitfield:

typedef struct router_client {
    union {
        QHsm  *client;
        void (*handler)(QSignal sig, QParam par);
    };
    uint8_t level;
    struct {
        uint8_t presence:2;
        uint8_t is_hsm:1;
        uint8_t is_handler:1;
    };
} router_client_t;

      

What is the correct way to initialize it? I used

router_client_t = {.client=(QHsm*)&qhsm_foo, level = l, \
.presence = p, .is_hsm = s, .is_handler = a}

      

But when switching toolchain from Code Red MCU tools to Cross GCC I started getting

unknown field 'client' specified in initializer
unknown field 'presence' specified in initializer
...

      

The merge point is that I want to be able to assign values ​​to either the client or the handler and let them use the same pointer. I've tried a few things and I know I can change the structure, but I just wanted to know if there is a way to initialize and access it in C99.

+3


source to share


2 answers


It might work. I think the trick is the name structs and union.

typedef union {
    int  *client;
    void (*handler)(int sig, int par);
}union_t;

typedef struct {
    uint8_t presence:2;
    uint8_t is_hsm:1;
    uint8_t is_handler:1;
}struct_t;

typedef struct router_client {
    union_t test;
    uint8_t level;
    struct_t test2
} router_client_t;

void main()
{
    int pippo;
    router_client_t pippo2= {.test.client=(int*)&pippo, .level = 10, .test2.presence = 2, .test2.is_hsm = 1, .test2.is_handler = 1};
}

      



Or as you wrote:

#include <stdint.h>

typedef struct router_client {
    union{
        int  *client;
        void (*handler)(int sig, int par);
    }union_t;
    uint8_t level;
    struct {
        uint8_t presence:2;
        uint8_t is_hsm:1;
        uint8_t is_handler:1;
    }struct_t;
} router_client_t;

void main()
{
    int pippo;
    router_client_t pippo2= {.union_t.client=(int*)&pippo, .level = 10, .struct_t.presence = 2, .struct_t.is_hsm = 1, .struct_t.is_handler = 1};
}

      

+3


source


I see an unnamed structure and an unnamed union.

It is very likely that the cross gcc compiler does not handle anonymous structures and unions with what was ever the default standard.



suggest adding an appropriate compiler, something like

'-std=c11'

      

+2


source







All Articles