C language usage __attribute__

http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html

http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Variable-Attributes.html#Variable-Attributes

 

A major feature of GNU C (not known to be a beginner) is __attribute__ mechanism. __attribute__ function attribute may be provided (Function Attribute), variable attributes (Variable Attribute) and type attributes (Type Attribute).
Writing __attribute__ wherein: __ attribute__ two underscores before and after, and cut immediately followed by a pair of original brackets, which brackets are the corresponding parameters __attribute__.
__attribute__ syntax is:
__attribute__ ((attribute-List))
its position constraint is:
put the tail declaration ";" before.
Function Properties (Function Attribute)
function attributes can help developers to add features to the function declaration so that the compiler can function in terms of a more powerful error checking. __attribute__ mechanism is also very easy to do with the effect of non-compliant GNU applications.
GNU CC need to use -Wall compiler to strike deserve function, which is a good way to control warning messages. Here are a few common attribute parameter.
__attribute__ the format
of the attribute can be added __attribute__ scanf or similar features to printf function is declared, it allows the compiler to check the function declaration and actually invoked if the format string matching between the parameters. This is useful, especially to deal with some bug difficult to find.
syntax format is:
format (archetype, String-index, First-to-the Check)
The format attribute tells the compiler to check the function of the parameters in accordance with printf, scanf, strftime or parameter table formatting rules strfmon of. "Archetype" specifies what kind of style; on several parameters "string-index" is passed to the function specified format string; "first-to-check" to specify the start of the check function of several parameters according to the above rules .
Specific use the following format:
__attribute __ ((the format (the printf, m, n)))
__attribute __ ((the format (Scanf, m, n)))
where the parameter m and the meaning of n are:
m: the first of several parameters for the format string string (String format);
the n-: the first set of parameters, namely the parameter "..." in the first argument in the total number of function parameters in the first few rows, note that sometimes the function parameters as well as "stealth" in it, It will be mentioned later;
in use, __ attribute __ ((format ( printf, m, n))) is commonly used, and the other rarely seen. Illustrated below, where myprint with a variable parameter as a function of their definition, its function is similar to the printf:
// m =. 1; 2 = n-
extern void myprint (the format const char *, ...) __attribute __ (( the format (the printf, 1,2)));
// m = 2; =. 3 n-
extern void myPrint (int L, the format const char *, ...) __attribute __ ((the format (the printf, 2,3)));
[NextPage]
Should be particularly noted that, if a member function myprint function, then the values of m and n may be a bit "Xuanhu" of, for example:
// m =. 3; = n. 4
extern void myprint (L int, char const * the format , ...) __attribute __ ((format (printf, 3,4)));
the reason is that the first parameter is actually a class member function "invisible" to "this" pointer. (C a little basic know this pointer points, do not know you're here know it?)
Here are the test case: attribute.c, code is as follows:
1:
2: extern void the myPrint () (const char * format, ... ) __attribute __ ((the format (the printf, 1,2)));
. 3:
. 4: void Test ()
. 5: {
. 6: myPrint ( "I D =% \ n-",. 6);
. 7: myPrint ( "% I = S \ n-",. 6);
. 8: myPrint ("% S I = \ n-"," ABC ");
. 9: myPrint ("% S,% D, D% \ n-", 1,2);
10: }

run $ gcc -Wall -c attribute.c attribute, the result is output:
attribute.c: Test the In function ` ':
attribute.c:. 7: warning:
attribute.c:. 9: warning: Not the format IS A pointer argument (Arg 2)
attribute.c:. 9: warning: TOO FEW arguments for the format

if the function declaration attribute.c removed in __attribute __ ((format (printf, 1 , 2))), and then recompile, after both run $ gcc -Wall -c attribute.c attribute, it does not output any warning messages.
Note that, by default, the compiler is able to identify similar printf "standard" library functions.
__attribute__ noreturn
This attribute tells the compiler to never return value of the function, when faced with a similar function needs to return value but they can not run to the return value of the case had to withdraw, and the property can avoid the error message. C library functions abort () and exit () statement format on the use of this format, as follows:

extern void Exit (int) __attribute __ ((the noreturn));
extern void ABORT (void) __attribute __ ((the noreturn) );

for ease of understanding, we can refer to the following example:
// name: noreturn.c; __ test __attribute ((the noreturn))
extern void myExit ();

int test (n-int)
{
IF (n-> 0)
{
myExit ();
}
the else
return 0;
}

an output compiled information displayed is:
$ GCC -Wall -C noreturn.c
noreturn.c: Test the In function ` ':
noreturn.c: 12 is: warning: Reaches End Control of non-void function

and the warnings well understood, because you define a function test return value there may be no return value, the program certainly do not know how to do!
Plus __attribute __ ((noreturn)) can be a good deal with issues such as this. The
extern void myexit ();
revised as:
extern void myExit () __attribute __ ((noreturn));
later, the compiler will not warning message appears.
__attribute__ const
This property can only be used with the function of the parameter value type. When the function is called repeatedly with a parameter value, since the return value is the same, so in this case the compiler may be optimized, in addition to the first required operation, the other first return only results can, in turn, may Improve efficiency. This property is mainly applied to a number of functions (static state) and a static state without side effects, and the return value depends only on the input parameters.
To illustrate the problem, the following give a very "bad" example that a function call will be repeated with the same parameter values, as follows:

extern int Square (n-int) __attribute __ ((const));
...
for (i = 0; i < 100; i )
{
total = square(5) i;

}

By adding __attribute __ ((const)) statement, the compiler calls a function only once, but later got the same direct a return value.
Indeed, const parameter can not be used with the function pointer type parameter, since this property affects not only the function parameters, also affecting the data parameter points, it may have serious or even code itself is unrecoverable severe as a result of.
Further, the attribute can not function with any side effects or static state, similar getchar () or time () function is not appropriate to use the property.
-finstrument-functions
This parameter allows the program at compile time, generating instrumentation calls the inlet and outlet functions. Just and just before function exit, the following profiling to call a function call using the address and the address of the current function after function entry. (On some platforms, __ builtin_return_address can not work more than the current function outside the range of normal, so the call address information may be on the profiling function is invalid.)

Void __cyg_profile_func_enter (void * this_fn, void * call_site);
void __cyg_profile_func_exit (void * this_fn, void * call_site);

wherein the first parameter is the current starting address this_fn function can be found in the symbol table; call_site the second parameter refers to the call of the address.
This instrumentation is also used for other functions in the expanded inline. Conceptually, profiling calls will indicate where to enter and exit inline functions. This means that this function must have an addressable form. If the function contains inline, and all use to the function of the program have to put inline expansion, which will additionally increase code size. If you use extern inline declarations in C code, which must be provided in the form of addressable function.
No_instrument_function function attributes can be specified, operated instrumentation is not done in this case. For example, you can use no_instrument_function property under the following conditions: profiling functions listed above, high priority interrupt routines can not guarantee profiling as well as any normal function call.
no_instrument_function
If the -finstrument-functions, will call the profiling function entry and exit points in the vast majority of users compiled functions. Using this property, instrument will not operate.
constructor / destructor
if the constructor function is set to the attribute, the function in the main () function is automatically performed before execution. Similarly, if the destructor function is set to the attribute, the function in the main () function is executed or after the exit () is invoked automatically after execution. Such function has a property often implicit in the initialization data with aspects of the program.
These two properties not realized in object-oriented C.
[NextPage]
simultaneous use of multiple attributes
can use multiple __attribute__ in the same statement in a function, and the practical application of this situation is very common. On use, you can choose the __attribute__ two separate, or write them together, can refer to the following example:

Die void extern (the format const char *, ...)
__attribute __ ((the noreturn))
__attribute __ ((the format (the printf,. 1, 2)));
or written
extern void Die (the format const char *, ...)
__attribute __ ( (noreturn, format (printf, 1 , 2)));

if the custom function with the attributes added to the library's header file, then the caller of the function so have to do the appropriate checks.

And non-GNU compiler compatibility
Fortunately, __ attribute__ very clever design, it is easy to be done to maintain compatibility with other compilers, that is, if the work on other non-GNU compiler, can easily ignore this property. Even __attribute__ using more than one parameter can be easily performed using a pair of parentheses process, for example:

#ifndef __GNUC__
# DEFINE __attribute __ (X)
#endif

Incidentally, __ attribute__ applicable to not function declarations defined functions. So, when the function requires the use of the property must be declared in the same file, for example:

void die(const char *format, ...) __attribute__((noreturn))

 

__attribute__((format(printf,1,2)));
void die(const char *format, ...)
{

}

Variable Attributes (Variable Attributes)
Keywords __attribute__ property can be set to a variable (variable) or body member (structure field) structure. Here are a few common explanation of the parameters, reference may be connected to more parameters given herein.
When using __attribute__ parameters, you can also add the parameters before and after "__" (two underscores), for example, instead of using __aligned__ aligned, so you can use it in the appropriate header file without being concerned about whether there are duplicate names in the header file of macro definitions.
aligned (alignment)
This attribute specifies the minimum alignment variable format or structure member, in bytes. For example:

int X the __attribute__ ((the aligned (16))) = 0;

compiler converts 16-byte (byte to note is not bit bit) assigned to a variable-aligned manner. It may be provided on a structure member of the variable properties, e.g., to create a double-word aligned int pair, can write:

struct {int foo X [2] the __attribute__ ((the aligned (. 8)));};

As described above, you can manually specify the alignment of the format, the same, you can also use the default alignment. If you do not keep up with aligned behind a specific numeric value, the compiler will use the largest and most beneficial alignment based on your target machine situation. For example:

Short Array [. 3] the __attribute__ ((the aligned));

Optional maximum alignment of the target machine, can improve the efficiency of copy operation.
aligned attribute of the object is set to make up more space, on the contrary, can be reduced using the packed space occupied by the object.
It should be noted that the effectiveness of attribute properties and also your connection, and if your connector only supports a maximum 16-byte aligned, then you define the 32-byte aligned at this time is useless.
packed
using the attribute may be such that the variable or structure members with a minimum of alignment, i.e. is a byte aligned variable, domain (field) are bit aligned.
In the following example, x member variable using the attribute, its value will be placed immediately behind the a:

struct Test
{
char A;
int X [2] the __attribute__ ((packed The));
};

other attribute values may also be: cleanup, common, nocommon, deprecated , mode, section, shared, tls_model, transparent_union, unused, vector_size , weak, dllimport, dlexport the like,
detailed information can be found:
http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Variable-Attributes.html#Variable-Attributes
type attribute (type attribute)
keyword __attribute__ property can also be provided for a structure (struct) or a union (union). Generally, there are six parameter values can be set, that is: aligned, packed, transparent_union, unused , deprecated and may_alias.
When using __attribute__ parameters, you can also add the parameters before and after "__" (two underscores), for example, instead of using __aligned__ aligned, so you can use it in the appropriate header file without being concerned about whether there are duplicate names in the header file of macro definitions.
aligned (alignment)
of the attribute setting a specified size format alignment (in bytes), for example:

struct {Short S F [. 3];} the __attribute__ ((the aligned (. 8)));
int more_aligned_int the __attribute__ typedef ((the aligned (8)));
[NextPage]
This statement will force the compiler to ensure (as best it can variable type struct S or more-aligned-int using the 8-byte variable in the distribution of spatially aligned way.
As mentioned above, you can manually specify the alignment of the format, the same, you can use the default alignment. If you do not keep up with aligned behind a specific numeric value, the compiler will use the largest and most based on your target machine case advantageous alignment example:.

struct {Short S F [. 3];} the __attribute__ ((the aligned));

here, if the size sizeof (short) to 2 (byte), then, the size of S is on a take 6 2 power values, so that the value is greater than or equal to 6, the value is 8, so the compiler will set the S type alignment is 8 bytes.
the aligned so that the object property to be set up more space, on the contrary, use packed can reduce the space occupied by the object.
it should be noted that the effectiveness of attribute properties and also your connection, and if your connector only supports a maximum 16-byte aligned, then you this When the 32-byte aligned defined is useless.
Packed The
use of the attribute defined struct types or a union, each variable setting memory constraints of its type. When used in enum type definition, implies a complete type should minimum (it indicates that the smallest integral type should be used).
In the following example, the value of variable array my-packed-struct types will tightly close together, the members inside the variable s is not "pack", if desired, also the interior of the member variable, then packed, my-unpacked-struct need for using the packed corresponding constraints.

my_unpacked_struct struct
{
char C;
int I;
};

struct my_packed_struct  
{
char C;
int I;
struct my_unpacked_struct S;
} __ attribute__ ((__packed__));

meaning other properties see:
http://gcc.gnu.org/onlinedocs/ gcc-4.0.0 / gcc / type- Attributes.html # type-attributes
variable attribute type attribute of example
below using the example __attribute__ attribute defines the structure and variables, and outputs the result given the results analysis.

Program code:


struct p
{
int a;
char b;
char c;
}__attribute__((aligned(4))) pp;

struct q
{
int a;
char b;
struct n qn;
char c;
}__attribute__((aligned(8))) qq;

int main()
{
  printf("sizeof(int)=%d,sizeof(short)=%d.sizeof(char)=%d\n",sizeof(int),sizeof(short),sizeof(char));
  printf("pp=%d,qq=%d \n", sizeof(pp),sizeof(qq));
  return 0;
}

输出结果:

sizeof(int)=4,sizeof(short)=2.sizeof(char)=1
pp=8,qq=24

分析:

the sizeof (PP):
the sizeof (A) the sizeof (B) the sizeof (C) =. 4. 1. 1 =. 6 <23 is =. 8 = the sizeof (PP)
the sizeof (QQ):
the sizeof (A) the sizeof (B) =. 4. 1 =. 5
sizeof (qn) = 8; i.e. qn is 8-byte aligned, so to add 3-byte spare behind a, b, and can store qn,
. 4. 1 (. 3). 1 = 8. 17
because employed aligned qq is 8-byte aligned, qq size must be an integer multiple of 8, i.e., qq is a size large than 17 is a multiple of a minimum value of 8, to obtain
17 <24 8 = 24 = sizeof (qq)

Guess you like

Origin www.cnblogs.com/longchang/p/12170622.html