C/C++開發--#pragma pack(n)和__attribute__((aligned(m)))的區別

    前者告訴編譯器結構體或類內部的成員變量相對於第一個變量的地址的偏移量的對齊方式,缺省情況下,編譯器按照自然邊界對齊,當變量所需的自然對齊邊界比n大 時,按照n對齊,否則按照自然邊界對齊;後者告訴編譯器一個結構體或者類或者聯合或者一個類型的變量(對象)分配地址空間時的地址對齊方式。也就是說,如果將__attribute__((aligned(m)))作用於一個類型,那麼該類型的變量在分配地址空間時,其存放的地址一定按照m字節對齊(m必 須是2的冪次方)。並且其佔用的空間,即大小,也是m的整數倍,以保證在申請連續存儲空間的時候,每一個元素的地址也是按照m字節對齊。 __attribute__((aligned(m)))也可以作用於一個單獨的變量。舉例說明:

#include<stdio.h>
 
#pragma pack(4)
typedef struct
{
    uint32_t f1;
    uint8_t f2;
    uint8_t f3;
    uint32_t f4;
    uint64_t f5;
}__attribute__((aligned(1024))) ts;
 
int main()
{
    printf("Struct sizeis: %d, aligned on 1024\n",sizeof(ts));
    printf("Allocate f1on address: 0x%x\n",&(((ts*)0)->f1));
    printf("Allocate f2on address: 0x%x\n",&(((ts*)0)->f2));
    printf("Allocate f3on address: 0x%x\n",&(((ts*)0)->f3));
    printf("Allocate f4on address: 0x%x\n",&(((ts*)0)->f4));
    printf("Allocate f5on address: 0x%x\n",&(((ts*)0)->f5));
   
    return 0;
}


輸出:

Struct size is: 1024, aligned on 1024

Allocate f1 on address: 0x0

Allocate f2 on address: 0x4

Allocate f3 on address: 0x5

Allocate f4 on address: 0x8

Allocate f5 on address: 0xc

注意

綠色部分表明了__attribute__((aligned(1024))) 的作用

紅色部分說明#pragma pack(4)只對大小大於4的成員變量的地址偏移起作用

紫色部分說明對於大小大於4的成員變量,其地址偏移按照4字節對齊

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章