「Management == Programming」
上述這個式子是個人最近突發奇想的想法,仔細想想還真的有這回事耶!
不管您從事何種職務,也許是CEO、也許是經理、也許是職員、也許是為人父或為人母……等等,
首先,您都會面臨職務分配,比方說,
一個公司有銷售團隊、有行政團隊、有研發團隊……等,
一個職員會有E-mail、會建立檔案匣、會寫Memo提醒自己……等,
一位父親或母親會分配使用家中的預算、會決定房間的使用、會分配家務給相關成員……等,
這些行為就好比是程式撰寫前,物件或界面的規劃。
其次,您會建立組職運作的流程與規則,比方說,
一個公司會建立預算執行的核決流程、會建立專案開發的流程……等,
一位職員會建立自己處理任務的方式、會建立自己的時間分配……等,
一位父親或母親會建立家中的作習習慣(如飯後刷牙、何時就寢)……等,
這些行為就好比是程式撰寫時的if判斷式、for迴圈、switch……等語法,以建立各種處理流程。
接下來,您如果是Smart的管理者,相信您會做風險管理,這好比
一個公司會建立火警發生時的處理流程與任務編組、會建立生產品質管制的措施……等,
一位職員會對突如其來的緊急任務進行處理……等,
一位父母當小朋友生病或不舒服會帶去給醫生檢查、當家電故障時會打電話請廠商來維修……等,
這就好比程式中的Error Handling流程、try/catch、setjump/longjump……等,當然對應到Smart的管理者,這通常也只有Smart的Programmer會考慮進去。
如果一個公司面臨突發狀況(如火警)會驚慌失措,沒有相對的應變措施;
如果一個人沒有控管自己的預算,每到月底都在為卡債調度資金;
這就好比Programming中,有些人常用的Workaround。
大家有空可以再想想,還有哪些可以相對應的!
最後,我給幾個想法讓大家想想,也可以找朋友討論:
.好的Programmer應該也可以是個好的manager!
.能力有待加強的Programmer,由於程式邏輯都無法完全掌握了,面對人的世界,應該也無法勝任Manager的角色吧!
.程式中有時會用到Reinitialize/Reset/Reboot的機制,以解決一些一時無法解決的問題;那人的世界呢?
.如果您自認是好的Manager(對自己、對家人、對組織來說),那歡迎您加入Programmer的行列!
「玩!就是要玩!」
人生何其短,不玩要做什麼?
2011年4月11日 星期一
2010年6月24日 星期四
Bounce Buffer
Bounce Buffer是一個資料傳遞的暫存空間,在計算機系統中,有時週邊裝置的定址能力與CPU不相同,此時週邊裝置將無法存取超出其定址能力範圍的記憶體位址,為解決這個問題,因而有了Bounce Buffer機制的出現。Device可以透過DMA將資料搬運到可定址的Bounce Buffer中,然後CPU再將Bounce Buffer內的內容搬到系統期待的位址。
2010年5月25日 星期二
Attribute Syntax
http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Attribute-Syntax.html#Attribute-Syntax
This section describes the syntax with which __attribute__ may be used, and the constructs to which attribute specifiers bind, for the C language. Some details may vary for C++ and Objective-C. Because of infelicities in the grammar for attributes, some forms described here may not be successfully parsed in all cases.
There are some problems with the semantics of attributes in C++. For example, there are no manglings for attributes, although they may affect code generation, so problems may arise when attributed types are used in conjunction with templates or overloading. Similarly, typeid does not distinguish between types with different attributes. Support for attributes in C++ may be restricted in future to attributes on declarations only, but not on nested declarators.
See Function Attributes, for details of the semantics of attributes applying to functions. See Variable Attributes, for details of the semantics of attributes applying to variables. See Type Attributes, for details of the semantics of attributes applying to structure, union and enumerated types.
An attribute specifier is of the form __attribute__ ((attribute-list)). An attribute list is a possibly empty comma-separated sequence of attributes, where each attribute is one of the following:
* Empty. Empty attributes are ignored.
* A word (which may be an identifier such as unused, or a reserved word such as const).
* A word, followed by, in parentheses, parameters for the attribute. These parameters take one of the following forms:
o An identifier. For example, mode attributes use this form.
o An identifier followed by a comma and a non-empty comma-separated list of expressions. For example, format attributes use this form.
o A possibly empty comma-separated list of expressions. For example, format_arg attributes use this form with the list being a single integer constant expression, and alias attributes use this form with the list being a single string constant.
An attribute specifier list is a sequence of one or more attribute specifiers, not separated by any other tokens.
In GNU C, an attribute specifier list may appear after the colon following a label, other than a case or default label. The only attribute it makes sense to use after a label is unused. This feature is intended for code generated by programs which contains labels that may be unused but which is compiled with -Wall. It would not normally be appropriate to use in it human-written code, though it could be useful in cases where the code that jumps to the label is contained within an #ifdef conditional. GNU C++ does not permit such placement of attribute lists, as it is permissible for a declaration, which could begin with an attribute list, to be labelled in C++. Declarations cannot be labelled in C90 or C99, so the ambiguity does not arise there.
An attribute specifier list may appear as part of a struct, union or enum specifier. It may go either immediately after the struct, union or enum keyword, or after the closing brace. It is ignored if the content of the structure, union or enumerated type is not defined in the specifier in which the attribute specifier list is used—that is, in usages such as struct __attribute__((foo)) bar with no following opening brace. Where attribute specifiers follow the closing brace, they are considered to relate to the structure, union or enumerated type defined, not to any enclosing declaration the type specifier appears in, and the type defined is not complete until after the attribute specifiers.
Otherwise, an attribute specifier appears as part of a declaration, counting declarations of unnamed parameters and type names, and relates to that declaration (which may be nested in another declaration, for example in the case of a parameter declaration), or to a particular declarator within a declaration. Where an attribute specifier is applied to a parameter declared as a function or an array, it should apply to the function or array rather than the pointer to which the parameter is implicitly converted, but this is not yet correctly implemented.
Any list of specifiers and qualifiers at the start of a declaration may contain attribute specifiers, whether or not such a list may in that context contain storage class specifiers. (Some attributes, however, are essentially in the nature of storage class specifiers, and only make sense where storage class specifiers may be used; for example, section.) There is one necessary limitation to this syntax: the first old-style parameter declaration in a function definition cannot begin with an attribute specifier, because such an attribute applies to the function instead by syntax described below (which, however, is not yet implemented in this case). In some other cases, attribute specifiers are permitted by this grammar but not yet supported by the compiler. All attribute specifiers in this place relate to the declaration as a whole. In the obsolescent usage where a type of int is implied by the absence of type specifiers, such a list of specifiers and qualifiers may be an attribute specifier list with no other specifiers or qualifiers.
At present, the first parameter in a function prototype must have some type specifier which is not an attribute specifier; this resolves an ambiguity in the interpretation of void f(int (__attribute__((foo)) x)), but is subject to change. At present, if the parentheses of a function declarator contain only attributes then those attributes are ignored, rather than yielding an error or warning or implying a single parameter of type int, but this is subject to change.
An attribute specifier list may appear immediately before a declarator (other than the first) in a comma-separated list of declarators in a declaration of more than one identifier using a single list of specifiers and qualifiers. Such attribute specifiers apply only to the identifier before whose declarator they appear. For example, in
__attribute__((noreturn)) void d0 (void),
__attribute__((format(printf, 1, 2))) d1 (const char *, ...),
d2 (void)
the noreturn attribute applies to all the functions declared; the format attribute only applies to d1.
An attribute specifier list may appear immediately before the comma, = or semicolon terminating the declaration of an identifier other than a function definition. At present, such attribute specifiers apply to the declared object or function, but in future they may attach to the outermost adjacent declarator. In simple cases there is no difference, but, for example, in
void (****f)(void) __attribute__((noreturn));
at present the noreturn attribute applies to f, which causes a warning since f is not a function, but in future it may apply to the function ****f. The precise semantics of what attributes in such cases will apply to are not yet specified. Where an assembler name for an object or function is specified (see Asm Labels), at present the attribute must follow the asm specification; in future, attributes before the asm specification may apply to the adjacent declarator, and those after it to the declared object or function.
An attribute specifier list may, in future, be permitted to appear after the declarator in a function definition (before any old-style parameter declarations or the function body).
Attribute specifiers may be mixed with type qualifiers appearing inside the [] of a parameter array declarator, in the C99 construct by which such qualifiers are applied to the pointer to which the array is implicitly converted. Such attribute specifiers apply to the pointer, not to the array, but at present this is not implemented and they are ignored.
An attribute specifier list may appear at the start of a nested declarator. At present, there are some limitations in this usage: the attributes correctly apply to the declarator, but for most individual attributes the semantics this implies are not implemented. When attribute specifiers follow the * of a pointer declarator, they may be mixed with any type qualifiers present. The following describes the formal semantics of this syntax. It will make the most sense if you are familiar with the formal specification of declarators in the ISO C standard.
Consider (as in C99 subclause 6.7.5 paragraph 4) a declaration T D1, where T contains declaration specifiers that specify a type Type (such as int) and D1 is a declarator that contains an identifier ident. The type specified for ident for derived declarators whose type does not include an attribute specifier is as in the ISO C standard.
If D1 has the form ( attribute-specifier-list D ), and the declaration T D specifies the type “derived-declarator-type-list Type” for ident, then T D1 specifies the type “derived-declarator-type-list attribute-specifier-list Type” for ident.
If D1 has the form * type-qualifier-and-attribute-specifier-list D, and the declaration T D specifies the type “derived-declarator-type-list Type” for ident, then T D1 specifies the type “derived-declarator-type-list type-qualifier-and-attribute-specifier-list Type” for ident.
For example,
void (__attribute__((noreturn)) ****f) (void);
specifies the type “pointer to pointer to pointer to pointer to non-returning function returning void”. As another example,
char *__attribute__((aligned(8))) *f;
specifies the type “pointer to 8-byte-aligned pointer to char”. Note again that this does not work with most attributes; for example, the usage of `aligned' and `noreturn' attributes given above is not yet supported.
For compatibility with existing code written for compiler versions that did not implement attributes on nested declarators, some laxity is allowed in the placing of attributes. If an attribute that only applies to types is applied to a declaration, it will be treated as applying to the type of that declaration. If an attribute that only applies to declarations is applied to the type of a declaration, it will be treated as applying to that declaration; and, for compatibility with code placing the attributes immediately before the identifier declared, such an attribute applied to a function return type will be treated as applying to the function type, and such an attribute applied to an array element type will be treated as applying to the array type. If an attribute that only applies to function types is applied to a pointer-to-function type, it will be treated as applying to the pointer target type; if such an attribute is applied to a function return type that is not a pointer-to-function type, it will be treated as applying to the function type.
This section describes the syntax with which __attribute__ may be used, and the constructs to which attribute specifiers bind, for the C language. Some details may vary for C++ and Objective-C. Because of infelicities in the grammar for attributes, some forms described here may not be successfully parsed in all cases.
There are some problems with the semantics of attributes in C++. For example, there are no manglings for attributes, although they may affect code generation, so problems may arise when attributed types are used in conjunction with templates or overloading. Similarly, typeid does not distinguish between types with different attributes. Support for attributes in C++ may be restricted in future to attributes on declarations only, but not on nested declarators.
See Function Attributes, for details of the semantics of attributes applying to functions. See Variable Attributes, for details of the semantics of attributes applying to variables. See Type Attributes, for details of the semantics of attributes applying to structure, union and enumerated types.
An attribute specifier is of the form __attribute__ ((attribute-list)). An attribute list is a possibly empty comma-separated sequence of attributes, where each attribute is one of the following:
* Empty. Empty attributes are ignored.
* A word (which may be an identifier such as unused, or a reserved word such as const).
* A word, followed by, in parentheses, parameters for the attribute. These parameters take one of the following forms:
o An identifier. For example, mode attributes use this form.
o An identifier followed by a comma and a non-empty comma-separated list of expressions. For example, format attributes use this form.
o A possibly empty comma-separated list of expressions. For example, format_arg attributes use this form with the list being a single integer constant expression, and alias attributes use this form with the list being a single string constant.
An attribute specifier list is a sequence of one or more attribute specifiers, not separated by any other tokens.
In GNU C, an attribute specifier list may appear after the colon following a label, other than a case or default label. The only attribute it makes sense to use after a label is unused. This feature is intended for code generated by programs which contains labels that may be unused but which is compiled with -Wall. It would not normally be appropriate to use in it human-written code, though it could be useful in cases where the code that jumps to the label is contained within an #ifdef conditional. GNU C++ does not permit such placement of attribute lists, as it is permissible for a declaration, which could begin with an attribute list, to be labelled in C++. Declarations cannot be labelled in C90 or C99, so the ambiguity does not arise there.
An attribute specifier list may appear as part of a struct, union or enum specifier. It may go either immediately after the struct, union or enum keyword, or after the closing brace. It is ignored if the content of the structure, union or enumerated type is not defined in the specifier in which the attribute specifier list is used—that is, in usages such as struct __attribute__((foo)) bar with no following opening brace. Where attribute specifiers follow the closing brace, they are considered to relate to the structure, union or enumerated type defined, not to any enclosing declaration the type specifier appears in, and the type defined is not complete until after the attribute specifiers.
Otherwise, an attribute specifier appears as part of a declaration, counting declarations of unnamed parameters and type names, and relates to that declaration (which may be nested in another declaration, for example in the case of a parameter declaration), or to a particular declarator within a declaration. Where an attribute specifier is applied to a parameter declared as a function or an array, it should apply to the function or array rather than the pointer to which the parameter is implicitly converted, but this is not yet correctly implemented.
Any list of specifiers and qualifiers at the start of a declaration may contain attribute specifiers, whether or not such a list may in that context contain storage class specifiers. (Some attributes, however, are essentially in the nature of storage class specifiers, and only make sense where storage class specifiers may be used; for example, section.) There is one necessary limitation to this syntax: the first old-style parameter declaration in a function definition cannot begin with an attribute specifier, because such an attribute applies to the function instead by syntax described below (which, however, is not yet implemented in this case). In some other cases, attribute specifiers are permitted by this grammar but not yet supported by the compiler. All attribute specifiers in this place relate to the declaration as a whole. In the obsolescent usage where a type of int is implied by the absence of type specifiers, such a list of specifiers and qualifiers may be an attribute specifier list with no other specifiers or qualifiers.
At present, the first parameter in a function prototype must have some type specifier which is not an attribute specifier; this resolves an ambiguity in the interpretation of void f(int (__attribute__((foo)) x)), but is subject to change. At present, if the parentheses of a function declarator contain only attributes then those attributes are ignored, rather than yielding an error or warning or implying a single parameter of type int, but this is subject to change.
An attribute specifier list may appear immediately before a declarator (other than the first) in a comma-separated list of declarators in a declaration of more than one identifier using a single list of specifiers and qualifiers. Such attribute specifiers apply only to the identifier before whose declarator they appear. For example, in
__attribute__((noreturn)) void d0 (void),
__attribute__((format(printf, 1, 2))) d1 (const char *, ...),
d2 (void)
the noreturn attribute applies to all the functions declared; the format attribute only applies to d1.
An attribute specifier list may appear immediately before the comma, = or semicolon terminating the declaration of an identifier other than a function definition. At present, such attribute specifiers apply to the declared object or function, but in future they may attach to the outermost adjacent declarator. In simple cases there is no difference, but, for example, in
void (****f)(void) __attribute__((noreturn));
at present the noreturn attribute applies to f, which causes a warning since f is not a function, but in future it may apply to the function ****f. The precise semantics of what attributes in such cases will apply to are not yet specified. Where an assembler name for an object or function is specified (see Asm Labels), at present the attribute must follow the asm specification; in future, attributes before the asm specification may apply to the adjacent declarator, and those after it to the declared object or function.
An attribute specifier list may, in future, be permitted to appear after the declarator in a function definition (before any old-style parameter declarations or the function body).
Attribute specifiers may be mixed with type qualifiers appearing inside the [] of a parameter array declarator, in the C99 construct by which such qualifiers are applied to the pointer to which the array is implicitly converted. Such attribute specifiers apply to the pointer, not to the array, but at present this is not implemented and they are ignored.
An attribute specifier list may appear at the start of a nested declarator. At present, there are some limitations in this usage: the attributes correctly apply to the declarator, but for most individual attributes the semantics this implies are not implemented. When attribute specifiers follow the * of a pointer declarator, they may be mixed with any type qualifiers present. The following describes the formal semantics of this syntax. It will make the most sense if you are familiar with the formal specification of declarators in the ISO C standard.
Consider (as in C99 subclause 6.7.5 paragraph 4) a declaration T D1, where T contains declaration specifiers that specify a type Type (such as int) and D1 is a declarator that contains an identifier ident. The type specified for ident for derived declarators whose type does not include an attribute specifier is as in the ISO C standard.
If D1 has the form ( attribute-specifier-list D ), and the declaration T D specifies the type “derived-declarator-type-list Type” for ident, then T D1 specifies the type “derived-declarator-type-list attribute-specifier-list Type” for ident.
If D1 has the form * type-qualifier-and-attribute-specifier-list D, and the declaration T D specifies the type “derived-declarator-type-list Type” for ident, then T D1 specifies the type “derived-declarator-type-list type-qualifier-and-attribute-specifier-list Type” for ident.
For example,
void (__attribute__((noreturn)) ****f) (void);
specifies the type “pointer to pointer to pointer to pointer to non-returning function returning void”. As another example,
char *__attribute__((aligned(8))) *f;
specifies the type “pointer to 8-byte-aligned pointer to char”. Note again that this does not work with most attributes; for example, the usage of `aligned' and `noreturn' attributes given above is not yet supported.
For compatibility with existing code written for compiler versions that did not implement attributes on nested declarators, some laxity is allowed in the placing of attributes. If an attribute that only applies to types is applied to a declaration, it will be treated as applying to the type of that declaration. If an attribute that only applies to declarations is applied to the type of a declaration, it will be treated as applying to that declaration; and, for compatibility with code placing the attributes immediately before the identifier declared, such an attribute applied to a function return type will be treated as applying to the function type, and such an attribute applied to an array element type will be treated as applying to the array type. If an attribute that only applies to function types is applied to a pointer-to-function type, it will be treated as applying to the pointer target type; if such an attribute is applied to a function return type that is not a pointer-to-function type, it will be treated as applying to the function type.
Specifying Attributes of Variables
http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Variable-Attributes.html#Variable-Attributes
The keyword __attribute__ allows you to specify special attributes of variables or structure fields. This keyword is followed by an attribute specification inside double parentheses. Some attributes are currently defined generically for variables. Other attributes are defined for variables on particular target systems. Other attributes are available for functions (see Function Attributes) and for types (see Type Attributes). Other front ends might define more attributes (see Extensions to the C++ Language).
You may also specify attributes with `__' preceding and following each keyword. This allows you to use them in header files without being concerned about a possible macro of the same name. For example, you may use __aligned__ instead of aligned.
See Attribute Syntax, for details of the exact syntax for using attributes.
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 the move16 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));
Whenever you leave out the alignment factor in an aligned attribute specification, the compiler automatically sets the alignment for the declared variable or field to the largest alignment which is ever used for any data type on the target machine you are compiling for. Doing this can often make copy operations more efficient, because the compiler can use whatever instructions copy the biggest chunks of memory when performing copies to or from the variables or fields that you have aligned this way.
The aligned attribute can only increase the alignment; but you can decrease it by specifying packed as well. See below.
Note that the effectiveness of aligned attributes may be limited by inherent limitations in your linker. On many systems, the linker is only able to arrange for variables to be aligned up to a certain maximum alignment. (For some linkers, the maximum supported alignment may be very very small.) If your linker is only able to align variables up to a maximum of 8 byte alignment, then specifying aligned(16) in an __attribute__ will still only provide you with 8 byte alignment. See your linker documentation for further information.
cleanup (cleanup_function)
The cleanup attribute runs a function when the variable goes out of scope. This attribute can only be applied to auto function scope variables; it may not be applied to parameters or variables with static storage duration. The function must take one parameter, a pointer to a type compatible with the variable. The return value of the function (if any) is ignored.
If -fexceptions is enabled, then cleanup_function will be run during the stack unwinding that happens during the processing of the exception. Note that the cleanup attribute does not allow the exception to be caught, only to perform an action. It is undefined what happens if cleanup_function does not return normally.
common
nocommon
The common attribute requests GCC to place a variable in “common” storage. The nocommon attribute requests the opposite—to allocate space for it directly.
These attributes override the default chosen by the -fno-common and -fcommon flags respectively.
deprecated
The deprecated attribute results in a warning if the variable is used anywhere in the source file. This is useful when identifying variables that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated variable, to enable users to easily find further information about why the variable is deprecated, or what they should do instead. Note that the warning only occurs for uses:
extern int old_var __attribute__ ((deprecated));
extern int old_var;
int new_fn () { return old_var; }
results in a warning on line 3 but not line 2.
The deprecated attribute can also be used for functions and types (see Function Attributes, see Type Attributes.)
mode (mode)
This attribute specifies the data type for the declaration—whichever type corresponds to the mode mode. This in effect lets you request an integer or floating point type according to its width.
You may also specify a mode of `byte' or `__byte__' to indicate the mode corresponding to a one-byte integer, `word' or `__word__' for the mode of a one-word integer, and `pointer' or `__pointer__' for the mode used to represent pointers.
packed
The packed attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute.
Here is a structure in which the field x is packed, so that it immediately follows a:
struct foo
{
char a;
int x[2] __attribute__ ((packed));
};
section ("section-name")
Normally, the compiler places the objects it generates in sections like data and bss. Sometimes, however, you need additional sections, or you need certain particular variables to appear in special sections, for example to map to special hardware. The section attribute specifies that a variable (or function) lives in a particular section. For example, this small program uses several specific section names:
struct duart a __attribute__ ((section ("DUART_A"))) = { 0 };
struct duart b __attribute__ ((section ("DUART_B"))) = { 0 };
char stack[10000] __attribute__ ((section ("STACK"))) = { 0 };
int init_data __attribute__ ((section ("INITDATA"))) = 0;
main()
{
/* Initialize stack pointer */
init_sp (stack + sizeof (stack));
/* Initialize initialized data */
memcpy (&init_data, &data, &edata - &data);
/* Turn on the serial ports */
init_duart (&a);
init_duart (&b);
}
Use the section attribute with an initialized definition of a global variable, as shown in the example. GCC issues a warning and otherwise ignores the section attribute in uninitialized variable declarations.
You may only use the section attribute with a fully initialized global definition because of the way linkers work. The linker requires each object be defined once, with the exception that uninitialized variables tentatively go in the common (or bss) section and can be multiply “defined”. You can force a variable to be initialized with the -fno-common flag or the nocommon attribute.
Some file formats do not support arbitrary sections so the section attribute is not available on all platforms. If you need to map the entire contents of a module to a particular section, consider using the facilities of the linker instead.
shared
On Microsoft Windows, in addition to putting variable definitions in a named section, the section can also be shared among all running copies of an executable or DLL. For example, this small program defines shared data by putting it in a named section shared and marking the section shareable:
int foo __attribute__((section ("shared"), shared)) = 0;
int
main()
{
/* Read and write foo. All running
copies see the same value. */
return 0;
}
You may only use the shared attribute along with section attribute with a fully initialized global definition because of the way linkers work. See section attribute for more information.
The shared attribute is only available on Microsoft Windows.
tls_model ("tls_model")
The tls_model attribute sets thread-local storage model (see Thread-Local) of a particular __thread variable, overriding -ftls-model= command line switch on a per-variable basis. The tls_model argument should be one of global-dynamic, local-dynamic, initial-exec or local-exec.
Not all targets support this attribute.
transparent_union
This attribute, attached to a function parameter which is a union, means that the corresponding argument may have the type of any union member, but the argument is passed as if its type were that of the first union member. For more details see See Type Attributes. You can also use this attribute on a typedef for a union data type; then it applies to all function parameters with that type.
unused
This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.
vector_size (bytes)
This attribute specifies the vector size for the variable, measured in bytes. For example, the declaration:
int foo __attribute__ ((vector_size (16)));
causes the compiler to set the mode for foo, to be 16 bytes, divided into int sized units. Assuming a 32-bit int (a vector of 4 units of 4 bytes), the corresponding mode of foo will be V4SI.
This attribute is only applicable to integral and float scalars, although arrays, pointers, and function return values are allowed in conjunction with this construct.
Aggregates with this attribute are invalid, even if they are of the same size as a corresponding scalar. For example, the declaration:
struct S { int a; };
struct S __attribute__ ((vector_size (16))) foo;
is invalid even if the size of the structure is the same as the size of the int.
weak
The weak attribute is described in See Function Attributes.
dllimport
The dllimport attribute is described in See Function Attributes.
dlexport
The dllexport attribute is described in See Function Attributes.
5.31.1 M32R/D Variable Attributes
One attribute is currently defined for the M32R/D.
model (model-name)
Use this attribute on the M32R/D to set the addressability of an object. The identifier model-name is one of small, medium, or large, representing each of the code models.
Small model objects live in the lower 16MB of memory (so that their addresses can be loaded with the ld24 instruction).
Medium and large model objects may live anywhere in the 32-bit address space (the compiler will generate seth/add3 instructions to load their addresses).
5.31.2 i386 Variable Attributes
Two attributes are currently defined for i386 configurations: ms_struct and gcc_struct
ms_struct
gcc_struct
If packed is used on a structure, or if bit-fields are used it may be that the Microsoft ABI packs them differently than GCC would normally pack them. Particularly when moving packed data between functions compiled with GCC and the native Microsoft compiler (either via function call or as data in a file), it may be necessary to access either format.
Currently -m[no-]ms-bitfields is provided for the Microsoft Windows X86 compilers to match the native Microsoft compiler.
5.31.3 Xstormy16 Variable Attributes
One attribute is currently defined for xstormy16 configurations: below100
below100
If a variable has the below100 attribute (BELOW100 is allowed also), GCC will place the variable in the first 0x100 bytes of memory and use special opcodes to access it. Such variables will be placed in either the .bss_below100 section or the .data_below100 section.
The keyword __attribute__ allows you to specify special attributes of variables or structure fields. This keyword is followed by an attribute specification inside double parentheses. Some attributes are currently defined generically for variables. Other attributes are defined for variables on particular target systems. Other attributes are available for functions (see Function Attributes) and for types (see Type Attributes). Other front ends might define more attributes (see Extensions to the C++ Language).
You may also specify attributes with `__' preceding and following each keyword. This allows you to use them in header files without being concerned about a possible macro of the same name. For example, you may use __aligned__ instead of aligned.
See Attribute Syntax, for details of the exact syntax for using attributes.
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 the move16 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));
Whenever you leave out the alignment factor in an aligned attribute specification, the compiler automatically sets the alignment for the declared variable or field to the largest alignment which is ever used for any data type on the target machine you are compiling for. Doing this can often make copy operations more efficient, because the compiler can use whatever instructions copy the biggest chunks of memory when performing copies to or from the variables or fields that you have aligned this way.
The aligned attribute can only increase the alignment; but you can decrease it by specifying packed as well. See below.
Note that the effectiveness of aligned attributes may be limited by inherent limitations in your linker. On many systems, the linker is only able to arrange for variables to be aligned up to a certain maximum alignment. (For some linkers, the maximum supported alignment may be very very small.) If your linker is only able to align variables up to a maximum of 8 byte alignment, then specifying aligned(16) in an __attribute__ will still only provide you with 8 byte alignment. See your linker documentation for further information.
cleanup (cleanup_function)
The cleanup attribute runs a function when the variable goes out of scope. This attribute can only be applied to auto function scope variables; it may not be applied to parameters or variables with static storage duration. The function must take one parameter, a pointer to a type compatible with the variable. The return value of the function (if any) is ignored.
If -fexceptions is enabled, then cleanup_function will be run during the stack unwinding that happens during the processing of the exception. Note that the cleanup attribute does not allow the exception to be caught, only to perform an action. It is undefined what happens if cleanup_function does not return normally.
common
nocommon
The common attribute requests GCC to place a variable in “common” storage. The nocommon attribute requests the opposite—to allocate space for it directly.
These attributes override the default chosen by the -fno-common and -fcommon flags respectively.
deprecated
The deprecated attribute results in a warning if the variable is used anywhere in the source file. This is useful when identifying variables that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated variable, to enable users to easily find further information about why the variable is deprecated, or what they should do instead. Note that the warning only occurs for uses:
extern int old_var __attribute__ ((deprecated));
extern int old_var;
int new_fn () { return old_var; }
results in a warning on line 3 but not line 2.
The deprecated attribute can also be used for functions and types (see Function Attributes, see Type Attributes.)
mode (mode)
This attribute specifies the data type for the declaration—whichever type corresponds to the mode mode. This in effect lets you request an integer or floating point type according to its width.
You may also specify a mode of `byte' or `__byte__' to indicate the mode corresponding to a one-byte integer, `word' or `__word__' for the mode of a one-word integer, and `pointer' or `__pointer__' for the mode used to represent pointers.
packed
The packed attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute.
Here is a structure in which the field x is packed, so that it immediately follows a:
struct foo
{
char a;
int x[2] __attribute__ ((packed));
};
section ("section-name")
Normally, the compiler places the objects it generates in sections like data and bss. Sometimes, however, you need additional sections, or you need certain particular variables to appear in special sections, for example to map to special hardware. The section attribute specifies that a variable (or function) lives in a particular section. For example, this small program uses several specific section names:
struct duart a __attribute__ ((section ("DUART_A"))) = { 0 };
struct duart b __attribute__ ((section ("DUART_B"))) = { 0 };
char stack[10000] __attribute__ ((section ("STACK"))) = { 0 };
int init_data __attribute__ ((section ("INITDATA"))) = 0;
main()
{
/* Initialize stack pointer */
init_sp (stack + sizeof (stack));
/* Initialize initialized data */
memcpy (&init_data, &data, &edata - &data);
/* Turn on the serial ports */
init_duart (&a);
init_duart (&b);
}
Use the section attribute with an initialized definition of a global variable, as shown in the example. GCC issues a warning and otherwise ignores the section attribute in uninitialized variable declarations.
You may only use the section attribute with a fully initialized global definition because of the way linkers work. The linker requires each object be defined once, with the exception that uninitialized variables tentatively go in the common (or bss) section and can be multiply “defined”. You can force a variable to be initialized with the -fno-common flag or the nocommon attribute.
Some file formats do not support arbitrary sections so the section attribute is not available on all platforms. If you need to map the entire contents of a module to a particular section, consider using the facilities of the linker instead.
shared
On Microsoft Windows, in addition to putting variable definitions in a named section, the section can also be shared among all running copies of an executable or DLL. For example, this small program defines shared data by putting it in a named section shared and marking the section shareable:
int foo __attribute__((section ("shared"), shared)) = 0;
int
main()
{
/* Read and write foo. All running
copies see the same value. */
return 0;
}
You may only use the shared attribute along with section attribute with a fully initialized global definition because of the way linkers work. See section attribute for more information.
The shared attribute is only available on Microsoft Windows.
tls_model ("tls_model")
The tls_model attribute sets thread-local storage model (see Thread-Local) of a particular __thread variable, overriding -ftls-model= command line switch on a per-variable basis. The tls_model argument should be one of global-dynamic, local-dynamic, initial-exec or local-exec.
Not all targets support this attribute.
transparent_union
This attribute, attached to a function parameter which is a union, means that the corresponding argument may have the type of any union member, but the argument is passed as if its type were that of the first union member. For more details see See Type Attributes. You can also use this attribute on a typedef for a union data type; then it applies to all function parameters with that type.
unused
This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.
vector_size (bytes)
This attribute specifies the vector size for the variable, measured in bytes. For example, the declaration:
int foo __attribute__ ((vector_size (16)));
causes the compiler to set the mode for foo, to be 16 bytes, divided into int sized units. Assuming a 32-bit int (a vector of 4 units of 4 bytes), the corresponding mode of foo will be V4SI.
This attribute is only applicable to integral and float scalars, although arrays, pointers, and function return values are allowed in conjunction with this construct.
Aggregates with this attribute are invalid, even if they are of the same size as a corresponding scalar. For example, the declaration:
struct S { int a; };
struct S __attribute__ ((vector_size (16))) foo;
is invalid even if the size of the structure is the same as the size of the int.
weak
The weak attribute is described in See Function Attributes.
dllimport
The dllimport attribute is described in See Function Attributes.
dlexport
The dllexport attribute is described in See Function Attributes.
5.31.1 M32R/D Variable Attributes
One attribute is currently defined for the M32R/D.
model (model-name)
Use this attribute on the M32R/D to set the addressability of an object. The identifier model-name is one of small, medium, or large, representing each of the code models.
Small model objects live in the lower 16MB of memory (so that their addresses can be loaded with the ld24 instruction).
Medium and large model objects may live anywhere in the 32-bit address space (the compiler will generate seth/add3 instructions to load their addresses).
5.31.2 i386 Variable Attributes
Two attributes are currently defined for i386 configurations: ms_struct and gcc_struct
ms_struct
gcc_struct
If packed is used on a structure, or if bit-fields are used it may be that the Microsoft ABI packs them differently than GCC would normally pack them. Particularly when moving packed data between functions compiled with GCC and the native Microsoft compiler (either via function call or as data in a file), it may be necessary to access either format.
Currently -m[no-]ms-bitfields is provided for the Microsoft Windows X86 compilers to match the native Microsoft compiler.
5.31.3 Xstormy16 Variable Attributes
One attribute is currently defined for xstormy16 configurations: below100
below100
If a variable has the below100 attribute (BELOW100 is allowed also), GCC will place the variable in the first 0x100 bytes of memory and use special opcodes to access it. Such variables will be placed in either the .bss_below100 section or the .data_below100 section.
Specifying Attributes of Types
http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Type-Attributes.html#Type-Attributes
The keyword __attribute__ allows you to specify special attributes of struct and union types when you define such types. This keyword is followed by an attribute specification inside double parentheses. Six attributes are currently defined for types: aligned, packed, transparent_union, unused, deprecated and may_alias. Other attributes are defined for functions (see Function Attributes) and for variables (see Variable Attributes).
You may also specify any one of these attributes with `__' preceding and following its keyword. This allows you to use these attributes in header files without being concerned about a possible macro of the same name. For example, you may use __aligned__ instead of aligned.
You may specify the aligned and transparent_union attributes either in a typedef declaration or just past the closing curly brace of a complete enum, struct or union type definition and the packed attribute only past the closing brace of a definition.
You may also specify attributes between the enum, struct or union tag and the name of the type rather than after the closing brace.
See Attribute Syntax, for details of the exact syntax for using attributes.
aligned (alignment)
This attribute specifies a minimum alignment (in bytes) for variables of the specified type. For example, the declarations:
struct S { short f[3]; } __attribute__ ((aligned (8)));
typedef int more_aligned_int __attribute__ ((aligned (8)));
force the compiler to insure (as far as it can) that each variable whose type is struct S or more_aligned_int will be allocated and aligned at least on a 8-byte boundary. On a SPARC, having all variables of type struct S aligned to 8-byte boundaries allows the compiler to use the ldd and std (doubleword load and store) instructions when copying one variable of type struct S to another, thus improving run-time efficiency.
Note that the alignment of any given struct or union type is required by the ISO C standard to be at least a perfect multiple of the lowest common multiple of the alignments of all of the members of the struct or union in question. This means that you can effectively adjust the alignment of a struct or union type by attaching an aligned attribute to any one of the members of such a type, but the notation illustrated in the example above is a more obvious, intuitive, and readable way to request the compiler to adjust the alignment of an entire struct or union type.
As in the preceding example, you can explicitly specify the alignment (in bytes) that you wish the compiler to use for a given struct or union type. Alternatively, you can leave out the alignment factor and just ask the compiler to align a type to the maximum useful alignment for the target machine you are compiling for. For example, you could write:
struct S { short f[3]; } __attribute__ ((aligned));
Whenever you leave out the alignment factor in an aligned attribute specification, the compiler automatically sets the alignment for the type to the largest alignment which is ever used for any data type on the target machine you are compiling for. Doing this can often make copy operations more efficient, because the compiler can use whatever instructions copy the biggest chunks of memory when performing copies to or from the variables which have types that you have aligned this way.
In the example above, if the size of each short is 2 bytes, then the size of the entire struct S type is 6 bytes. The smallest power of two which is greater than or equal to that is 8, so the compiler sets the alignment for the entire struct S type to 8 bytes.
Note that although you can ask the compiler to select a time-efficient alignment for a given type and then declare only individual stand-alone objects of that type, the compiler's ability to select a time-efficient alignment is primarily useful only when you plan to create arrays of variables having the relevant (efficiently aligned) type. If you declare or use arrays of variables of an efficiently-aligned type, then it is likely that your program will also be doing pointer arithmetic (or subscripting, which amounts to the same thing) on pointers to the relevant type, and the code that the compiler generates for these pointer arithmetic operations will often be more efficient for efficiently-aligned types than for other types.
The aligned attribute can only increase the alignment; but you can decrease it by specifying packed as well. See below.
Note that the effectiveness of aligned attributes may be limited by inherent limitations in your linker. On many systems, the linker is only able to arrange for variables to be aligned up to a certain maximum alignment. (For some linkers, the maximum supported alignment may be very very small.) If your linker is only able to align variables up to a maximum of 8 byte alignment, then specifying aligned(16) in an __attribute__ will still only provide you with 8 byte alignment. See your linker documentation for further information.
packed
This attribute, attached to struct or union type definition, specifies that each member of the structure or union is placed to minimize the memory required. When attached to an enum definition, it indicates that the smallest integral type should be used.
Specifying this attribute for struct and union types is equivalent to specifying the packed attribute on each of the structure or union members. Specifying the -fshort-enums flag on the line is equivalent to specifying the packed attribute on all enum definitions.
In the following example struct my_packed_struct's members are packed closely together, but the internal layout of its s member is not packed—to do that, struct my_unpacked_struct would need to be packed too.
struct my_unpacked_struct
{
char c;
int i;
};
struct my_packed_struct __attribute__ ((__packed__))
{
char c;
int i;
struct my_unpacked_struct s;
};
You may only specify this attribute on the definition of a enum, struct or union, not on a typedef which does not also define the enumerated type, structure or union.
transparent_union
This attribute, attached to a union type definition, indicates that any function parameter having that union type causes calls to that function to be treated in a special way.
First, the argument corresponding to a transparent union type can be of any type in the union; no cast is required. Also, if the union contains a pointer type, the corresponding argument can be a null pointer constant or a void pointer expression; and if the union contains a void pointer type, the corresponding argument can be any pointer expression. If the union member type is a pointer, qualifiers like const on the referenced type must be respected, just as with normal pointer conversions.
Second, the argument is passed to the function using the calling conventions of the first member of the transparent union, not the calling conventions of the union itself. All members of the union must have the same machine representation; this is necessary for this argument passing to work properly.
Transparent unions are designed for library functions that have multiple interfaces for compatibility reasons. For example, suppose the wait function must accept either a value of type int * to comply with Posix, or a value of type union wait * to comply with the 4.1BSD interface. If wait's parameter were void *, wait would accept both kinds of arguments, but it would also accept any other pointer type and this would make argument type checking less useful. Instead, might define the interface as follows:
typedef union
{
int *__ip;
union wait *__up;
} wait_status_ptr_t __attribute__ ((__transparent_union__));
pid_t wait (wait_status_ptr_t);
This interface allows either int * or union wait * arguments to be passed, using the int * calling convention. The program can call wait with arguments of either type:
int w1 () { int w; return wait (&w); }
int w2 () { union wait w; return wait (&w); }
With this interface, wait's implementation might look like this:
pid_t wait (wait_status_ptr_t p)
{
return waitpid (-1, p.__ip, 0);
}
unused
When attached to a type (including a union or a struct), this attribute means that variables of that type are meant to appear possibly unused. GCC will not produce a warning for any variables of that type, even if the variable appears to do nothing. This is often the case with lock or thread classes, which are usually defined and then not referenced, but contain constructors and destructors that have nontrivial bookkeeping functions.
deprecated
The deprecated attribute results in a warning if the type is used anywhere in the source file. This is useful when identifying types that are expected to be removed in a future version of a program. If possible, the warning also includes the location of the declaration of the deprecated type, to enable users to easily find further information about why the type is deprecated, or what they should do instead. Note that the warnings only occur for uses and then only if the type is being applied to an identifier that itself is not being declared as deprecated.
typedef int T1 __attribute__ ((deprecated));
T1 x;
typedef T1 T2;
T2 y;
typedef T1 T3 __attribute__ ((deprecated));
T3 z __attribute__ ((deprecated));
results in a warning on line 2 and 3 but not lines 4, 5, or 6. No warning is issued for line 4 because T2 is not explicitly deprecated. Line 5 has no warning because T3 is explicitly deprecated. Similarly for line 6.
The deprecated attribute can also be used for functions and variables (see Function Attributes, see Variable Attributes.)
may_alias
Accesses to objects with types with this attribute are not subjected to type-based alias analysis, but are instead assumed to be able to alias any other type of objects, just like the char type. See -fstrict-aliasing for more information on aliasing issues.
Example of use:
typedef short __attribute__((__may_alias__)) short_a;
int
main (void)
{
int a = 0x12345678;
short_a *b = (short_a *) &a;
b[1] = 0;
if (a == 0x12345678)
abort();
exit(0);
}
If you replaced short_a with short in the variable declaration, the above program would abort when compiled with -fstrict-aliasing, which is on by default at -O2 or above in recent GCC versions.
5.32.1 ARM Type Attributes
On those ARM targets that support dllimport (such as Symbian OS), you can use the notshared attribute to indicate that the virtual table and other similar data for a class should not be exported from a DLL. For example:
class __declspec(notshared) C {
public:
__declspec(dllimport) C();
virtual void f();
}
__declspec(dllexport)
C::C() {}
In this code, C::C is exported from the current DLL, but the virtual table for C is not exported. (You can use __attribute__ instead of __declspec if you prefer, but most Symbian OS code uses __declspec.)
5.32.2 i386 Type Attributes
Two attributes are currently defined for i386 configurations: ms_struct and gcc_struct
ms_struct
gcc_struct
If packed is used on a structure, or if bit-fields are used it may be that the Microsoft ABI packs them differently than GCC would normally pack them. Particularly when moving packed data between functions compiled with GCC and the native Microsoft compiler (either via function call or as data in a file), it may be necessary to access either format.
Currently -m[no-]ms-bitfields is provided for the Microsoft Windows X86 compilers to match the native Microsoft compiler.
To specify multiple attributes, separate them by commas within the double parentheses: for example, `__attribute__ ((aligned (16), packed))'.
The keyword __attribute__ allows you to specify special attributes of struct and union types when you define such types. This keyword is followed by an attribute specification inside double parentheses. Six attributes are currently defined for types: aligned, packed, transparent_union, unused, deprecated and may_alias. Other attributes are defined for functions (see Function Attributes) and for variables (see Variable Attributes).
You may also specify any one of these attributes with `__' preceding and following its keyword. This allows you to use these attributes in header files without being concerned about a possible macro of the same name. For example, you may use __aligned__ instead of aligned.
You may specify the aligned and transparent_union attributes either in a typedef declaration or just past the closing curly brace of a complete enum, struct or union type definition and the packed attribute only past the closing brace of a definition.
You may also specify attributes between the enum, struct or union tag and the name of the type rather than after the closing brace.
See Attribute Syntax, for details of the exact syntax for using attributes.
aligned (alignment)
This attribute specifies a minimum alignment (in bytes) for variables of the specified type. For example, the declarations:
struct S { short f[3]; } __attribute__ ((aligned (8)));
typedef int more_aligned_int __attribute__ ((aligned (8)));
force the compiler to insure (as far as it can) that each variable whose type is struct S or more_aligned_int will be allocated and aligned at least on a 8-byte boundary. On a SPARC, having all variables of type struct S aligned to 8-byte boundaries allows the compiler to use the ldd and std (doubleword load and store) instructions when copying one variable of type struct S to another, thus improving run-time efficiency.
Note that the alignment of any given struct or union type is required by the ISO C standard to be at least a perfect multiple of the lowest common multiple of the alignments of all of the members of the struct or union in question. This means that you can effectively adjust the alignment of a struct or union type by attaching an aligned attribute to any one of the members of such a type, but the notation illustrated in the example above is a more obvious, intuitive, and readable way to request the compiler to adjust the alignment of an entire struct or union type.
As in the preceding example, you can explicitly specify the alignment (in bytes) that you wish the compiler to use for a given struct or union type. Alternatively, you can leave out the alignment factor and just ask the compiler to align a type to the maximum useful alignment for the target machine you are compiling for. For example, you could write:
struct S { short f[3]; } __attribute__ ((aligned));
Whenever you leave out the alignment factor in an aligned attribute specification, the compiler automatically sets the alignment for the type to the largest alignment which is ever used for any data type on the target machine you are compiling for. Doing this can often make copy operations more efficient, because the compiler can use whatever instructions copy the biggest chunks of memory when performing copies to or from the variables which have types that you have aligned this way.
In the example above, if the size of each short is 2 bytes, then the size of the entire struct S type is 6 bytes. The smallest power of two which is greater than or equal to that is 8, so the compiler sets the alignment for the entire struct S type to 8 bytes.
Note that although you can ask the compiler to select a time-efficient alignment for a given type and then declare only individual stand-alone objects of that type, the compiler's ability to select a time-efficient alignment is primarily useful only when you plan to create arrays of variables having the relevant (efficiently aligned) type. If you declare or use arrays of variables of an efficiently-aligned type, then it is likely that your program will also be doing pointer arithmetic (or subscripting, which amounts to the same thing) on pointers to the relevant type, and the code that the compiler generates for these pointer arithmetic operations will often be more efficient for efficiently-aligned types than for other types.
The aligned attribute can only increase the alignment; but you can decrease it by specifying packed as well. See below.
Note that the effectiveness of aligned attributes may be limited by inherent limitations in your linker. On many systems, the linker is only able to arrange for variables to be aligned up to a certain maximum alignment. (For some linkers, the maximum supported alignment may be very very small.) If your linker is only able to align variables up to a maximum of 8 byte alignment, then specifying aligned(16) in an __attribute__ will still only provide you with 8 byte alignment. See your linker documentation for further information.
packed
This attribute, attached to struct or union type definition, specifies that each member of the structure or union is placed to minimize the memory required. When attached to an enum definition, it indicates that the smallest integral type should be used.
Specifying this attribute for struct and union types is equivalent to specifying the packed attribute on each of the structure or union members. Specifying the -fshort-enums flag on the line is equivalent to specifying the packed attribute on all enum definitions.
In the following example struct my_packed_struct's members are packed closely together, but the internal layout of its s member is not packed—to do that, struct my_unpacked_struct would need to be packed too.
struct my_unpacked_struct
{
char c;
int i;
};
struct my_packed_struct __attribute__ ((__packed__))
{
char c;
int i;
struct my_unpacked_struct s;
};
You may only specify this attribute on the definition of a enum, struct or union, not on a typedef which does not also define the enumerated type, structure or union.
transparent_union
This attribute, attached to a union type definition, indicates that any function parameter having that union type causes calls to that function to be treated in a special way.
First, the argument corresponding to a transparent union type can be of any type in the union; no cast is required. Also, if the union contains a pointer type, the corresponding argument can be a null pointer constant or a void pointer expression; and if the union contains a void pointer type, the corresponding argument can be any pointer expression. If the union member type is a pointer, qualifiers like const on the referenced type must be respected, just as with normal pointer conversions.
Second, the argument is passed to the function using the calling conventions of the first member of the transparent union, not the calling conventions of the union itself. All members of the union must have the same machine representation; this is necessary for this argument passing to work properly.
Transparent unions are designed for library functions that have multiple interfaces for compatibility reasons. For example, suppose the wait function must accept either a value of type int * to comply with Posix, or a value of type union wait * to comply with the 4.1BSD interface. If wait's parameter were void *, wait would accept both kinds of arguments, but it would also accept any other pointer type and this would make argument type checking less useful. Instead,
typedef union
{
int *__ip;
union wait *__up;
} wait_status_ptr_t __attribute__ ((__transparent_union__));
pid_t wait (wait_status_ptr_t);
This interface allows either int * or union wait * arguments to be passed, using the int * calling convention. The program can call wait with arguments of either type:
int w1 () { int w; return wait (&w); }
int w2 () { union wait w; return wait (&w); }
With this interface, wait's implementation might look like this:
pid_t wait (wait_status_ptr_t p)
{
return waitpid (-1, p.__ip, 0);
}
unused
When attached to a type (including a union or a struct), this attribute means that variables of that type are meant to appear possibly unused. GCC will not produce a warning for any variables of that type, even if the variable appears to do nothing. This is often the case with lock or thread classes, which are usually defined and then not referenced, but contain constructors and destructors that have nontrivial bookkeeping functions.
deprecated
The deprecated attribute results in a warning if the type is used anywhere in the source file. This is useful when identifying types that are expected to be removed in a future version of a program. If possible, the warning also includes the location of the declaration of the deprecated type, to enable users to easily find further information about why the type is deprecated, or what they should do instead. Note that the warnings only occur for uses and then only if the type is being applied to an identifier that itself is not being declared as deprecated.
typedef int T1 __attribute__ ((deprecated));
T1 x;
typedef T1 T2;
T2 y;
typedef T1 T3 __attribute__ ((deprecated));
T3 z __attribute__ ((deprecated));
results in a warning on line 2 and 3 but not lines 4, 5, or 6. No warning is issued for line 4 because T2 is not explicitly deprecated. Line 5 has no warning because T3 is explicitly deprecated. Similarly for line 6.
The deprecated attribute can also be used for functions and variables (see Function Attributes, see Variable Attributes.)
may_alias
Accesses to objects with types with this attribute are not subjected to type-based alias analysis, but are instead assumed to be able to alias any other type of objects, just like the char type. See -fstrict-aliasing for more information on aliasing issues.
Example of use:
typedef short __attribute__((__may_alias__)) short_a;
int
main (void)
{
int a = 0x12345678;
short_a *b = (short_a *) &a;
b[1] = 0;
if (a == 0x12345678)
abort();
exit(0);
}
If you replaced short_a with short in the variable declaration, the above program would abort when compiled with -fstrict-aliasing, which is on by default at -O2 or above in recent GCC versions.
5.32.1 ARM Type Attributes
On those ARM targets that support dllimport (such as Symbian OS), you can use the notshared attribute to indicate that the virtual table and other similar data for a class should not be exported from a DLL. For example:
class __declspec(notshared) C {
public:
__declspec(dllimport) C();
virtual void f();
}
__declspec(dllexport)
C::C() {}
In this code, C::C is exported from the current DLL, but the virtual table for C is not exported. (You can use __attribute__ instead of __declspec if you prefer, but most Symbian OS code uses __declspec.)
5.32.2 i386 Type Attributes
Two attributes are currently defined for i386 configurations: ms_struct and gcc_struct
ms_struct
gcc_struct
If packed is used on a structure, or if bit-fields are used it may be that the Microsoft ABI packs them differently than GCC would normally pack them. Particularly when moving packed data between functions compiled with GCC and the native Microsoft compiler (either via function call or as data in a file), it may be necessary to access either format.
Currently -m[no-]ms-bitfields is provided for the Microsoft Windows X86 compilers to match the native Microsoft compiler.
To specify multiple attributes, separate them by commas within the double parentheses: for example, `__attribute__ ((aligned (16), packed))'.
Declaring Attributes of Functions
以下內容來自
http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html
放到這裡只是讓自己便於查閱!無其它意途。
In GNU C, you declare certain things about functions called in your program which help the compiler optimize function calls and check your code more carefully.
The keyword __attribute__ allows you to specify special attributes when making a declaration. This keyword is followed by an attribute specification inside double parentheses. The following attributes are currently defined for functions on all targets: noreturn, noinline, always_inline, pure, const, nothrow, sentinel, format, format_arg, no_instrument_function, section, constructor, destructor, used, unused, deprecated, weak, malloc, alias, warn_unused_result and nonnull. Several other attributes are defined for functions on particular target systems. Other attributes, including section are supported for variables declarations (see Variable Attributes) and for types (see Type Attributes).
You may also specify attributes with `__' preceding and following each keyword. This allows you to use them in header files without being concerned about a possible macro of the same name. For example, you may use __noreturn__ instead of noreturn.
See Attribute Syntax, for details of the exact syntax for using attributes.
alias ("target")
The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified. For instance,
void __f () { /* Do something. */; }
void f () __attribute__ ((weak, alias ("__f")));
declares `f' to be a weak alias for `__f'. In C++, the mangled name for the target must be used. It is an error if `__f' is not defined in the same translation unit.
Not all target machines support this attribute.
always_inline
Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level was specified.
cdecl
On the Intel 386, the cdecl attribute causes the compiler to assume that the calling function will pop off the stack space used to pass arguments. This is useful to override the effects of the -mrtd switch.
const
Many functions do not examine any values except their arguments, and have no effects except the return value. Basically this is just slightly more strict class than the pure attribute below, since function is not allowed to read global memory.
Note that a function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It does not make sense for a const function to return void.
The attribute const is not implemented in GCC versions earlier than 2.5. An alternative way to declare that a function has no side effects, which works in the current version and in some older versions, is as follows:
typedef int intfn ();
extern const intfn square;
This approach does not work in GNU C++ from 2.6.0 on, since the language specifies that the `const' must be attached to the return value.
constructor
destructor
The constructor attribute causes the function to be called automatically before execution enters main (). Similarly, the destructor attribute causes the function to be called automatically after main () has completed or exit () has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program.
These attributes are not currently implemented for Objective-C.
deprecated
The deprecated attribute results in a warning if the function is used anywhere in the source file. This is useful when identifying functions that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated function, to enable users to easily find further information about why the function is deprecated, or what they should do instead. Note that the warnings only occurs for uses:
int old_fn () __attribute__ ((deprecated));
int old_fn ();
int (*fn_ptr)() = old_fn;
results in a warning on line 3 but not line 2.
The deprecated attribute can also be used for variables and types (see Variable Attributes, see Type Attributes.)
dllexport
On Microsoft Windows targets and Symbian OS targets the dllexport attribute causes the compiler to provide a global pointer to a pointer in a DLL, so that it can be referenced with the dllimport attribute. On Microsoft Windows targets, the pointer name is formed by combining _imp__ and the function or variable name.
You can use __declspec(dllexport) as a synonym for __attribute__ ((dllexport)) for compatibility with other compilers.
On systems that support the visibility attribute, this attribute also implies “default” visibility, unless a visibility attribute is explicitly specified. You should avoid the use of dllexport with “hidden” or “internal” visibility; in the future GCC may issue an error for those cases.
Currently, the dllexport attribute is ignored for inlined functions, unless the -fkeep-inline-functions flag has been used. The attribute is also ignored for undefined symbols.
When applied to C++ classes, the attribute marks defined non-inlined member functions and static data members as exports. Static consts initialized in-class are not marked unless they are also defined out-of-class.
For Microsoft Windows targets there are alternative methods for including the symbol in the DLL's export table such as using a .def file with an EXPORTS section or, with GNU ld, using the --export-all linker flag.
dllimport
On Microsoft Windows and Symbian OS targets, the dllimport attribute causes the compiler to reference a function or variable via a global pointer to a pointer that is set up by the DLL exporting the symbol. The attribute implies extern storage. On Microsoft Windows targets, the pointer name is formed by combining _imp__ and the function or variable name.
You can use __declspec(dllimport) as a synonym for __attribute__ ((dllimport)) for compatibility with other compilers.
Currently, the attribute is ignored for inlined functions. If the attribute is applied to a symbol definition, an error is reported. If a symbol previously declared dllimport is later defined, the attribute is ignored in subsequent references, and a warning is emitted. The attribute is also overridden by a subsequent declaration as dllexport.
When applied to C++ classes, the attribute marks non-inlined member functions and static data members as imports. However, the attribute is ignored for virtual methods to allow creation of vtables using thunks.
On the SH Symbian OS target the dllimport attribute also has another affect—it can cause the vtable and run-time type information for a class to be exported. This happens when the class has a dllimport'ed constructor or a non-inline, non-pure virtual function and, for either of those two conditions, the class also has a inline constructor or destructor and has a key function that is defined in the current translation unit.
For Microsoft Windows based targets the use of the dllimport attribute on functions is not necessary, but provides a small performance benefit by eliminating a thunk in the DLL. The use of the dllimport attribute on imported variables was required on older versions of the GNU linker, but can now be avoided by passing the --enable-auto-import switch to the GNU linker. As with functions, using the attribute for a variable eliminates a thunk in the DLL.
One drawback to using this attribute is that a pointer to a function or variable marked as dllimport cannot be used as a constant address. On Microsoft Windows targets, the attribute can be disabled for functions by setting the -mnop-fun-dllimport flag.
eightbit_data
Use this attribute on the H8/300, H8/300H, and H8S to indicate that the specified variable should be placed into the eight bit data section. The compiler will generate more efficient code for certain operations on data in the eight bit data area. Note the eight bit data area is limited to 256 bytes of data.
You must use GAS and GLD from GNU binutils version 2.7 or later for this attribute to work correctly.
far
On 68HC11 and 68HC12 the far attribute causes the compiler to use a calling convention that takes care of switching memory banks when entering and leaving a function. This calling convention is also the default when using the -mlong-calls option.
On 68HC12 the compiler will use the call and rtc instructions to call and return from a function.
On 68HC11 the compiler will generate a sequence of instructions to invoke a board-specific routine to switch the memory bank and call the real function. The board-specific routine simulates a call. At the end of a function, it will jump to a board-specific routine instead of using rts. The board-specific return routine simulates the rtc.
fastcall
On the Intel 386, the fastcall attribute causes the compiler to pass the first two arguments in the registers ECX and EDX. Subsequent arguments are passed on the stack. The called function will pop the arguments off the stack. If the number of arguments is variable all arguments are pushed on the stack.
format (archetype, string-index, first-to-check)
The format attribute specifies that a function takes printf, scanf, strftime or strfmon style arguments which should be type-checked against a format string. For example, the declaration:
extern int
my_printf (void *my_object, const char *my_format, ...)
__attribute__ ((format (printf, 2, 3)));
causes the compiler to check the arguments in calls to my_printf for consistency with the printf style format string argument my_format.
The parameter archetype determines how the format string is interpreted, and should be printf, scanf, strftime or strfmon. (You can also use __printf__, __scanf__, __strftime__ or __strfmon__.) The parameter string-index specifies which argument is the format string argument (starting from 1), while first-to-check is the number of the first argument to check against the format string. For functions where the arguments are not available to be checked (such as vprintf), specify the third parameter as zero. In this case the compiler only checks the format string for consistency. For strftime formats, the third parameter is required to be zero. Since non-static C++ methods have an implicit this argument, the arguments of such methods should be counted from two, not one, when giving values for string-index and first-to-check.
In the example above, the format string (my_format) is the second argument of the function my_print, and the arguments to check start with the third argument, so the correct parameters for the format attribute are 2 and 3.
The format attribute allows you to identify your own functions which take format strings as arguments, so that GCC can check the calls to these functions for errors. The compiler always (unless -ffreestanding or -fno-builtin is used) checks formats for the standard library functions printf, fprintf, sprintf, scanf, fscanf, sscanf, strftime, vprintf, vfprintf and vsprintf whenever such warnings are requested (using -Wformat), so there is no need to modify the header file stdio.h. In C99 mode, the functions snprintf, vsnprintf, vscanf, vfscanf and vsscanf are also checked. Except in strictly conforming C standard modes, the X/Open function strfmon is also checked as are printf_unlocked and fprintf_unlocked. See Options Controlling C Dialect.
The target may provide additional types of format checks. See Format Checks Specific to Particular Target Machines.
format_arg (string-index)
The format_arg attribute specifies that a function takes a format string for a printf, scanf, strftime or strfmon style function and modifies it (for example, to translate it into another language), so the result can be passed to a printf, scanf, strftime or strfmon style function (with the remaining arguments to the format function the same as they would have been for the unmodified string). For example, the declaration:
extern char *
my_dgettext (char *my_domain, const char *my_format)
__attribute__ ((format_arg (2)));
causes the compiler to check the arguments in calls to a printf, scanf, strftime or strfmon type function, whose format string argument is a call to the my_dgettext function, for consistency with the format string argument my_format. If the format_arg attribute had not been specified, all the compiler could tell in such calls to format functions would be that the format string argument is not constant; this would generate a warning when -Wformat-nonliteral is used, but the calls could not be checked without the attribute.
The parameter string-index specifies which argument is the format string argument (starting from one). Since non-static C++ methods have an implicit this argument, the arguments of such methods should be counted from two.
The format-arg attribute allows you to identify your own functions which modify format strings, so that GCC can check the calls to printf, scanf, strftime or strfmon type function whose operands are a call to one of your own function. The compiler always treats gettext, dgettext, and dcgettext in this manner except when strict ISO C support is requested by -ansi or an appropriate -std option, or -ffreestanding or -fno-builtin is used. See Options Controlling C Dialect.
function_vector
Use this attribute on the H8/300, H8/300H, and H8S to indicate that the specified function should be called through the function vector. Calling a function through the function vector will reduce code size, however; the function vector has a limited size (maximum 128 entries on the H8/300 and 64 entries on the H8/300H and H8S) and shares space with the interrupt vector.
You must use GAS and GLD from GNU binutils version 2.7 or later for this attribute to work correctly.
interrupt
Use this attribute on the ARM, AVR, C4x, M32R/D and Xstormy16 ports to indicate that the specified function is an interrupt handler. The compiler will generate function entry and exit sequences suitable for use in an interrupt handler when this attribute is present.
Note, interrupt handlers for the m68k, H8/300, H8/300H, H8S, and SH processors can be specified via the interrupt_handler attribute.
Note, on the AVR, interrupts will be enabled inside the function.
Note, for the ARM, you can specify the kind of interrupt to be handled by adding an optional parameter to the interrupt attribute like this:
void f () __attribute__ ((interrupt ("IRQ")));
Permissible values for this parameter are: IRQ, FIQ, SWI, ABORT and UNDEF.
interrupt_handler
Use this attribute on the m68k, H8/300, H8/300H, H8S, and SH to indicate that the specified function is an interrupt handler. The compiler will generate function entry and exit sequences suitable for use in an interrupt handler when this attribute is present.
long_call/short_call
This attribute specifies how a particular function is called on ARM. Both attributes override the -mlong-calls (see ARM Options) command line switch and #pragma long_calls settings. The long_call attribute causes the compiler to always call the function by first loading its address into a register and then using the contents of that register. The short_call attribute always places the offset to the function from the call site into the `BL' instruction directly.
longcall/shortcall
On the RS/6000 and PowerPC, the longcall attribute causes the compiler to always call this function via a pointer, just as it would if the -mlongcall option had been specified. The shortcall attribute causes the compiler not to do this. These attributes override both the -mlongcall switch and the #pragma longcall setting.
See RS/6000 and PowerPC Options, for more information on whether long calls are necessary.
malloc
The malloc attribute is used to tell the compiler that a function may be treated as if any non-NULL pointer it returns cannot alias any other pointer valid when the function returns. This will often improve optimization. Standard functions with this property include malloc and calloc. realloc-like functions have this property as long as the old pointer is never referred to (including comparing it to the new pointer) after the function returns a non-NULL value.
model (model-name)
On the M32R/D, use this attribute to set the addressability of an object, and of the code generated for a function. The identifier model-name is one of small, medium, or large, representing each of the code models.
Small model objects live in the lower 16MB of memory (so that their addresses can be loaded with the ld24 instruction), and are callable with the bl instruction.
Medium model objects may live anywhere in the 32-bit address space (the compiler will generate seth/add3 instructions to load their addresses), and are callable with the bl instruction.
Large model objects may live anywhere in the 32-bit address space (the compiler will generate seth/add3 instructions to load their addresses), and may not be reachable with the bl instruction (the compiler will generate the much slower seth/add3/jl instruction sequence).
On IA-64, use this attribute to set the addressability of an object. At present, the only supported identifier for model-name is small, indicating addressability via “small” (22-bit) addresses (so that their addresses can be loaded with the addl instruction). Caveat: such addressing is by definition not position independent and hence this attribute must not be used for objects defined by shared libraries.
naked
Use this attribute on the ARM, AVR, C4x and IP2K ports to indicate that the specified function does not need prologue/epilogue sequences generated by the compiler. It is up to the programmer to provide these sequences.
near
On 68HC11 and 68HC12 the near attribute causes the compiler to use the normal calling convention based on jsr and rts. This attribute can be used to cancel the effect of the -mlong-calls option.
no_instrument_function
If -finstrument-functions is given, profiling function calls will be generated at entry and exit of most user-compiled functions. Functions with this attribute will not be so instrumented.
noinline
This function attribute prevents a function from being considered for inlining.
nonnull (arg-index, ...)
The nonnull attribute specifies that some function parameters should be non-null pointers. For instance, the declaration:
extern void *
my_memcpy (void *dest, const void *src, size_t len)
__attribute__((nonnull (1, 2)));
causes the compiler to check that, in calls to my_memcpy, arguments dest and src are non-null. If the compiler determines that a null pointer is passed in an argument slot marked as non-null, and the -Wnonnull option is enabled, a warning is issued. The compiler may also choose to make optimizations based on the knowledge that certain function arguments will not be null.
If no argument index list is given to the nonnull attribute, all pointer arguments are marked as non-null. To illustrate, the following declaration is equivalent to the previous example:
extern void *
my_memcpy (void *dest, const void *src, size_t len)
__attribute__((nonnull));
noreturn
A few standard library functions, such as abort and exit, cannot return. GCC knows this automatically. Some programs define their own functions that never return. You can declare them noreturn to tell the compiler this fact. For example,
void fatal () __attribute__ ((noreturn));
void
fatal (/* ... */)
{
/* ... */ /* Print error message. */ /* ... */
exit (1);
}
The noreturn keyword tells the compiler to assume that fatal cannot return. It can then optimize without regard to what would happen if fatal ever did return. This makes slightly better code. More importantly, it helps avoid spurious warnings of uninitialized variables.
The noreturn keyword does not affect the exceptional path when that applies: a noreturn-marked function may still return to the caller by throwing an exception or calling longjmp.
Do not assume that registers saved by the calling function are restored before calling the noreturn function.
It does not make sense for a noreturn function to have a return type other than void.
The attribute noreturn is not implemented in GCC versions earlier than 2.5. An alternative way to declare that a function does not return, which works in the current version and in some older versions, is as follows:
typedef void voidfn ();
volatile voidfn fatal;
This approach does not work in GNU C++.
nothrow
The nothrow attribute is used to inform the compiler that a function cannot throw an exception. For example, most functions in the standard C library can be guaranteed not to throw an exception with the notable exceptions of qsort and bsearch that take function pointer arguments. The nothrow attribute is not implemented in GCC versions earlier than 3.3.
pure
Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute pure. For example,
int square (int) __attribute__ ((pure));
says that the hypothetical function square is safe to call fewer times than the program says.
Some of common examples of pure functions are strlen or memcmp. Interesting non-pure functions are functions with infinite loops or those depending on volatile memory or other system resource, that may change between two consecutive calls (such as feof in a multithreading environment).
The attribute pure is not implemented in GCC versions earlier than 2.96.
regparm (number)
On the Intel 386, the regparm attribute causes the compiler to pass up to number integer arguments in registers EAX, EDX, and ECX instead of on the stack. Functions that take a variable number of arguments will continue to be passed all of their arguments on the stack.
Beware that on some ELF systems this attribute is unsuitable for global functions in shared libraries with lazy binding (which is the default). Lazy binding will send the first call via resolving code in the loader, which might assume EAX, EDX and ECX can be clobbered, as per the standard calling conventions. Solaris 8 is affected by this. GNU systems with GLIBC 2.1 or higher, and FreeBSD, are believed to be safe since the loaders there save all registers. (Lazy binding can be disabled with the linker or the loader if desired, to avoid the problem.)
saveall
Use this attribute on the H8/300, H8/300H, and H8S to indicate that all registers except the stack pointer should be saved in the prologue regardless of whether they are used or not.
section ("section-name")
Normally, the compiler places the code it generates in the text section. Sometimes, however, you need additional sections, or you need certain particular functions to appear in special sections. The section attribute specifies that a function lives in a particular section. For example, the declaration:
extern void foobar (void) __attribute__ ((section ("bar")));
puts the function foobar in the bar section.
Some file formats do not support arbitrary sections so the section attribute is not available on all platforms. If you need to map the entire contents of a module to a particular section, consider using the facilities of the linker instead.
sentinel
This function attribute ensures that a parameter in a function call is an explicit NULL. The attribute is only valid on variadic functions. By default, the sentinel is located at position zero, the last parameter of the function call. If an optional integer position argument P is supplied to the attribute, the sentinel must be located at position P counting backwards from the end of the argument list.
__attribute__ ((sentinel))
is equivalent to
__attribute__ ((sentinel(0)))
The attribute is automatically set with a position of 0 for the built-in functions execl and execlp. The built-in function execle has the attribute set with a position of 1.
A valid NULL in this context is defined as zero with any pointer type. If your system defines the NULL macro with an integer type then you need to add an explicit cast. GCC replaces stddef.h with a copy that redefines NULL appropriately.
The warnings for missing or incorrect sentinels are enabled with -Wformat.
short_call
See long_call/short_call.
shortcall
See longcall/shortcall.
signal
Use this attribute on the AVR to indicate that the specified function is a signal handler. The compiler will generate function entry and exit sequences suitable for use in a signal handler when this attribute is present. Interrupts will be disabled inside the function.
sp_switch
Use this attribute on the SH to indicate an interrupt_handler function should switch to an alternate stack. It expects a string argument that names a global variable holding the address of the alternate stack.
void *alt_stack;
void f () __attribute__ ((interrupt_handler,
sp_switch ("alt_stack")));
stdcall
On the Intel 386, the stdcall attribute causes the compiler to assume that the called function will pop off the stack space used to pass arguments, unless it takes a variable number of arguments.
tiny_data
Use this attribute on the H8/300H and H8S to indicate that the specified variable should be placed into the tiny data section. The compiler will generate more efficient code for loads and stores on data in the tiny data section. Note the tiny data area is limited to slightly under 32kbytes of data.
trap_exit
Use this attribute on the SH for an interrupt_handler to return using trapa instead of rte. This attribute expects an integer argument specifying the trap number to be used.
unused
This attribute, attached to a function, means that the function is meant to be possibly unused. GCC will not produce a warning for this function.
used
This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly.
visibility ("visibility_type")
The visibility attribute on ELF targets causes the declaration to be emitted with default, hidden, protected or internal visibility.
void __attribute__ ((visibility ("protected")))
f () { /* Do something. */; }
int i __attribute__ ((visibility ("hidden")));
See the ELF gABI for complete details, but the short story is:
default
Default visibility is the normal case for ELF. This value is available for the visibility attribute to override other options that may change the assumed visibility of symbols.
hidden
Hidden visibility indicates that the symbol will not be placed into the dynamic symbol table, so no other module (executable or shared library) can reference it directly.
internal
Internal visibility is like hidden visibility, but with additional processor specific semantics. Unless otherwise specified by the psABI, GCC defines internal visibility to mean that the function is never called from another module. Note that hidden symbols, while they cannot be referenced directly by other modules, can be referenced indirectly via function pointers. By indicating that a symbol cannot be called from outside the module, GCC may for instance omit the load of a PIC register since it is known that the calling function loaded the correct value.
protected
Protected visibility indicates that the symbol will be placed in the dynamic symbol table, but that references within the defining module will bind to the local symbol. That is, the symbol cannot be overridden by another module.
Not all ELF targets support this attribute.
warn_unused_result
The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug, such as realloc.
int fn () __attribute__ ((warn_unused_result));
int foo ()
{
if (fn () < 0) return -1;
fn ();
return 0;
}
results in warning on line 5.
weak
The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions which can be overridden in user code, though it can also be used with non-function declarations. Weak symbols are supported for ELF targets, and also for a.out targets when using the GNU assembler and linker.
You can specify multiple attributes in a declaration by separating them by commas within the double parentheses or by immediately following an attribute declaration with another attribute declaration.
Some people object to the __attribute__ feature, suggesting that ISO C's #pragma should be used instead. At the time __attribute__ was designed, there were two reasons for not doing this.
1. It is impossible to generate #pragma commands from a macro.
2. There is no telling what the same #pragma might mean in another compiler.
These two reasons applied to almost any application that might have been proposed for #pragma. It was basically a mistake to use #pragma for anything.
The ISO C99 standard includes _Pragma, which now allows pragmas to be generated from macros. In addition, a #pragma GCC namespace is now in use for GCC-specific pragmas. However, it has been found convenient to use __attribute__ to achieve a natural attachment of attributes to their corresponding declarations, whereas #pragma GCC is of use for constructs that do not naturally form part of the grammar. See Miscellaneous Preprocessing Directives.
http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html
放到這裡只是讓自己便於查閱!無其它意途。
In GNU C, you declare certain things about functions called in your program which help the compiler optimize function calls and check your code more carefully.
The keyword __attribute__ allows you to specify special attributes when making a declaration. This keyword is followed by an attribute specification inside double parentheses. The following attributes are currently defined for functions on all targets: noreturn, noinline, always_inline, pure, const, nothrow, sentinel, format, format_arg, no_instrument_function, section, constructor, destructor, used, unused, deprecated, weak, malloc, alias, warn_unused_result and nonnull. Several other attributes are defined for functions on particular target systems. Other attributes, including section are supported for variables declarations (see Variable Attributes) and for types (see Type Attributes).
You may also specify attributes with `__' preceding and following each keyword. This allows you to use them in header files without being concerned about a possible macro of the same name. For example, you may use __noreturn__ instead of noreturn.
See Attribute Syntax, for details of the exact syntax for using attributes.
alias ("target")
The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified. For instance,
void __f () { /* Do something. */; }
void f () __attribute__ ((weak, alias ("__f")));
declares `f' to be a weak alias for `__f'. In C++, the mangled name for the target must be used. It is an error if `__f' is not defined in the same translation unit.
Not all target machines support this attribute.
always_inline
Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level was specified.
cdecl
On the Intel 386, the cdecl attribute causes the compiler to assume that the calling function will pop off the stack space used to pass arguments. This is useful to override the effects of the -mrtd switch.
const
Many functions do not examine any values except their arguments, and have no effects except the return value. Basically this is just slightly more strict class than the pure attribute below, since function is not allowed to read global memory.
Note that a function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It does not make sense for a const function to return void.
The attribute const is not implemented in GCC versions earlier than 2.5. An alternative way to declare that a function has no side effects, which works in the current version and in some older versions, is as follows:
typedef int intfn ();
extern const intfn square;
This approach does not work in GNU C++ from 2.6.0 on, since the language specifies that the `const' must be attached to the return value.
constructor
destructor
The constructor attribute causes the function to be called automatically before execution enters main (). Similarly, the destructor attribute causes the function to be called automatically after main () has completed or exit () has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program.
These attributes are not currently implemented for Objective-C.
deprecated
The deprecated attribute results in a warning if the function is used anywhere in the source file. This is useful when identifying functions that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated function, to enable users to easily find further information about why the function is deprecated, or what they should do instead. Note that the warnings only occurs for uses:
int old_fn () __attribute__ ((deprecated));
int old_fn ();
int (*fn_ptr)() = old_fn;
results in a warning on line 3 but not line 2.
The deprecated attribute can also be used for variables and types (see Variable Attributes, see Type Attributes.)
dllexport
On Microsoft Windows targets and Symbian OS targets the dllexport attribute causes the compiler to provide a global pointer to a pointer in a DLL, so that it can be referenced with the dllimport attribute. On Microsoft Windows targets, the pointer name is formed by combining _imp__ and the function or variable name.
You can use __declspec(dllexport) as a synonym for __attribute__ ((dllexport)) for compatibility with other compilers.
On systems that support the visibility attribute, this attribute also implies “default” visibility, unless a visibility attribute is explicitly specified. You should avoid the use of dllexport with “hidden” or “internal” visibility; in the future GCC may issue an error for those cases.
Currently, the dllexport attribute is ignored for inlined functions, unless the -fkeep-inline-functions flag has been used. The attribute is also ignored for undefined symbols.
When applied to C++ classes, the attribute marks defined non-inlined member functions and static data members as exports. Static consts initialized in-class are not marked unless they are also defined out-of-class.
For Microsoft Windows targets there are alternative methods for including the symbol in the DLL's export table such as using a .def file with an EXPORTS section or, with GNU ld, using the --export-all linker flag.
dllimport
On Microsoft Windows and Symbian OS targets, the dllimport attribute causes the compiler to reference a function or variable via a global pointer to a pointer that is set up by the DLL exporting the symbol. The attribute implies extern storage. On Microsoft Windows targets, the pointer name is formed by combining _imp__ and the function or variable name.
You can use __declspec(dllimport) as a synonym for __attribute__ ((dllimport)) for compatibility with other compilers.
Currently, the attribute is ignored for inlined functions. If the attribute is applied to a symbol definition, an error is reported. If a symbol previously declared dllimport is later defined, the attribute is ignored in subsequent references, and a warning is emitted. The attribute is also overridden by a subsequent declaration as dllexport.
When applied to C++ classes, the attribute marks non-inlined member functions and static data members as imports. However, the attribute is ignored for virtual methods to allow creation of vtables using thunks.
On the SH Symbian OS target the dllimport attribute also has another affect—it can cause the vtable and run-time type information for a class to be exported. This happens when the class has a dllimport'ed constructor or a non-inline, non-pure virtual function and, for either of those two conditions, the class also has a inline constructor or destructor and has a key function that is defined in the current translation unit.
For Microsoft Windows based targets the use of the dllimport attribute on functions is not necessary, but provides a small performance benefit by eliminating a thunk in the DLL. The use of the dllimport attribute on imported variables was required on older versions of the GNU linker, but can now be avoided by passing the --enable-auto-import switch to the GNU linker. As with functions, using the attribute for a variable eliminates a thunk in the DLL.
One drawback to using this attribute is that a pointer to a function or variable marked as dllimport cannot be used as a constant address. On Microsoft Windows targets, the attribute can be disabled for functions by setting the -mnop-fun-dllimport flag.
eightbit_data
Use this attribute on the H8/300, H8/300H, and H8S to indicate that the specified variable should be placed into the eight bit data section. The compiler will generate more efficient code for certain operations on data in the eight bit data area. Note the eight bit data area is limited to 256 bytes of data.
You must use GAS and GLD from GNU binutils version 2.7 or later for this attribute to work correctly.
far
On 68HC11 and 68HC12 the far attribute causes the compiler to use a calling convention that takes care of switching memory banks when entering and leaving a function. This calling convention is also the default when using the -mlong-calls option.
On 68HC12 the compiler will use the call and rtc instructions to call and return from a function.
On 68HC11 the compiler will generate a sequence of instructions to invoke a board-specific routine to switch the memory bank and call the real function. The board-specific routine simulates a call. At the end of a function, it will jump to a board-specific routine instead of using rts. The board-specific return routine simulates the rtc.
fastcall
On the Intel 386, the fastcall attribute causes the compiler to pass the first two arguments in the registers ECX and EDX. Subsequent arguments are passed on the stack. The called function will pop the arguments off the stack. If the number of arguments is variable all arguments are pushed on the stack.
format (archetype, string-index, first-to-check)
The format attribute specifies that a function takes printf, scanf, strftime or strfmon style arguments which should be type-checked against a format string. For example, the declaration:
extern int
my_printf (void *my_object, const char *my_format, ...)
__attribute__ ((format (printf, 2, 3)));
causes the compiler to check the arguments in calls to my_printf for consistency with the printf style format string argument my_format.
The parameter archetype determines how the format string is interpreted, and should be printf, scanf, strftime or strfmon. (You can also use __printf__, __scanf__, __strftime__ or __strfmon__.) The parameter string-index specifies which argument is the format string argument (starting from 1), while first-to-check is the number of the first argument to check against the format string. For functions where the arguments are not available to be checked (such as vprintf), specify the third parameter as zero. In this case the compiler only checks the format string for consistency. For strftime formats, the third parameter is required to be zero. Since non-static C++ methods have an implicit this argument, the arguments of such methods should be counted from two, not one, when giving values for string-index and first-to-check.
In the example above, the format string (my_format) is the second argument of the function my_print, and the arguments to check start with the third argument, so the correct parameters for the format attribute are 2 and 3.
The format attribute allows you to identify your own functions which take format strings as arguments, so that GCC can check the calls to these functions for errors. The compiler always (unless -ffreestanding or -fno-builtin is used) checks formats for the standard library functions printf, fprintf, sprintf, scanf, fscanf, sscanf, strftime, vprintf, vfprintf and vsprintf whenever such warnings are requested (using -Wformat), so there is no need to modify the header file stdio.h. In C99 mode, the functions snprintf, vsnprintf, vscanf, vfscanf and vsscanf are also checked. Except in strictly conforming C standard modes, the X/Open function strfmon is also checked as are printf_unlocked and fprintf_unlocked. See Options Controlling C Dialect.
The target may provide additional types of format checks. See Format Checks Specific to Particular Target Machines.
format_arg (string-index)
The format_arg attribute specifies that a function takes a format string for a printf, scanf, strftime or strfmon style function and modifies it (for example, to translate it into another language), so the result can be passed to a printf, scanf, strftime or strfmon style function (with the remaining arguments to the format function the same as they would have been for the unmodified string). For example, the declaration:
extern char *
my_dgettext (char *my_domain, const char *my_format)
__attribute__ ((format_arg (2)));
causes the compiler to check the arguments in calls to a printf, scanf, strftime or strfmon type function, whose format string argument is a call to the my_dgettext function, for consistency with the format string argument my_format. If the format_arg attribute had not been specified, all the compiler could tell in such calls to format functions would be that the format string argument is not constant; this would generate a warning when -Wformat-nonliteral is used, but the calls could not be checked without the attribute.
The parameter string-index specifies which argument is the format string argument (starting from one). Since non-static C++ methods have an implicit this argument, the arguments of such methods should be counted from two.
The format-arg attribute allows you to identify your own functions which modify format strings, so that GCC can check the calls to printf, scanf, strftime or strfmon type function whose operands are a call to one of your own function. The compiler always treats gettext, dgettext, and dcgettext in this manner except when strict ISO C support is requested by -ansi or an appropriate -std option, or -ffreestanding or -fno-builtin is used. See Options Controlling C Dialect.
function_vector
Use this attribute on the H8/300, H8/300H, and H8S to indicate that the specified function should be called through the function vector. Calling a function through the function vector will reduce code size, however; the function vector has a limited size (maximum 128 entries on the H8/300 and 64 entries on the H8/300H and H8S) and shares space with the interrupt vector.
You must use GAS and GLD from GNU binutils version 2.7 or later for this attribute to work correctly.
interrupt
Use this attribute on the ARM, AVR, C4x, M32R/D and Xstormy16 ports to indicate that the specified function is an interrupt handler. The compiler will generate function entry and exit sequences suitable for use in an interrupt handler when this attribute is present.
Note, interrupt handlers for the m68k, H8/300, H8/300H, H8S, and SH processors can be specified via the interrupt_handler attribute.
Note, on the AVR, interrupts will be enabled inside the function.
Note, for the ARM, you can specify the kind of interrupt to be handled by adding an optional parameter to the interrupt attribute like this:
void f () __attribute__ ((interrupt ("IRQ")));
Permissible values for this parameter are: IRQ, FIQ, SWI, ABORT and UNDEF.
interrupt_handler
Use this attribute on the m68k, H8/300, H8/300H, H8S, and SH to indicate that the specified function is an interrupt handler. The compiler will generate function entry and exit sequences suitable for use in an interrupt handler when this attribute is present.
long_call/short_call
This attribute specifies how a particular function is called on ARM. Both attributes override the -mlong-calls (see ARM Options) command line switch and #pragma long_calls settings. The long_call attribute causes the compiler to always call the function by first loading its address into a register and then using the contents of that register. The short_call attribute always places the offset to the function from the call site into the `BL' instruction directly.
longcall/shortcall
On the RS/6000 and PowerPC, the longcall attribute causes the compiler to always call this function via a pointer, just as it would if the -mlongcall option had been specified. The shortcall attribute causes the compiler not to do this. These attributes override both the -mlongcall switch and the #pragma longcall setting.
See RS/6000 and PowerPC Options, for more information on whether long calls are necessary.
malloc
The malloc attribute is used to tell the compiler that a function may be treated as if any non-NULL pointer it returns cannot alias any other pointer valid when the function returns. This will often improve optimization. Standard functions with this property include malloc and calloc. realloc-like functions have this property as long as the old pointer is never referred to (including comparing it to the new pointer) after the function returns a non-NULL value.
model (model-name)
On the M32R/D, use this attribute to set the addressability of an object, and of the code generated for a function. The identifier model-name is one of small, medium, or large, representing each of the code models.
Small model objects live in the lower 16MB of memory (so that their addresses can be loaded with the ld24 instruction), and are callable with the bl instruction.
Medium model objects may live anywhere in the 32-bit address space (the compiler will generate seth/add3 instructions to load their addresses), and are callable with the bl instruction.
Large model objects may live anywhere in the 32-bit address space (the compiler will generate seth/add3 instructions to load their addresses), and may not be reachable with the bl instruction (the compiler will generate the much slower seth/add3/jl instruction sequence).
On IA-64, use this attribute to set the addressability of an object. At present, the only supported identifier for model-name is small, indicating addressability via “small” (22-bit) addresses (so that their addresses can be loaded with the addl instruction). Caveat: such addressing is by definition not position independent and hence this attribute must not be used for objects defined by shared libraries.
naked
Use this attribute on the ARM, AVR, C4x and IP2K ports to indicate that the specified function does not need prologue/epilogue sequences generated by the compiler. It is up to the programmer to provide these sequences.
near
On 68HC11 and 68HC12 the near attribute causes the compiler to use the normal calling convention based on jsr and rts. This attribute can be used to cancel the effect of the -mlong-calls option.
no_instrument_function
If -finstrument-functions is given, profiling function calls will be generated at entry and exit of most user-compiled functions. Functions with this attribute will not be so instrumented.
noinline
This function attribute prevents a function from being considered for inlining.
nonnull (arg-index, ...)
The nonnull attribute specifies that some function parameters should be non-null pointers. For instance, the declaration:
extern void *
my_memcpy (void *dest, const void *src, size_t len)
__attribute__((nonnull (1, 2)));
causes the compiler to check that, in calls to my_memcpy, arguments dest and src are non-null. If the compiler determines that a null pointer is passed in an argument slot marked as non-null, and the -Wnonnull option is enabled, a warning is issued. The compiler may also choose to make optimizations based on the knowledge that certain function arguments will not be null.
If no argument index list is given to the nonnull attribute, all pointer arguments are marked as non-null. To illustrate, the following declaration is equivalent to the previous example:
extern void *
my_memcpy (void *dest, const void *src, size_t len)
__attribute__((nonnull));
noreturn
A few standard library functions, such as abort and exit, cannot return. GCC knows this automatically. Some programs define their own functions that never return. You can declare them noreturn to tell the compiler this fact. For example,
void fatal () __attribute__ ((noreturn));
void
fatal (/* ... */)
{
/* ... */ /* Print error message. */ /* ... */
exit (1);
}
The noreturn keyword tells the compiler to assume that fatal cannot return. It can then optimize without regard to what would happen if fatal ever did return. This makes slightly better code. More importantly, it helps avoid spurious warnings of uninitialized variables.
The noreturn keyword does not affect the exceptional path when that applies: a noreturn-marked function may still return to the caller by throwing an exception or calling longjmp.
Do not assume that registers saved by the calling function are restored before calling the noreturn function.
It does not make sense for a noreturn function to have a return type other than void.
The attribute noreturn is not implemented in GCC versions earlier than 2.5. An alternative way to declare that a function does not return, which works in the current version and in some older versions, is as follows:
typedef void voidfn ();
volatile voidfn fatal;
This approach does not work in GNU C++.
nothrow
The nothrow attribute is used to inform the compiler that a function cannot throw an exception. For example, most functions in the standard C library can be guaranteed not to throw an exception with the notable exceptions of qsort and bsearch that take function pointer arguments. The nothrow attribute is not implemented in GCC versions earlier than 3.3.
pure
Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute pure. For example,
int square (int) __attribute__ ((pure));
says that the hypothetical function square is safe to call fewer times than the program says.
Some of common examples of pure functions are strlen or memcmp. Interesting non-pure functions are functions with infinite loops or those depending on volatile memory or other system resource, that may change between two consecutive calls (such as feof in a multithreading environment).
The attribute pure is not implemented in GCC versions earlier than 2.96.
regparm (number)
On the Intel 386, the regparm attribute causes the compiler to pass up to number integer arguments in registers EAX, EDX, and ECX instead of on the stack. Functions that take a variable number of arguments will continue to be passed all of their arguments on the stack.
Beware that on some ELF systems this attribute is unsuitable for global functions in shared libraries with lazy binding (which is the default). Lazy binding will send the first call via resolving code in the loader, which might assume EAX, EDX and ECX can be clobbered, as per the standard calling conventions. Solaris 8 is affected by this. GNU systems with GLIBC 2.1 or higher, and FreeBSD, are believed to be safe since the loaders there save all registers. (Lazy binding can be disabled with the linker or the loader if desired, to avoid the problem.)
saveall
Use this attribute on the H8/300, H8/300H, and H8S to indicate that all registers except the stack pointer should be saved in the prologue regardless of whether they are used or not.
section ("section-name")
Normally, the compiler places the code it generates in the text section. Sometimes, however, you need additional sections, or you need certain particular functions to appear in special sections. The section attribute specifies that a function lives in a particular section. For example, the declaration:
extern void foobar (void) __attribute__ ((section ("bar")));
puts the function foobar in the bar section.
Some file formats do not support arbitrary sections so the section attribute is not available on all platforms. If you need to map the entire contents of a module to a particular section, consider using the facilities of the linker instead.
sentinel
This function attribute ensures that a parameter in a function call is an explicit NULL. The attribute is only valid on variadic functions. By default, the sentinel is located at position zero, the last parameter of the function call. If an optional integer position argument P is supplied to the attribute, the sentinel must be located at position P counting backwards from the end of the argument list.
__attribute__ ((sentinel))
is equivalent to
__attribute__ ((sentinel(0)))
The attribute is automatically set with a position of 0 for the built-in functions execl and execlp. The built-in function execle has the attribute set with a position of 1.
A valid NULL in this context is defined as zero with any pointer type. If your system defines the NULL macro with an integer type then you need to add an explicit cast. GCC replaces stddef.h with a copy that redefines NULL appropriately.
The warnings for missing or incorrect sentinels are enabled with -Wformat.
short_call
See long_call/short_call.
shortcall
See longcall/shortcall.
signal
Use this attribute on the AVR to indicate that the specified function is a signal handler. The compiler will generate function entry and exit sequences suitable for use in a signal handler when this attribute is present. Interrupts will be disabled inside the function.
sp_switch
Use this attribute on the SH to indicate an interrupt_handler function should switch to an alternate stack. It expects a string argument that names a global variable holding the address of the alternate stack.
void *alt_stack;
void f () __attribute__ ((interrupt_handler,
sp_switch ("alt_stack")));
stdcall
On the Intel 386, the stdcall attribute causes the compiler to assume that the called function will pop off the stack space used to pass arguments, unless it takes a variable number of arguments.
tiny_data
Use this attribute on the H8/300H and H8S to indicate that the specified variable should be placed into the tiny data section. The compiler will generate more efficient code for loads and stores on data in the tiny data section. Note the tiny data area is limited to slightly under 32kbytes of data.
trap_exit
Use this attribute on the SH for an interrupt_handler to return using trapa instead of rte. This attribute expects an integer argument specifying the trap number to be used.
unused
This attribute, attached to a function, means that the function is meant to be possibly unused. GCC will not produce a warning for this function.
used
This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly.
visibility ("visibility_type")
The visibility attribute on ELF targets causes the declaration to be emitted with default, hidden, protected or internal visibility.
void __attribute__ ((visibility ("protected")))
f () { /* Do something. */; }
int i __attribute__ ((visibility ("hidden")));
See the ELF gABI for complete details, but the short story is:
default
Default visibility is the normal case for ELF. This value is available for the visibility attribute to override other options that may change the assumed visibility of symbols.
hidden
Hidden visibility indicates that the symbol will not be placed into the dynamic symbol table, so no other module (executable or shared library) can reference it directly.
internal
Internal visibility is like hidden visibility, but with additional processor specific semantics. Unless otherwise specified by the psABI, GCC defines internal visibility to mean that the function is never called from another module. Note that hidden symbols, while they cannot be referenced directly by other modules, can be referenced indirectly via function pointers. By indicating that a symbol cannot be called from outside the module, GCC may for instance omit the load of a PIC register since it is known that the calling function loaded the correct value.
protected
Protected visibility indicates that the symbol will be placed in the dynamic symbol table, but that references within the defining module will bind to the local symbol. That is, the symbol cannot be overridden by another module.
Not all ELF targets support this attribute.
warn_unused_result
The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug, such as realloc.
int fn () __attribute__ ((warn_unused_result));
int foo ()
{
if (fn () < 0) return -1;
fn ();
return 0;
}
results in warning on line 5.
weak
The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions which can be overridden in user code, though it can also be used with non-function declarations. Weak symbols are supported for ELF targets, and also for a.out targets when using the GNU assembler and linker.
You can specify multiple attributes in a declaration by separating them by commas within the double parentheses or by immediately following an attribute declaration with another attribute declaration.
Some people object to the __attribute__ feature, suggesting that ISO C's #pragma should be used instead. At the time __attribute__ was designed, there were two reasons for not doing this.
1. It is impossible to generate #pragma commands from a macro.
2. There is no telling what the same #pragma might mean in another compiler.
These two reasons applied to almost any application that might have been proposed for #pragma. It was basically a mistake to use #pragma for anything.
The ISO C99 standard includes _Pragma, which now allows pragmas to be generated from macros. In addition, a #pragma GCC namespace is now in use for GCC-specific pragmas. However, it has been found convenient to use __attribute__ to achieve a natural attachment of attributes to their corresponding declarations, whereas #pragma GCC is of use for constructs that do not naturally form part of the grammar. See Miscellaneous Preprocessing Directives.
2010年5月10日 星期一
Gcc中的__attribute__關鍵字
感謝Zuse的說明,以下記錄詢問後的心得,Gcc提供一種指定函式或變數屬性的方法__attribute__,使用者可以籍由它來告訴Gcc,被宣告的函式或變數的屬性及行為;當一個資料結構被以__attribute__(packed)指定屬性,當資料結構中的成員沒有Alignment 時,Gcc將不會主動對其進行Padding處理!這個動作常用於通訊方面的傳輸,因為通訊傳輸上的資料格式必須固定一致,使用 __attribute__(packed)可避免Gcc在Compile Time時,誤將其進行Padding的處理!
PS. Padding就是當資料結構在宣告時,若沒有注意到成員變數的型態是否有Alignment,Gcc會主動將其進行Alignment的動作,以提昇存取效率!
PS. Padding就是當資料結構在宣告時,若沒有注意到成員變數的型態是否有Alignment,Gcc會主動將其進行Alignment的動作,以提昇存取效率!
訂閱:
文章 (Atom)