3

I have been trying to look up this problem but have not found a solution that works. My compiler is ignoring #pragma pack(push) #pragma pack(2) and __ attribute __ ((aligned (2), packed)) does not solve problem as well. The stack is 8 byte aligned and want to convert some structures to be 2 byte aligned. -fpack-struct works but it affects all structures.

I would like to use #pragma pack.

I am programming a xilinx microblaze in SDK 13.3 eclipse IDE GCC #4.1.2

I guess I dont understand what is making the compiler ignore the Pragma pack.. I dont want to turn the warnings off I would like to use it.

#pragma pack(push)
#pragma pack(2)
struct _Size_Test
{

  union
  {
    struct{
        int8    x;
        int8    y;
     };
     int16    z;
  };
}Size_Test;
#pragma pack(pop)

sizeof(Size_test) = 4 when it should be 2

adding attribute((aligned(2),packed)) does not work

struct _Size_Test
{

  union
  {
    struct{
        int8    x;
        int8    y;
     };
     int16    z;
  };
}Size_Test _attribute_((aligned(2),packed));
4

2 回答 2

0

结构大小为四个字节的原因是由于内部结构包含 x 和 y 字段。使用您指定的 2 字节打包编译指示,这些字段中的每一个都将是 2 字节对齐的,使联合中最长的成员为 4 字节长。

如果紧凑性对您很重要,则将 1 字节打包与显式填充字段结合使用。在这个特定的示例中,甚至不需要填充:

#pragma pack(push, 1)

struct _Size_Test
{
    union
    {
        struct
        {
            int8 x;
            int8 y;
        };

        int16 z;
    };
} Size_Test;

以下代码段显示了显式填充如何工作:

#pragma pack(push, 1)

struct _Size_Test
{
    union
    {
        struct
        {
            int8 x;
            int8 pad1;
        };

        int16 z;
    };
} Size_Test;
于 2013-03-19T19:36:26.293 回答
0

你可以为你的结构使用这样的东西:

struct __packed__
{
    char* member_one;
    int *member_two;
    .... 
} my_struct;

您还可以尝试使用以下方法抑制标准对齐:

int *__unaligned my_int_pointer;

希望这有帮助。

问候。

于 2012-08-04T00:27:57.377 回答