0

I use __attribute__((packed)); to make items of a struct being stored in memory after another as this is critical for some low-level development.
As __attribute__((packed)); is GCC specific I wonder if there is a similar solution that works on ALL ANSI/C89/C99/C11 compilers or at least some of them.

pitastic
  • 322
  • 4
  • 9
  • 5
    Simple answer: **No**. Read the [standard](http://port70.net/~nsz/c/c11/n1570.html). But you might use conditional compilation to create code appropriate for different compilers. OTOH, question is more **Why** do you want to pack a `struct`. If it is for serialization, this is likely a bad idea. – too honest for this site Jul 21 '15 at 18:41
  • Notice that such attribute is understood by [GCC](http://gcc.gnu.org/) and by [Clang/LLVM](http://clang.llvm.org/) – Basile Starynkevitch Jul 21 '15 at 19:25
  • 1
    Note that using 'attribute packed' tends to preclude efficiency — or, at least, you are trading (gaining) space efficiency at the cost of time efficiency. If you aren't accessing the structures very often, it may not matter. If you're doing it a lot, it probably does. – Jonathan Leffler Jul 21 '15 at 19:34
  • @Olaf I need this to ensure the [IDT](http://wiki.osdev.org/IDT) of my small hobby operating system sits in memory the way it should.
    – pitastic Jul 22 '15 at 07:52

2 Answers2

3

There is no standard approach to accomplish what __attribute__((packed)) does. The typical solution is to use #ifdef's to handle different compilers. You can find a few solutions to this approach at this SO post which also contains the details on the Visual C++ equivalent of __attribute__((packed)). Alternatively, GCC supports the Windows struct packing pragmas, so if you are just concerned with Windows and GCC you could just use the Windows approach.

Community
  • 1
  • 1
missimer
  • 4,022
  • 1
  • 19
  • 33
2

There is no support for features to control struct layout specified by the standard. The standard simply states that this aspect is implementation defined.

Therefore, if you do need to control layout, you will need to use compiler specific functionality. If you can find a way to avoid needing to do this at all, that would be preferable.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490