Reputation: 2597
I am writing code for an ATSAM device using XC32 from Microchip (not clear to me if C99 or C11).
This code works fine:
typedef union {
struct {
uint16_t bit1 : 1;
uint16_t bit2 : 1;
// .. MUCH more lines...
};
struct {
uint32_t data[N];
// ... more lines, with sub-structures....
};
} Context_t;
Context_t c;
c.data[0] = 1;
c.bit2 = false;
Notice both anonymous structures.
Since both structures are large, change all the time and their code are generated automatically by other script, it would be more convenient to use them like this:
// bit.h
typedef struct {
uint16_t bit1 : 1;
uint16_t bit2 : 1;
// .. MUCH more items...
} Bits_t;
// data.h
typedef struct {
uint32_t data[N];
// ... more code...
} Data_t;
// import both headers
typedef union {
Bits_t;
Data_t;
} Context_t;
Context_t c;
c.data[0] = 1;
c.bit2 = false;
This fails to build with compiler saying declaration does not declare anything
for both lines inside union. That sounds fair to me.
If I name them like bellow it works, but final code will be forced to be aware of this change in structure. Not good for our application.
typedef union {
Bits_t b;
Data_t d;
} Context_t;
Context_t c;
c.d.data[0] = 1;
c.b.bit2 = false;
I assume I am the culprit in here and failing example is failing due to me declaring the union the wrong way.
Any tip are welcome!
Upvotes: 5
Views: 134
Reputation: 223689
You can take advantage of the fact that include files are essentially copied-and-pasted into the source files that include them to do what you want.
If you have bit.h consist only of this:
struct {
uint16_t bit1 : 1;
uint16_t bit2 : 1;
// .. MUCH more items...
};
And data.h only of this:
struct {
uint32_t data[N];
// ... more code...
};
Then you can create your union like this:
typedef union {
#include "bits.h"
#include "data.h"
} Context_t;
Allowing the two internal struct to both be anonymous and to be generated externally without having to touch the module where Context_t
is defined.
Upvotes: 5