[toc]
__attribute 語法的來源
GNU C 的一大特色就是__attribute__ 機制。attribute 可以設置函數屬性(Function Attribute)、變量屬性(Variable Attribute)和類型屬性(Type Attribute)。
其位置約束為: 放于聲明的尾部“;” 之前
attribute 書寫特征為: attribute 前后都有兩個下劃線,并且后面會緊跟一對原括弧,括弧里面是相應的__attribute__ 參數。
attribute 語法格式為: attribute ((attribute-list))
當__attribute__ 用于修飾對象時,它就如同C 語言語法體系結構的類型限定符,跟const , volatile , restrict 等屬一類。
當__attribute__ 用于修飾函數時,它就相當于一個函數說明符,跟inline,Noreturn 屬同一類。
當__attribute__ 用于修飾一個結構體,聯合體或者枚舉類型,該限定符只能放在類型標識符之前。
__attribute__ 所支持的類型
當我們需要識別當前編譯器能否支持GNU 語法拓展,我們可以使用 __GNU __ 宏作為區分
函數屬性(Function Attribute) | 類型屬性(Type Attributes) | 變量屬性(Variable Attribute) | Clang特有的 |
---|---|---|---|
noreturn | aligned | alias | availability |
noinline | packed | at(address) | overloadable |
always_inline | bitband | aligned | |
flatten | deprecated | ||
pure | noinline | ||
const | packed | ||
constructor | weak | ||
destructor | weakref(“target”) | ||
sentinel | section(“name”) | ||
format | unused | ||
format_arg | used | ||
section | visibility(“visibility_type”) | ||
used | zero_init | ||
unused | |||
deprecated | |||
weak | |||
malloc | |||
alias | |||
warn_unused_result | |||
nonnull | |||
nothrow (不拋出C++ 異常) |
常用函數屬性
attribute((const)) function attribute
用const屬性修飾的函數與用pure屬性修飾的十分類似,不過const屬性比pure更嚴格,它要求函數不能讀全局對象。此外,用const屬性修飾的函數的參數不能是一個指針類型,而且在用const屬性修飾的函數內往往不能調用一個非const屬性的函數。
__attribute__ ((__packed__))
__attribute__ ((__packed__))的作用就是告訴編譯器,被修飾的類型不要在編譯的過程中進行字節對齊優化,要按照實際的情況進行對齊。