C之a(chǎn)ttribute用法
轉(zhuǎn)自:http://www.cnblogs.com/astwish/p/3460618.html
GNU C 的一大特色就是__attribute__ 機(jī)制。__attribute__ 可以設(shè)置函數(shù)屬性(Function Attribute )、變量屬性(Variable Attribute )和類(lèi)型屬性(Type Attribute )。
__attribute__ 書(shū)寫(xiě)特征是:__attribute__ 前后都有兩個(gè)下劃線,并切后面會(huì)緊跟一對(duì)原括弧,括弧里面是相應(yīng)的__attribute__ 參數(shù)。
__attribute__ 語(yǔ)法格式為:__attribute__ ((attribute-list))
其位置約束為:放于聲明的尾部“ ;” 之前。
關(guān)鍵字__attribute__ 也可以對(duì)結(jié)構(gòu)體(struct )或共用體(union )進(jìn)行屬性設(shè)置。大致有六個(gè)參數(shù)值可以被設(shè)定,即:aligned, packed, transparent_union, unused, deprecated 和 may_alias 。
在使用__attribute__ 參數(shù)時(shí),你也可以在參數(shù)的前后都加上“__” (兩個(gè)下劃線),例如,使用__aligned__而不是aligned ,這樣,你就可以在相應(yīng)的頭文件里使用它而不用關(guān)心頭文件里是否有重名的宏定義。
aligned (alignment)
該屬性設(shè)定一個(gè)指定大小的對(duì)齊格式(以字節(jié) 為單位),例如:
struct S {
short b[3];
} __attribute__ ((aligned (8)));
typedef int int32_t __attribute__ ((aligned (8)));
該聲明將強(qiáng)制編譯器確保(盡它所能)變量類(lèi) 型為struct S 或者int32_t 的變量在分配空間時(shí)采用8 字節(jié)對(duì)齊方式。
如上所述,你可以手動(dòng)指定對(duì)齊的格式,同 樣,你也可以使用默認(rèn)的對(duì)齊方式。如果aligned 后面不緊跟一個(gè)指定的數(shù)字值,那么編譯器將依據(jù)你的目標(biāo)機(jī)器情況使用最大最有益的對(duì)齊方式。例如:
struct S {
short b[3];
} __attribute__ ((aligned));
這里,如果sizeof (short )的大小為2 (byte ),那么,S 的大小就為6 。取一個(gè)2 的次方值,使得該值大于等于6 ,則該值為8 ,所以編譯器將設(shè)置S 類(lèi)型的對(duì)齊方式為8 字節(jié)。
aligned 屬性使被設(shè)置的對(duì)象占用更多的空間,相反的,使用packed 可以減小對(duì)象占用的空間。
需要注意的是,attribute 屬性的效力與你的連接器也有關(guān),如果你的連接器最大只支持16 字節(jié)對(duì)齊,那么你此時(shí)定義32 字節(jié)對(duì)齊也是無(wú)濟(jì)于事的。
packed
使用該屬性對(duì)struct 或者union 類(lèi)型進(jìn)行定義,設(shè)定其類(lèi)型的每一個(gè)變量的內(nèi)存約束。當(dāng)用在enum 類(lèi)型 定義時(shí),暗示了應(yīng)該使用最小完整的類(lèi)型(it indicates that the smallest integral type should be used)。
下面的例子中,packed_struct 類(lèi)型的變量數(shù)組中的值將會(huì)緊緊的靠在一起,但內(nèi)部的成員變量s 不會(huì)被“pack” ,如果希望內(nèi)部的成員變量也被packed 的話,unpacked-struct 也需要使用packed 進(jìn)行相應(yīng)的約束。
struct unpacked_struct
{
char c;
int i;
};
struct packed_struct
{
char c;
int i;
struct unpacked_struct s;
}__attribute__ ((__packed__));
下面的例子中使用__attribute__ 屬性定義了一些結(jié)構(gòu)體及其變量,并給出了輸出結(jié)果和對(duì)結(jié)果的分析。
程序代 碼為:
1 struct p 2 3 { 4 5 int a; 6 7 char b; 8 9 short c; 10 11 }__attribute__((aligned(4))) pp; 12 13 struct m 14 15 { 16 17 char a; 18 19 int b; 20 21 short c; 22 23 }__attribute__((aligned(4))) mm; 24 25 struct o 26 27 { 28 29 int a; 30 31 char b; 32 33 short c; 34 35 }oo; 36 37 struct x 38 39 { 40 41 int a; 42 43 char b; 44 45 struct p px; 46 47 short c; 48 49 }__attribute__((aligned(8))) xx; 50 51 int main() 52 53 { 54 55 printf("sizeof(int)=%d,sizeof(short)=%d.sizeof(char)=%d\n",sizeof(int),sizeof(short),sizeof(char)); 56 57 printf("pp=%d,mm=%d \n", sizeof(pp),sizeof(mm)); 58 59 printf("oo=%d,xx=%d \n", sizeof(oo),sizeof(xx)); 60 61 return 0; 62 63 }
輸出結(jié) 果:
sizeof(int)=4,sizeof(short)=2.sizeof(char)=1
pp=8,mm=12
oo=8,xx=24
分析:
sizeof(pp):
sizeof(a)+sizeof(b)+sizeof(c)=4+1+1=6<8 所以sizeof(pp)=8
sizeof(mm):
sizeof(a)+sizeof(b)+sizeof(c)=1+4+2=7
但是 a 后面需要用 3 個(gè)字節(jié)填充,但是 b 是 4 個(gè)字節(jié),所以 a 占用 4 字節(jié), b 占用 4 個(gè)字節(jié),而 c 又要占用 4 個(gè)字節(jié)。所以 sizeof(mm)=12
sizeof(oo):
sizeof(a)+sizeof(b)+sizeof(c)=4+1+2=7
因?yàn)槟?認(rèn)是以4 字節(jié)對(duì)齊,所以sizeof(oo)=8
sizeof(xx):
sizeof(a)+ sizeof(b)=4+1=5
sizeof(pp)=8; 即xx 是采用8 字節(jié)對(duì)齊的,所以要在a ,b 后面添3 個(gè)空余字節(jié),然后才能存儲(chǔ)px ,
4+1+ (3 )+8+1=17
因?yàn)閤x 采用的對(duì)齊是8 字節(jié)對(duì)齊,所以xx 的大小必定是8 的整數(shù)倍,即xx 的大小是一個(gè)比17 大又是8 的倍數(shù)的一個(gè)最小值,由此得到
17<24 ,所以sizeof(xx)=24
函數(shù)屬性(Function Attribute)
函數(shù)屬性可以幫助開(kāi)發(fā)者把一些特性添加到函數(shù)聲明中,從而可以使編譯器在錯(cuò)誤檢查方面的功能更強(qiáng)大。__attribute__機(jī)制也很容易同非GNU應(yīng)用程序做到兼容之功效。
GNU CC需要使用 –Wall編譯器來(lái)?yè)艋钤摴δ?,這是控制警告信息的一個(gè)很好的方式。下面介紹幾個(gè)常見(jiàn)的屬性參數(shù)。
__attribute__ format
該__attribute__屬性可以給被聲明的函數(shù)加上類(lèi)似printf或者scanf的特征,它可以使編譯器檢查函數(shù)聲明和函數(shù)實(shí)際調(diào)用參數(shù)之間的格式化字符串是否匹配。該功能十分有用,尤其是處理一些很難發(fā)現(xiàn)的bug。
format的語(yǔ)法格式為:
format (archetype, string-index, first-to-check)
format屬性告訴編譯器,按照printf, scanf,
strftime或strfmon的參數(shù)表格式規(guī)則對(duì)該函數(shù)的參數(shù)進(jìn)行檢查。“archetype”指定是哪種風(fēng)格;“string-index”指定傳入函數(shù)的第幾個(gè)參數(shù)是格式化字符串;“first-to-check”指定從函數(shù)的第幾個(gè)參數(shù)開(kāi)始按上述規(guī)則進(jìn)行檢查。
具體使用格式如下:
__attribute__((format(printf,m,n)))
__attribute__((format(scanf,m,n)))
其中參數(shù)m與n的含義為:
m:第幾個(gè)參數(shù)為格式化字符串(format string);
n:參數(shù)集合中的第一個(gè),即參數(shù)“…”里的第一個(gè)參數(shù)在函數(shù)參數(shù)總數(shù)排在第幾,注意,有時(shí)函數(shù)參數(shù)里還有“隱身”的呢,后面會(huì)提到;
在使用上,__attribute__((format(printf,m,n)))是常用的,而另一種卻很少見(jiàn)到。下面舉例說(shuō)明,其中myprint為自己定義的一個(gè)帶有可變參數(shù)的函數(shù),其功能類(lèi)似于printf:
//m=1;n=2
extern void myprint(const char *format,...) __attribute__((format(printf,1,2)));
//m=2;n=3
extern void myprint(int l,const char *format,...)
__attribute__((format(printf,2,3)));
需要特別注意的是,如果myprint是一個(gè)函數(shù)的成員函數(shù),那么m和n的值可有點(diǎn)“懸乎”了,例如:
//m=3;n=4
extern void myprint(int l,const char *format,...)
__attribute__((format(printf,3,4)));
其原因是,類(lèi)成員函數(shù)的第一個(gè)參數(shù)實(shí)際上一個(gè)“隱身”的“this”指針。(有點(diǎn)C++基礎(chǔ)的都知道點(diǎn)this指針,不知道你在這里還知道嗎?)
這里給出測(cè)試用例:attribute.c,代碼如下:
1: 2:extern void myprint(const char *format,...) __attribute__((format(printf,1,2))); 3: 4:void test() 5:{ 6: myprint("i=%d\n",6); 7: myprint("i=%s\n",6); 8: myprint("i=%s\n","abc"); 9: myprint("%s,%d,%d\n",1,2); 10:}
運(yùn)行$gcc –Wall –c attribute.c attribute后,輸出結(jié)果為:
attribute.c: In function `test':
attribute.c:7: warning: format argument is not a pointer (arg 2)
attribute.c:9: warning: format argument is not a pointer (arg 2)
attribute.c:9: warning: too few arguments for format
如果在attribute.c中的函數(shù)聲明去掉__attribute__((format(printf,1,2))),再重新編譯,既運(yùn)行$gcc –Wall –c attribute.c attribute后,則并不會(huì)輸出任何警告信息。
注意,默認(rèn)情況下,編譯器是能識(shí)別類(lèi)似printf的“標(biāo)準(zhǔn)”庫(kù)函數(shù)。
__attribute__ noreturn
該屬性通知編譯器函數(shù)從不返回值,當(dāng)遇到類(lèi)似函數(shù)需要返回值而卻不可能運(yùn)行到返回值處就已經(jīng)退出來(lái)的情況,該屬性可以避免出現(xiàn)錯(cuò)誤信息。C庫(kù)函數(shù)中的abort()和exit()的聲明格式就采用了這種格式,如下所示:
extern void exit(int) __attribute__((noreturn));extern void abort(void) __attribute__((noreturn)); 為了方便理解,大家可以參考如下的例子:
1 //name: noreturn.c ;測(cè)試__attribute__((noreturn)) 2 extern void myexit(); 3 4 int test(int n) 5 { 6 if ( n > 0 ) 7 { 8 myexit(); 9 /* 程序不可能到達(dá)這里*/ 10 } 11 else 12 return 0; 13 }
編譯顯示的輸出信息為:
$gcc –Wall –c noreturn.c
noreturn.c: In function `test':
noreturn.c:12: warning: control reaches end of non-void function
警告信息也很好理解,因?yàn)槟愣x了一個(gè)有返回值的函數(shù)test卻有可能沒(méi)有返回值,程序當(dāng)然不知道怎么辦了!
加上__attribute__((noreturn))則可以很好的處理類(lèi)似這種問(wèn)題。把
extern void myexit();修改為:
extern void myexit() __attribute__((noreturn));之后,編譯不會(huì)再出現(xiàn)警告信息。
__attribute__ const
該屬性只能用于帶有數(shù)值類(lèi)型參數(shù)的函數(shù)上。當(dāng)重復(fù)調(diào)用帶有數(shù)值參數(shù)的函數(shù)時(shí),由于返回值是相同的,所以此時(shí)編譯器可以進(jìn)行優(yōu)化處理,除第一次需要運(yùn)算外, 其它只需要返回第一次的結(jié)果就可以了,進(jìn)而可以提高效率。該屬性主要適用于沒(méi)有靜態(tài)狀態(tài)(static state)和副作用的一些函數(shù),并且返回值僅僅依賴(lài)輸入的參數(shù)。
為了說(shuō)明問(wèn)題,下面舉個(gè)非常“糟糕”的例子,該例子將重復(fù)調(diào)用一個(gè)帶有相同參數(shù)值的函數(shù),具體如下:
extern int square(int n) __attribute__ ((const));... for (i = 0; i < 100; i++ ) { total += square (5) + i; }
通過(guò)添加__attribute__((const))聲明,編譯器只調(diào)用了函數(shù)一次,以后只是直接得到了相同的一個(gè)返回值。
事實(shí)上,const參數(shù)不能用在帶有指針類(lèi)型參數(shù)的函數(shù)中,因?yàn)樵搶傩圆坏绊懞瘮?shù)的參數(shù)值,同樣也影響到了參數(shù)指向的數(shù)據(jù),它可能會(huì)對(duì)代碼本身產(chǎn)生嚴(yán)重甚至是不可恢復(fù)的嚴(yán)重后果。
并且,帶有該屬性的函數(shù)不能有任何副作用或者是靜態(tài)的狀態(tài),所以,類(lèi)似getchar()或time()的函數(shù)是不適合使用該屬性的。
-finstrument-functions
該參數(shù)可以使程序在編譯時(shí),在函數(shù)的入口和出口處生成instrumentation調(diào)用。恰好在函數(shù)入口之后并恰好在函數(shù)出口之前,將使用當(dāng)前函數(shù)的地址和調(diào)用地址來(lái)調(diào)用下面的
profiling
函數(shù)。(在一些平臺(tái)上,__builtin_return_address不能在超過(guò)當(dāng)前函數(shù)范圍之外正常工作,所以調(diào)用地址信息可能對(duì)profiling函數(shù)是無(wú)效的。)
void __cyg_profile_func_enter(void *this_fn, void *call_site);
void __cyg_profile_func_exit(void *this_fn, void *call_site);
其中,第一個(gè)參數(shù)this_fn是當(dāng)前函數(shù)的起始地址,可在符號(hào)表中找到;第二個(gè)參數(shù)call_site是指調(diào)用處地址。
instrumentation
也可用于在其它函數(shù)中展開(kāi)的內(nèi)聯(lián)函數(shù)。從概念上來(lái)說(shuō),profiling調(diào)用將指出在哪里進(jìn)入和退出內(nèi)聯(lián)函數(shù)。這就意味著這種函數(shù)必須具有可尋址形式。如 果函數(shù)包含內(nèi)聯(lián),而所有使用到該函數(shù)的程序都要把該內(nèi)聯(lián)展開(kāi),這會(huì)額外地增加代碼長(zhǎng)度。如果要在C 代碼中使用extern inline聲明,必須提供這種函數(shù)的可尋址形式。
可對(duì)函數(shù)指定no_instrument_function屬性,在這種情況下不會(huì)進(jìn)行 Instrumentation操作。例如,可以在以下情況下使用no_instrument_function屬性:上面列出的profiling函 數(shù)、高優(yōu)先級(jí)的中斷例程以及任何不能保證profiling正常調(diào)用的函數(shù)。
no_instrument_function
如果使用了-finstrument-functions
,將在絕大多數(shù)用戶(hù)編譯的函數(shù)的入口和出口點(diǎn)調(diào)用profiling函數(shù)。使用該屬性,將不進(jìn)行instrument操作。
constructor/destructor
若函數(shù)被設(shè)定為constructor屬性,則該函數(shù)會(huì)在main()函數(shù)執(zhí)行之前被自動(dòng)的執(zhí)行。類(lèi)似的,若函數(shù)被設(shè)定為destructor屬性,則該 函數(shù)會(huì)在main()函數(shù)執(zhí)行之后或者exit()被調(diào)用后被自動(dòng)的執(zhí)行。擁有此類(lèi)屬性的函數(shù)經(jīng)常隱式的用在程序的初始化數(shù)據(jù)方面。
這兩個(gè)屬性還沒(méi)有在面向?qū)ο驝中實(shí)現(xiàn)。
同時(shí)使用多個(gè)屬性
可以在同一個(gè)函數(shù)聲明里使用多個(gè)__attribute__,并且實(shí)際應(yīng)用中這種情況是十分常見(jiàn)的。使用方式上,你可以選擇兩個(gè)單獨(dú)的__attribute__,或者把它們寫(xiě)在一起,可以參考下面的例子:
/* 把類(lèi)似printf的消息傳遞給stderr 并退出 */extern void die(const char *format, ...) __attribute__((noreturn)) __attribute__((format(printf, 1, 2))); 或者寫(xiě)成 extern void die(const char *format, ...) __attribute__((noreturn, format(printf, 1, 2))); 如果帶有該屬性的自定義函數(shù)追加到庫(kù)的頭文件里,那么所以調(diào)用該函數(shù)的程序都要做相應(yīng)的檢查。
和非GNU編譯器的兼容性
慶幸的是,__attribute__設(shè)計(jì)的非常巧妙,很容易作到和其它編譯器保持兼容,也就是說(shuō),如果工作在其它的非GNU編譯器上,可以很容易的忽略該屬性。即使__attribute__使用了多個(gè)參數(shù),也可以很容易的使用一對(duì)圓括弧進(jìn)行處理,例如:
/* 如果使用的是非GNU C, 那么就忽略__attribute__ */#ifndef __GNUC__# define __attribute__(x) /*NOTHING*/#endif
需要說(shuō)明的是,__attribute__適用于函數(shù)的聲明而不是函數(shù)的定義。所以,當(dāng)需要使用該屬性的函數(shù)時(shí),必須在同一個(gè)文件里進(jìn)行聲明,例如:
/* 函數(shù)聲明 */void die(const char *format, ...) __attribute__((noreturn)) __attribute__((format(printf,1,2))); void die(const char *format, ...){ /* 函數(shù)定義 */}
aligned (alignment)This attribute specifies a minimum alignment for the variable or structure field, measured in bytes. For example, the declaration:
int x __attribute__ ((aligned (16))) = 0;
causes the compiler to allocate the global variable x on a 16-byte boundary. On a 68040, this could be used in conjunction with an asm expression to access themove16 instruction which requires 16-byte aligned operands.
You can also specify the alignment of structure fields. For example, to create a double-word aligned int pair, you could write:
struct foo { int x[2] __attribute__ ((aligned (8))); };
This is an alternative to creating a union with a double member that forces the union to be double-word aligned.
As in the preceding examples, you can explicitly specify the alignment (in bytes) that you wish the compiler to use for a given variable or structure field. Alternatively, you can leave out the alignment factor and just ask the compiler to align a variable or field to the maximum useful alignment for the target machine you are compiling for. For example, you could write:
short array[3] __attribute__ ((aligned));
for more: http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Variable-Attributes.html#Variable-Attributes
下面來(lái)看一個(gè)不一樣的HelloWorld程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> #include <stdlib.h> static __attribute__((constructor)) void before() { printf("Hello"); } static __attribute__((destructor)) void after() { printf(" World!\n"); } int main(int args,char ** argv) { return EXIT_SUCCESS; } |
我們知道這是一個(gè)HelloWorld程序,所以輸出的結(jié)果就是"Hello World!",很簡(jiǎn)單,不需要對(duì)這點(diǎn)過(guò)多關(guān)心.
下面我們來(lái)關(guān)心關(guān)心別的:
1 2 3 | __attribute__((constructor)) __attribute__((destructor)) |
解釋一下:__attribute__((constructor)) 在main() 之前執(zhí)行,__attribute__((destructor)) 在main()執(zhí)行結(jié)束之后執(zhí)行.
上面的例子中我沒(méi)有在main函數(shù)中添加任何的輸出,所以看不到具體的信息.這點(diǎn)可以自己嘗試~
如果要在main()之前或者是執(zhí)行完成之后,需要執(zhí)行很多的前處理動(dòng)作或者是后處理動(dòng)作,我們應(yīng)該怎么處理?
也許,你需要下面這些東西:
__attribute__((constructor(PRIORITY))) __attribute__((destructor(PRIORITY))) |
PRIORITY: 優(yōu)先級(jí).
好吧,下面就來(lái)試試:
執(zhí)行的輸出如下:
從輸出的信息看,前處理都是按照優(yōu)先級(jí)先后執(zhí)行的,而后處理則是相反的,好吧,我們使用GDB調(diào)試驗(yàn)證一下:
從調(diào)試的信息也是驗(yàn)證了上面的結(jié)果.
另外一個(gè)問(wèn)題,優(yōu)先級(jí)有沒(méi)有范圍的?
其實(shí)剛開(kāi)始我寫(xiě)的程序中的優(yōu)先級(jí)是1,我們將上面的程序改一下,然后編譯看一下會(huì)有什么樣的結(jié)果:
0-100(包括100),是內(nèi)部保留的,所以在編碼的時(shí)候需要注意.
關(guān)于__attribute__的用法,可以有另外一種寫(xiě)法,先聲明函數(shù),然后再定義.
glibc多采用第一種寫(xiě)法.
關(guān)于linux內(nèi)核中的"__attribute__ ((packed))"
引用:
__attrubte__ ((packed)) 的作用就是告訴編譯器取消結(jié)構(gòu)在編譯過(guò)程中的優(yōu)化對(duì)齊,按照實(shí)際占用字節(jié)數(shù)進(jìn)行對(duì)齊。 #define __u8 unsigned char
#define __u16 unsigned short /* __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)); typedef struct {
__u8 a;
__u8 b;
__u8 c;
__u16 d;
}str_nopacked; int main(void)
{
printf("sizeof str = %d\n", sizeof(str));
printf("sizeof str_struct = %d\n", sizeof(struct str_struct));
printf("sizeof str_temp = %d\n", sizeof(str_temp));
printf("sizeof str_nopacked = %d\n", sizeof(str_nopacked));
return 0;
}
編譯運(yùn)行:
引用:
[root@localhost root]# ./packedtest
sizeof str = 5
sizeof str_struct = 5
sizeof str_temp = 6
sizeof str_nopacked = 6
GNU C的一大特色就是__attribute__機(jī)制。__attribute__可以設(shè)置函數(shù)屬性(Function Attribute)、變量屬性(Variable Attribute)和類(lèi)型屬性(Type Attribute)。 __attribute__書(shū)寫(xiě)特征是:__attribute__前后都有兩個(gè)下劃線,并且后面會(huì)緊跟一對(duì)括弧,括弧里面是相應(yīng)的__attribute__參數(shù)。 __attribute__語(yǔ)法格式為: __attribute__ ((attribute-list)) 其位置約束:放于聲明的尾部“;”之前。 函數(shù)屬性(Function Attribute):函數(shù)屬性可以幫助開(kāi)發(fā)者把一些特性添加到函數(shù)聲明中,從而可以使編譯器在錯(cuò)誤檢查方面的功能更強(qiáng)大。__attribute__機(jī)制也很容易同非GNU應(yīng)用程序做到兼容之功效。 GNU CC需要使用 –Wall編譯器來(lái)?yè)艋钤摴δ?,這是控制警告信息的一個(gè)很好的方式。 packed屬性:使用該屬性可以使得變量或者結(jié)構(gòu)體成員使用最小的對(duì)齊方式,即對(duì)變量是一字節(jié)對(duì)齊,對(duì)域(field)是位對(duì)齊。
網(wǎng)絡(luò)通信通常分為基于數(shù)據(jù)結(jié)構(gòu)的和基于流的。HTTP協(xié)議就是后者的一個(gè)例子。
有時(shí)為了提高程序的處理速度和數(shù)據(jù)處理的方便,會(huì)使用基于數(shù)據(jù)結(jié)構(gòu)的通信(不需要對(duì)流進(jìn)行解析)。但是,當(dāng)需要在多平臺(tái)間進(jìn)行通信時(shí),基于數(shù)據(jù)結(jié)構(gòu)的通信,往往要十分注意以下幾個(gè)方面:
[1] 字節(jié)序
[2] 變量長(zhǎng)度
[3] 內(nèi)存對(duì)齊
在常見(jiàn)的系統(tǒng)架構(gòu)中(Linux X86,Windows),非單字節(jié)長(zhǎng)度的變量類(lèi)型,都是低字節(jié)在前,而在某些特定系統(tǒng)中,如Soalris Sparc平臺(tái),高字節(jié)在前。如果在發(fā)送數(shù)據(jù)前不進(jìn)行處理,那么由Linux X86發(fā)向Soalris Sparc平臺(tái)的數(shù)據(jù)值,勢(shì)必會(huì)有極大的偏差,進(jìn)而程序運(yùn)行過(guò)程中無(wú)法出現(xiàn)預(yù)計(jì)的正常結(jié)果,更嚴(yán)重時(shí),會(huì)導(dǎo)致段錯(cuò)誤。
對(duì)于此種情況,我們往往使用同一的字節(jié)序。在系統(tǒng)中,有ntohXXX(), htonXXX()等函數(shù),負(fù)責(zé)將數(shù)據(jù)在網(wǎng)絡(luò)字節(jié)序和本地字節(jié)序之間轉(zhuǎn)換。雖然每種系統(tǒng)的本地字節(jié)序不同,但是對(duì)于所有系統(tǒng)來(lái)說(shuō),網(wǎng)絡(luò)字節(jié)序是固定的 -----高字節(jié)在前。所以,可以以網(wǎng)絡(luò)字節(jié)序?yàn)橥ㄐ诺臉?biāo)準(zhǔn),發(fā)送前,數(shù)據(jù)都轉(zhuǎn)換為網(wǎng)絡(luò)字節(jié)序。
轉(zhuǎn)換的過(guò)程,也建議使用ntohXXX(), htonXXX()等標(biāo)準(zhǔn)函數(shù),這樣代碼可以輕松地在各平臺(tái)間進(jìn)行移植(像通信這種很少依賴(lài)系統(tǒng)API的代碼,做成通用版本是不錯(cuò)的選擇)。
變量的長(zhǎng)度,在不同的系統(tǒng)之間會(huì)有差別,如同是Linux2.6.18的平臺(tái),在64位系統(tǒng)中,指針的長(zhǎng)度為8個(gè)字節(jié),而在32位系統(tǒng)中,指針又是4個(gè)字 節(jié)的長(zhǎng)度---此處只是舉個(gè)例子,很少有人會(huì)將指針作為數(shù)據(jù)發(fā)送出去。下面是我整理的在64位Linux系統(tǒng)和32位Linux系統(tǒng)中,幾種常見(jiàn)C語(yǔ)言變 量的長(zhǎng)度:
short int long long long ptr time_t
32位 2 4 4 8 4 4
64位 2 4 8 8 8 8
在定義通信用的結(jié)構(gòu)體時(shí),應(yīng)該考慮使用定常的數(shù)據(jù)類(lèi)型,如uint32_t,4字節(jié)的固定長(zhǎng)度,并且這屬于標(biāo)準(zhǔn)C庫(kù)(C99),在各系統(tǒng)中都可使用。
內(nèi)存對(duì)齊的問(wèn)題,也與系統(tǒng)是64位還是32位有關(guān)。如果你手頭有32位和64位系統(tǒng),不妨寫(xiě)個(gè)簡(jiǎn)單的程序測(cè)試一下,你就會(huì)看到同一個(gè)結(jié)構(gòu)體,即便使用了定 常的數(shù)據(jù)類(lèi)型,在不同系統(tǒng)中的大小是不同的。對(duì)齊往往是以4字節(jié)或8字節(jié)為準(zhǔn)的,只要你寫(xiě)的測(cè)試程序,變量所占空間沒(méi)有對(duì)齊到4或8的倍數(shù)即可,舉個(gè)簡(jiǎn)單 的測(cè)試用的結(jié)構(gòu)體的例子吧:
struct student
{
char name[7];
uint32_t id;
char subject[5];
};
在每個(gè)系統(tǒng)上看下這個(gè)結(jié)構(gòu)體的長(zhǎng)度吧。
內(nèi)存對(duì)齊,往往是由編譯器來(lái)做的,如果你使用的是gcc,可以在定義變量時(shí),添加__attribute__,來(lái)決定是否使用內(nèi)存對(duì)齊,或是內(nèi)存對(duì)齊到幾個(gè)字節(jié),以上面的結(jié)構(gòu)體為例:
1)到4字節(jié),同樣可指定對(duì)齊到8字節(jié)。
struct student
{
char name[7];
uint32_t id;
char subject[5];
} __attribute__ ((aligned(4)));
2)不對(duì)齊,結(jié)構(gòu)體的長(zhǎng)度,就是各個(gè)變量長(zhǎng)度的和
struct student
{
char name[7];
uint32_t id;
char subject[5];
} __attribute__ ((packed));
One of the best (but little known) features of GNU C is the __attribute__ mechanism, which allows a developer to attach characteristics to function declarations to allow the compiler to perform more error checking. It was designed in a way to be compatible with non-GNU implementations, and we've been using this for years in highly portable code with very good results.
Table of ContentsNote that __attribute__ spelled with two underscores before and two after, and there are always two sets of parentheses surrounding the contents. There is a good reason for this - see below. Gnu CC needs to use the -Wall compiler directive to enable this (yes, there is a finer degree of warnings control available, but we are very big fans of max warnings anyway).
__ATTRIBUTE__ FORMAT
This __attribute__ allows assigning printf-like or scanf-like characteristics to the declared function, and this enables the compiler to check the format string against the parameters provided throughout the code. This is exceptionally helpful in tracking down hard-to-find bugs.
There are two flavors:
__attribute__((format(printf,m,n)))
__attribute__((format(scanf,m,n)))
but in practice we use the first one much more often.
The (m) is the number of the "format string" parameter, and (n) is the number of the first variadic parameter. To see some examples:
/* like printf() but to standard error only */ extern void eprintf(const char *format, ...) __attribute__((format(printf, 1, 2))); /* 1=format 2=params */ /* printf only if debugging is at the desired level */ extern void dprintf(int dlevel, const char *format, ...) __attribute__((format(printf, 2, 3))); /* 2=format 3=params */
With the functions so declared, the compiler will examine the argument lists
$ cat test.c 1 extern void eprintf(const char *format, ...) 2 __attribute__((format(printf, 1, 2))); 3 4 void foo() 5 { 6 eprintf("s=%s\n", 5); /* error on this line */ 7 8 eprintf("n=%d,%d,%d\n", 1, 2); /* error on this line */ 9 } $ cc -Wall -c test.c test.c: In function `foo': test.c:6: warning: format argument is not a pointer (arg 2) test.c:8: warning: too few arguments for format
Note that the "standard" library functions - printf and the like - are already understood by the compiler by default.
__ATTRIBUTE__ NORETURN
This attribute tells the compiler that the function won't ever return, and this can be used to suppress errors about code paths not being reached. The C library functions abort() and exit() are both declared with this attribute:
extern void exit(int) __attribute__((noreturn)); extern void abort(void) __attribute__((noreturn));
Once tagged this way, the compiler can keep track of paths through the code and suppress errors that won't ever happen due to the flow of control never returning after the function call.
In this example, two nearly-identical C source files refer to an "exitnow()" function that never returns, but without the __attribute__tag, the compiler issues a warning. The compiler is correct here, because it has no way of knowing that control doesn't return.
$ cat test1.c extern void exitnow(); int foo(int n) { if ( n > 0 ) { exitnow(); /* control never reaches this point */ } else return 0; } $ cc -c -Wall test1.c test1.c: In function `foo': test1.c:9: warning: this function may return with or without a value
But when we add __attribute__, the compiler suppresses the spurious warning:
$ cat test2.c extern void exitnow() __attribute__((noreturn)); int foo(int n) { if ( n > 0 ) exitnow(); else return 0; } $ cc -c -Wall test2.c no warnings!
__ATTRIBUTE__ CONST
This attribute marks the function as considering only its numeric parameters. This is mainly intended for the compiler to optimize away repeated calls to a function that the compiler knows will return the same value repeatedly. It applies mostly to math functions that have no static state or side effects, and whose return is solely determined by the inputs.
In this highly-contrived example, the compiler normally must call the square() function in every loop even though we know that it's going to return the same value each time:
extern int square(int n) __attribute__((const)); ... for (i = 0; i < 100; i++ ) { total += square(5) + i; }
By adding __attribute__((const)), the compiler can choose to call the function just once and cache the return value.
In virtually every case, const can't be used on functions that take pointers, because the function is not considering just the function parameters but also the data the parameters point to, and it will almost certainly break the code very badly in ways that will be nearly impossible to track down.
Furthermore, the functions so tagged cannot have any side effects or static state, so things like getchar() or time() would behave very poorly under these circumstances.
PUTTING THEM TOGETHER
Multiple __attributes__ can be strung together on a single declaration, and this is not uncommon in practice. You can either use two separate __attribute__s, or use one with a comma-separated list:
/* send printf-like message to stderr and exit */ extern void die(const char *format, ...) __attribute__((noreturn)) __attribute__((format(printf, 1, 2))); /*or*/ extern void die(const char *format, ...) __attribute__((noreturn, format(printf, 1, 2)));
If this is tucked away safely in a library header file, all programs that call this function receive this checking.
COMPATIBILITY WITH NON-GNU COMPILERS
Fortunately, the __attribute__ mechanism was cleverly designed in a way to make it easy to quietly eliminate them if used on platforms other than GNU C. Superficially, __attribute__ appears to have multiple parameters (which would typically rule out using a macro), but the two sets of parentheses effectively make it a single parameter, and in practice this works very nicely.
/* If we're not using GNU C, elide __attribute__ */ #ifndef __GNUC__ # define __attribute__(x) /*NOTHING*/ #endif
Note that __attribute__ applies to function declarations, not definitions, and we're not sure why this is. So when defining a function that merits this treatment, an extra declaration must be used (in the same file):
/* function declaration */ void die(const char *format, ...) __attribute__((noreturn)) __attribute__((format(printf,1,2))); void die(const char *format, ...) { /* function definition */ }
OTHER REFERENCES
We'll note that there are many more attributes available, including those for variables and types, and they are not covered here: we have chosen to just touch on the high points. Those wishing more information can find it in the GNU online documentation athttp://gcc.gnu.org:
GCC 4.0
GCC 4.0 Function Attributes
GCC 4.0 Variable Attributes
GCC 4.0 Type AttributesGCC 3.2
GCC 3.2 Function Attributes
GCC 3.2 Variable Attributes
GCC 3.2 Type AttributesGCC 3.1
GCC 3.1 Function Attributes
GCC 3.1 Variable Attributes
GCC 3.1 Type AttributesGCC 3.0.4
GCC 2.95.3
參考:
http://blog.sina.com.cn/s/blog_644c3be70100i8ii.html
http://hi.baidu.com/srbadxecnihqtue/item/039535e051a0d30f8d3ea8b1
http://www.cnblogs.com/respawn/archive/2012/07/09/2582078.html
http://qq164587043.blog.51cto.com/261469/187562
http://my.oschina.net/u/174242/blog/72760
http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html
http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Type-Attributes.html#Type-Attributes
http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Variable-Attributes.html#Variable-Attributes
http://www.unixwiz.net/techtips/gnu-c-attributes.html
*博客內(nèi)容為網(wǎng)友個(gè)人發(fā)布,僅代表博主個(gè)人觀點(diǎn),如有侵權(quán)請(qǐng)聯(lián)系工作人員刪除。
DIY機(jī)械鍵盤(pán)相關(guān)社區(qū):機(jī)械鍵盤(pán)DIY
電子鎮(zhèn)流器相關(guān)文章:電子鎮(zhèn)流器工作原理