3
int readint(__packed int *data)
{
    return *data;
}

I have seen __packed attribute in struct declarations to avoid padding. However, what is the benefit of using __packed attribute in function arguments.

The author says that he has used __packed to tell the compiler that the integer may possibly not be aligned. What does it means?

Edit: Will the following work with gcc compiler

int readint(__attribute__((packed)) int *data)
{
    return *data;
}
artless noise
  • 21,212
  • 6
  • 68
  • 105
manav m-n
  • 11,136
  • 23
  • 74
  • 97
  • 1
    It is important to mention that this is not standard C++ but a compiler specific extension. – TNA Jan 28 '15 at 07:10
  • This usage is actually specific to ARM (and, in fact, to a specific ARM C compiler). I've edited the tags to reflect this. –  Jan 28 '15 at 07:11
  • @duskwuff why is it specific to `arm`, it can be the case with any processor with supports unaligned memory access. – manav m-n Jan 28 '15 at 07:12
  • I edited the tag to 'armcc' ; at least include that one. Especially, there are macros/extensions like `__packed` for other systems. It is nice to be up front this question deals with armcc. I found the tag [arm] misleading, but you can add it back. – artless noise Jan 28 '15 at 19:19

1 Answers1

6

The __packed qualifier is a compiler-specific feature of the armcc C compiler, published by ARM. A full explanation is present in their documentation, but in brief, it indicates that no padding for alignment should be inserted into the qualified object, and that pointers with this qualifier should be accessed as if they might be misaligned. (This may cause slower code to be generated for some processors, so it should not be used gratuitously.)

Note that this is not the same as the GCC packed attribute, which only applies to struct and union type definitions.

  • We can also use the functions `get_unaligned()` and `put_unaligned()` for doing unaligned reads and writes. – manav m-n Jan 28 '15 at 08:21