1

How to translate the below vc++ packing commands into gcc commands in Linux? I am aware how to do it for a single struct, but how do I do this for a range of struct?

#pragma pack(push, 1) // exact fit - no padding
//structures here
#pragma pack(pop) //back to whatever the previous packing mode was
Bryan Fok
  • 3,277
  • 2
  • 31
  • 59
  • Since gcc supports the pragma pack compiler commands, we can stick with the above code. – Bryan Fok Dec 18 '12 at 06:38
  • 1
    See this too... [link](http://stackoverflow.com/questions/1537964/visual-c-equivalent-of-gccs-attribute-packed?rq=1) – NeonGlow Dec 18 '12 at 07:14
  • thx Neon, I will test my program again carefully – Bryan Fok Dec 18 '12 at 08:18
  • Common compilers will be happy with `pragma pack` including borland, digital mars, gcc. So you can keep this unless you are planning to use some less common compilers. _Target platform also matters. Hope you are on x86. Otherwise you may need more reference._ – NeonGlow Dec 18 '12 at 09:58

3 Answers3

3

You can add attribute((packed)) to individual data items to achieve this. In this case the packing is applied for a data item, so no need to restore the old mode.

Ex : For Structures :

typedef struct _MY_STRUCT
{

}__attribute__((packed)) MY_STRUCT;

For data members :

struct MyStruct {

    char c;

    int myInt1 __attribute__ ((packed));

    char b;

    int myInt2 __attribute__ ((packed));

};
Frohman
  • 111
  • 11
NeonGlow
  • 1,659
  • 4
  • 18
  • 36
1

gcc also supports those pragmas. See the compiler docs at: http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html

alternatively you could use the more gcc-specific

__attribute__(packed)

example:

struct foo {
  int16_t one;
  int32_t two;
} __attribute__(packed);

http://gcc.gnu.org/onlinedocs/gcc-3.3.6/gcc/Type-Attributes.html

1

According to http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html, gcc should support #pragma pack directly, so you can use it directly as is.

The gcc way of specifying alignment is __attribute__((aligned(x))), where x is required alignment.

You can also use __attribute__((packed)) to specify tightly packed struct.

Refer to http://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Type-Attributes.html

v154c1
  • 1,698
  • 11
  • 19