1. 程式人生 > >__attribute__ ((packed)) 和 __attribute__ ((aligned(4)))用法

__attribute__ ((packed)) 和 __attribute__ ((aligned(4)))用法

1、 __attribute__ ((packed))的作用就是告訴編譯器取消結構在編譯過程中的優化對齊,按照實際佔用位元組數進行對齊,是GCC特有的語法。
2、 __attribute__ ((aligned(n)))的作用就是告訴編譯器在編譯過程中按照n位元組對齊。常常用來在結構體後面進行修飾。

下面通過一段程式碼來進行測試

  1. #include <stdio.h>
  2. /*編譯器預設是4位元組對齊*/
  3. struct test{
  4.     char a;
  5.     int b;
  6. };
  7. /*按實際佔用的空間大小*/
  8. struct test1{
  9.     char a;
  10.     int b;
  11. }__attribute__((packed));
  12. /*結構體大小必須4位元組對齊*/
  13. struct test2{
  14.     char a;
  15.     int b;
  16. }__attribute__((aligned(4)));
  17. /*結構體大小必須8位元組對齊*/
  18. struct test3{
  19.     char a;
  20.     int b;
  21. }__attribute__((aligned(8)));
  22. /*結構體大小必須16位元組對齊*/
  23. struct test4{
  24.     char a;
  25.     int b;
  26. }__attribute__((aligned(16)));
  27. /*int 型別資料大小必須8位元組對齊*/
  28. struct test5{
  29.     char a;
  30.     int __attribute__((aligned(8))) b;
  31. };
  32. int main()
  33. {
  34.     printf("test:%d\n",sizeof(struct test));
  35.     printf("test1:%d\n",sizeof(struct test1));
  36.     printf("test2:%d\n",sizeof(struct test2));
  37.     printf("test3:%d\n",sizeof(struct test3));
  38.     printf("test4:%d\n",sizeof(struct test4));
  39.     printf("test5:%d\n",sizeof(struct test5));
  40.     return 0;
  41. }

編譯執行的結果: