PoiNtEr->: What is __attribute__((packed)) ???

                             Difference between a dream and an aim. A dream requires soundless sleep, whereas an aim requires sleepless efforts.

Search This Blog

Wednesday, February 22, 2012

What is __attribute__((packed)) ???


Compact
#include <stdio.h>

struct s1 {
   char a;
   
   int  i;
};

struct s2 {
   char a;
   int i __attribute__((packed));
};

int main( int argc, char* argv[] ) {

  struct s1 s_1;
  struct s2 s_2;

  printf( "sizeof s1 is %d\n" , sizeof(s_1) );
  printf( "sizeof s2 is %d\n" , sizeof(s_2) );

  return( 0 );
}


Output:
sizeof s1 is 8
sizeof s2 is 5

__attribute__((packed)) ensures that structure fields align on one-byte boundaries.That means now your structure will be of same size on any processor.Using this attribute you tell GCC that you want to align them one after other.

As in s1: like here processor is aligning to 4-byte boundaries.
  1(char)+3(waste)+4(int)=8
In s2:
1(char)+4(int)=5












No comments:

Post a Comment