請(qǐng)閱讀【ARM GCC 編譯專欄導(dǎo)讀】
上篇文章:ARM 嵌入式 編譯系列 10.3 – GNU elfutils 工具小結(jié)
下篇文章:ARM 嵌入式 編譯系列 11.1 – GCC attribute((aligned(x)))詳細(xì)介紹
attribute((packed)) 介紹
__attribute__((packed))
是 GCC 編譯器的一個(gè)特性,它可以用于阻止編譯器為結(jié)構(gòu)體或聯(lián)合體的成員進(jìn)行對(duì)齊優(yōu)化,從而使其盡可能地小。
默認(rèn)情況下,編譯器可能會(huì)在結(jié)構(gòu)體的成員之間添加填充字節(jié),以確保特定類型的數(shù)據(jù)在內(nèi)存中按照適當(dāng)?shù)倪吔鐚?duì)齊,以提高處理器訪問(wèn)數(shù)據(jù)的效率。但是,這可能會(huì)導(dǎo)致結(jié)構(gòu)體比實(shí)際需要的更大。
使用 __attribute__((packed))
可以消除這些填充字節(jié),使得結(jié)構(gòu)體或聯(lián)合體的大小盡可能小。
以下是一個(gè)簡(jiǎn)單的示例:
#include <stdio.h>
struct normal_struct
{
char c;
int i;
};
struct __attribute__((packed)) packed_struct {
char c;
int i;
};
int main(void)
{
printf("Size of normal_struct: %lu\n", sizeof(struct normal_struct));
printf("Size of packed_struct: %lu\n", sizeof(struct packed_struct));
return 0;
}
在這個(gè)示例中,normal_struct
是一個(gè)常規(guī)的結(jié)構(gòu)體,由于編譯器對(duì) int
類型的對(duì)齊要求,它的大小可能大于 packed_struct
。packed_struct
使用了 __attribute__((packed))
,所以它的大小是成員 char c
和 int i
的大小的總和,沒(méi)有額外的填充字節(jié)。
[09:34:09]sam@sam-pcStation-P350 (*^~^*) ~/workbase/test> gcc test.c
[09:34:13]sam@sam-pcStation-P350 (*^~^*) ~/workbase/test> ./a.out
Size of normal_struct: 8
Size of packed_struct: 5
但是請(qǐng)注意,使用 __attribute__((packed))
可能會(huì)導(dǎo)致處理器需要執(zhí)行額外的操作來(lái)加載或存儲(chǔ)非對(duì)齊的字段,這可能會(huì)降低代碼的性能。因此,在考慮使用此屬性時(shí),應(yīng)權(quán)衡內(nèi)存使用和代碼性能之間的平衡。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-660433.html
上篇文章:ARM 嵌入式 編譯系列 10.3 – GNU elfutils 工具小結(jié)
下篇文章:ARM 嵌入式 編譯系列 11.1 – GCC attribute((aligned(x)))詳細(xì)介紹文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-660433.html
到了這里,關(guān)于【ARM 嵌入式 編譯系列 11 -- GCC __attribute__((packed))詳細(xì)介紹】的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!