简体   繁体   English

工会和记忆力问题

[英]Issues with union and memory aligment

i'm currently working on a Port of Embedded Code (on a Freescale S12) so GNU and i hava a issue with unions. 我目前正在嵌入式代码端口(在Freescale S12上)上工作,所以GNU和我遇到了工会问题。 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. 我想访问联合的最高2个字节。 The Problem is, that both AkkuHigh and AkkuLow have the same starting adress as Akku. 问题在于,AkkuHigh和AkkuLow的起始地址与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? Atribute ((align(2)))能帮我吗?

Thank you in Advance 先感谢您

Yes, all of Akku , AkkuHigh , AkkuLow have the same address. 是的,所有AkkuAkkuHighAkkuLow都具有相同的地址。 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. 这就是联合在C中的工作方式。从外观上看,您打算使用32位成员和一个由两个16位成员构成的成员进行联合。 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;

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. 如果在32位或64位体系结构上进行编译, atribute(align(2))绝对会为您提供帮助。 Also, on 64bit sizeof(sint32) is 8 (64 bits). 同样,在64位上, sizeof(sint32)8 (64位)。

Depending on the endian-ness of the architecture, you may need to swap AkkuHigh and AkkuLow . 根据架构的字节序,您可能需要交换AkkuHighAkkuLow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM