4
votes

Consider following program:

#include <iostream>
struct __attribute__((__packed__)) mystruct_A
{
   char a;
   int b;
   char c;
}x;
int main()
{
    std::cout<<sizeof(x)<<'\n';
}

From this I understood following:

  • Structure packing suppresses structure padding, padding used when alignment matters most, packing used when space matters most.
  • Structure Packing, on the other hand prevents compiler from doing padding

I am on 32 bit environment & using Windows 7 OS. The 1st answer of linked question says that above code would produce structure of size 6 on a 32-bit architecture.

But when I compiled it using g++ 4.8.1 it gives me 9 as an output. So, is structure packing not happening completely here? Why extra 3 bytes are there in output? sizeof char is always 1. Sizeof int is 4 on my compiler. So, sizeof above struct should be 1+4+1=6 when structure is packed.

I tried it on here. It gives me expected output 6.

Is there any role of processor or it depends only on Compiler?

2
@JohnZwinck: please attach the link if you test it on clang. - Destructor
I tested it on my Macbook, 64-bit, Clang 3.5. - John Zwinck
@AndreyNasonov: not working. It still gives 9 as output - Destructor
are you on x86 CPU? Also, which compiler? (there are two different ports of g++ to windows 32, mingw and mingw-w64) - M.M
Using mingw-w64-i686-gcc 5.2 with any of the __attribute__((packed)) variants mentioned here, I get size 9. Using mingw-w64-i686-clang 3.7 and the same attributes I get size 6. Using g++ again with #pragma pack(push, 1) / #pragma pack(pop) around the struct, I also get size 6. - melak47

2 Answers

4
votes

attribute packed is broken on mingw32 compilers. Another option is to use pragma pack:

#pragma pack(1)
struct mystruct_A {
  char a;
  int b;
  char c;
} x;
0
votes

Solution here worked for me: https://wintermade.it/blog/posts/__attribute__packed-on-windows-is-ignored-with-mingw.html, which is to add -mno-ms-bitfields to the compiler flags.