1

I came across this piece of code in one of MicroChip's example codes. I'm unable to understand what it exactly means

typedef struct __attribute__((packed))
{
    BYTE command;
    BYTE data;
} ACCESSORY_APP_PACKET;

I can understand that a struct aliased ACCESSORY_APP_PACKET is being created, but what does the __attribute__((packed)) mean? It makes __attribute__ as a function. But if that is so, how is it being typedef'd as a struct?
BYTE is a known datatype made by Microchip.

Thanks.

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
Adwait Dongare
  • 301
  • 1
  • 3
  • 13

3 Answers3

3

__attribute__ is a gcc compiler option that specifies a separate behavior of the compiler on compilation.

In your case it says to the compiler not to use padding between structure members.

Alex
  • 9,891
  • 11
  • 53
  • 87
  • so as far as I am concerned, the code simply means a struct alias ACCESSORY_APP_PACKET was created with 2 BYTE elements in it? what does "not to use padding between structure members" exactly mean? – Adwait Dongare Mar 28 '13 at 11:06
  • Is it related to the fact that if i create a struct with say 2 booleans, the whole things becomes 2 bytes long instead of 2 bits long? – Adwait Dongare Mar 28 '13 at 11:07
  • @AdwaitDongare in order to make structure members access faster, structure members are padded to a processors word size (`char` member takes e.g `4` bytes instead of `1`byte). Thus in your case you're forcing the structure to have size `2` bytes instead of `8` (this value can be dependent on the compiler/platform etc). – Alex Mar 28 '13 at 11:31
2

It is not part of the typedef, nor is it a function. It's a compiler extension using syntax that sort of looks "function-like" perhaps. It is used to change the way the struct members are packed in memory so it uses minimal space, rather than being packed in a potentially larger way that might execute faster.

Randy Howard
  • 2,165
  • 16
  • 26
0

No, it's not a function. It's an attribute (this is a GNU extension). It specifies that there should be no padding between the members of the struct (which otherwise there can be).