最近在看我們的代碼的時(shí)候發(fā)現(xiàn)聲明類型的時(shí)候有 __attribute__ ((packed))的結(jié)構(gòu)體類型聲明,不知道是什么意思,查了下知道是如下含義:
1. __attribute__ ((packed)) 的作用就是告訴編譯器取消結(jié)構(gòu)在編譯過程中的優(yōu)化對(duì)齊,按照實(shí)際占用字節(jié)數(shù)進(jìn)行對(duì)齊,是GCC特有的語法。這個(gè)功能是跟操作系統(tǒng)沒關(guān)系,跟編譯器有關(guān),gcc編譯器不是緊湊模式的,我在windows下,用vc的編譯器也不是緊湊的,用tc的編譯器就是緊湊的。例如:
在TC下:struct my{ char ch; int a;} sizeof(int)=2;sizeof(my)=3;(緊湊模式)
在GCC下:struct my{ char ch; int a;} sizeof(int)=4;sizeof(my)=8;(非緊湊模式)
在GCC下:struct my{ char ch; int a;}__attrubte__ ((packed)) sizeof(int)=4;sizeof(my)=5
2. __attribute__關(guān)鍵字主要是用來在函數(shù)或數(shù)據(jù)聲明中設(shè)置其屬性。給函數(shù)賦給屬性的主要目的在于讓編譯器進(jìn)行優(yōu)化。函數(shù)聲明中的__attribute__((noreturn)),就是告訴編譯器這個(gè)函數(shù)不會(huì)返回給調(diào)用者,以便編譯器在優(yōu)化時(shí)去掉不必要的函數(shù)返回代碼。
GNU C的一大特色就是__attribute__機(jī)制。__attribute__可以設(shè)置函數(shù)屬性(Function Attribute)、變量屬性(Variable Attribute)和類型屬性(Type Attribute)。
__attribute__書寫特征是:__attribute__前后都有兩個(gè)下劃線,并且后面會(huì)緊跟一對(duì)括弧,括弧里面是相應(yīng)的__attribute__參數(shù)。
__attribute__語法格式為:
__attribute__ ((attribute-list))
其位置約束:放于聲明的尾部“;”之前。
函數(shù)屬性(Function Attribute):函數(shù)屬性可以幫助開發(fā)者把一些特性添加到函數(shù)聲明中,從而可以使編譯器在錯(cuò)誤檢查方面的功能更強(qiáng)大。__attribute__機(jī)制也很容易同非GNU應(yīng)用程序做到兼容之功效。
GNU CC需要使用 –Wall編譯器來?yè)艋钤摴δ埽@是控制警告信息的一個(gè)很好的方式。
packed屬性:使用該屬性可以使得變量或者結(jié)構(gòu)體成員使用最小的對(duì)齊方式,即對(duì)變量是一字節(jié)對(duì)齊,對(duì)域(field)是位對(duì)齊。
http://blogguan.blog.sohu.com/109697765.html
/* __attribute__ ((packed)) 的位置約束是放于聲明的尾部“;”之前 */
struct str_struct{
__u8 a;
__u8 b;
__u8 c;
__u16 d;
} __attribute__ ((packed));
/* 當(dāng)用到typedef時(shí),要特別注意__attribute__ ((packed))放置的位置,相當(dāng)于:
* typedef struct str_stuct str;
* 而struct str_struct 就是上面的那個(gè)結(jié)構(gòu)。
*/
typedef struct {
__u8 a;
__u8 b;
__u8 c;
__u16 d;
} __attribute__ ((packed)) str;
/* 在下面這個(gè)typedef結(jié)構(gòu)中,__attribute__ ((packed))放在結(jié)構(gòu)名str_temp之后,其作用是被忽略的,注意與結(jié)構(gòu)str的區(qū)別。*/
typedef struct {
__u8 a;
__u8 b;
__u8 c;
__u16 d;
}str_temp __attribute__ ((packed));
http://rmax2005.spaces.live.com/blog/cns!4C2190641D9E68A!311.entry