__attribute__ 機制詳解

請移步原文鏈接

[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__))的作用就是告訴編譯器,被修飾的類型不要在編譯的過程中進行字節對齊優化,要按照實際的情況進行對齊。


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容