Confusion on __attribute__((__packed__))

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi all,

I have to confuse on using of __attribute__((__packed__)).

struct bits {
  uint8_t b0:1;
  uint8_t b1:1;
  uint8_t b2:1;
  uint8_t b3:1;
  uint8_t b4:1;
  uint8_t b5:1;
  uint8_t b6:1;
  uint8_t b7:1;
}__attribute__((__packed__));

#define SBIT(port,pin) ((*(volatile struct bits*)&port).b##pin)
 
int main()
{
  SBIT(PORTB,0) = 1;
  SBIT(PORTB,1) = 1;
  SBIT(PORTB,2) = 1;
  SBIT(PORTB,3) = 1;
  SBIT(PORTB,4) = 1;
  SBIT(PORTB,5) = 1;
  SBIT(PORTB,6) = 1;
  SBIT(PORTB,7) = 1;
}  

Try to test without __attribute__((__packed__)).

struct bits {
  uint8_t b0:1;
  uint8_t b1:1;
  uint8_t b2:1;
  uint8_t b3:1;
  uint8_t b4:1;
  uint8_t b5:1;
  uint8_t b6:1;
  uint8_t b7:1;
};

Both result are same. So, when I should consider to use it? Is it necessary to use?

Thank you.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

On 8 bit processors it is rarely needed. It is more useful on machines that have a basic data size that is multi-byte. As far as bit fields, I believe that avr-gcc will always pack the bits as best it can.

Regards,
Steve A.

The Board helps those that help themselves.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thank you for your reply. Is this also on other than bit field structure on 8 bit processors ?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I don't think packing has anything to do with bit fields. It has to do with data alignment of multibyte operands.

In general, bitfields are non-portable. They are defined in different orders on big endian and little endian machines. The 8 bit AVRs have no inherent endianness, but GCC apparently uses little endian for multiple byte operands, and for bit field order.

I find bit fields can make code much easier to read so I use them, but I make sure to account for differences between computers when appropriate.

Defining the bits in a register using bit fields can make for better looking code, in my humble opinion. But it can also make for less efficient code. So it's a tradeoff.