Reputation: 11
i'm currently working on a Port of Embedded Code (on a Freescale S12) so GNU and i hava a issue with unions. i have the following union
typedef signed short sint16;
typedef signed long sint32;
typedef union
{
sint32 Akku;
sint16 AkkuHigh;
sint16 AkkuLow;
} akku_type;
and i want to access the highest 2 byte of the union. The Problem is, that both AkkuHigh and AkkuLow have the same starting adress as Akku. It seems to be compiler specific. My Questions are: Is the there a Compiler Flag which changes the behaviour of the union? Can atribute((align (2))) help me?
Thank you in Advance
Upvotes: 0
Views: 121
Reputation: 72425
The correct definition of the union can be found in this answer.
atribute(align(2))
will definitely help you if you compile this on a 32bit or 64bit architecture. Also, on 64bit sizeof(sint32)
is 8
(64 bits).
Depending on the endian-ness of the architecture, you may need to swap AkkuHigh
and AkkuLow
.
Upvotes: 0
Reputation: 80355
Yes, all of Akku
, AkkuHigh
, AkkuLow
have the same address. This is how unions work in C. By the look of it, you intended to make an union with a 32-bit member and a member that is a struct of two 16-bit members instead. What you wrote is not the way to achieve it. Try instead:
typedef union
{
sint32 Akku;
struct s {
sint16 AkkuHigh;
sint16 AkkuLow;
} representation;
} akku_type;
Upvotes: 3