__attribute__ ((packed)) 和 __attribute__ ((aligned(4)))用法
阿新 • • 發佈:2019-02-19
1、 __attribute__ ((packed))的作用就是告訴編譯器取消結構在編譯過程中的優化對齊,按照實際佔用位元組數進行對齊,是GCC特有的語法。
2、 __attribute__ ((aligned(n)))的作用就是告訴編譯器在編譯過程中按照n位元組對齊。常常用來在結構體後面進行修飾。
下面通過一段程式碼來進行測試
- #include <stdio.h>
- /*編譯器預設是4位元組對齊*/
- struct test{
- char a;
- int b;
- };
- /*按實際佔用的空間大小*/
- struct test1{
- char a;
- int b;
- }__attribute__((packed));
- /*結構體大小必須4位元組對齊*/
- struct test2{
- char a;
- int b;
- }__attribute__((aligned(4)));
- /*結構體大小必須8位元組對齊*/
- struct test3{
- char a;
- int b;
- }__attribute__((aligned(8)));
- /*結構體大小必須16位元組對齊*/
- struct test4{
- char a;
- int b;
- }__attribute__((aligned(16)));
- /*int 型別資料大小必須8位元組對齊*/
- struct test5{
- char a;
- int __attribute__((aligned(8))) b;
- };
- int main()
- {
- printf("test:%d\n",sizeof(struct test));
- printf("test1:%d\n",sizeof(struct test1));
- printf("test2:%d\n",sizeof(struct test2));
- printf("test3:%d\n",sizeof(struct test3));
- printf("test4:%d\n",sizeof(struct test4));
- printf("test5:%d\n",sizeof(struct test5));
- return 0;
- }
編譯執行的結果: