Gnu c's _ attribute _ Mechanism

Source: Internet
Author: User

Gnu c's _ attribute _ Mechanism

----------------------------------------------------------------
Author: afreez@sina.com
Initial Release Date:
Modifier: gates84@gmail.com
----------------------------------------------------------------

_ Attribute _ FUNCTION attribute, variable attribute, and type attribute can be set ).
_ Attribute _ is followed by a pair of parentheses, which contains the corresponding _ attribute _ parameter.
_ Attribute _ syntax format: __attribute _ (Attribute-list ))
The position is: placed at the end of the declaration such as the function; before.

Function attribute)

Function Attributes help developers add some features to function declaration, which makes the compiler more powerful in error checking.
The _ attribute _ mechanism is also easily compatible with non-GNU applications.
Gnu cc uses the-wall compiler to enable the function.

The following describes several common attribute parameters:

Regparm

Tells the compiler to pass function parameters using several general registers.
# Define asmlinkage cpp_asmlinkage _ attribute _ (regparm (0 )))
# Define fastcall _ attribute _ (regparm (3 )))
# Define internal_function _ attribute _ (regparm (3), stdcall ))
The last line indicates that three parameters are passed from the Register, while stdcall indicates that the called function is used to clear the stack. Generally, the caller is used to clear the stack, and cdecl is used.

Format

This attribute adds a feature similar to printf or scanf to the declared function. It enables the compiler to check whether the formatting string between the function declaration and the actually called function parameter matches. This function is very useful, especially for handling bugs that are hard to find.
Format syntax format:
Format (archetype, string-index, first-to-check)
The format attribute tells the compiler to check the parameters of the function according to the format rules of the parameter table of printf, scanf, strftime, or strfmon.
Archetype specifies the style. String-index specifies that the first parameter of the input function is a formatted string. First-to-check specifies that the parameters of the function are checked according to the preceding rules.
The specific format is as follows:
_ Attribute _ (format (printf, m, n )))
_ Attribute _ (format (scanf, m, n )))
The meanings of M and N are as follows:
M: The parameters are formatted strings );
N: The first parameter in the parameter set, that is, the parameter "…" The first parameter is in the number of function parameters. Note that sometimes function parameters are "invisible" and will be mentioned later;
In terms of usage, __attribute _ (format (printf, m, n) is commonly used, but the other is rarely seen.
The following example shows that myprint is a function defined by myself with variable parameters. Its function is similar to printf:
// M = 1; n = 2
Extern void myprint (const char * format,...) _ attribute _ (format (printf, 1, 2 )));
// M = 2; n = 3
Extern void myprint (int l, const char * format,...) _ attribute _ (format (printf, 2, 3 )));
Note that if myprint is a member function of a function, the values of M and N may be a bit "pretty". The reason is, the first parameter of the class member function is actually a "Stealth" "This" pointer.

Here is a test case: attribute. C. The Code is as follows:
1:
2: extern void myprint (const char * format,...) _ attribute _ (format (printf, 1, 2 )));
3:
4: void test ()
5 :{
6: myprint ("I = % d/N", 6 );
7: myprint ("I = % s/n", 6 );
8: myprint ("I = % s/n", "ABC ");
9: myprint ("% s, % d, % d/N", 1, 2 );
10 :}
 
After running $ gcc-wall-C attribute. c attribute, the output result is:
 
Attribute. C: In function 'test ':
Attribute. C: 7: Warning: format argument is not a pointer (ARG 2)
Attribute. C: 9: Warning: format argument is not a pointer (ARG 2)
Attribute. C: 9: Warning: Too few arguments for format
 
If the function declaration in attribute. c removes _ attribute _ (format (printf,) and re-compiles it, no warning information is output.
Note that by default, the compiler recognizes "standard" library functions similar to printf.

Noreturn
This attribute notifies the compiler function to never return a value. When a function needs to return a value but cannot run it to the return value, it exits. This attribute can avoid errors. The declaration formats of abort () and exit () in the C library function use this format, as shown below:
 
Extern void exit (INT) _ attribute _ (noreturn ));
Extern void abort (void) _ attribute _ (noreturn ));
For ease of understanding, you can refer to the following example:
 
// Name: noreturn. c
Test _ attribute _ (noreturn ))
Extern void myexit ();
 
Int test (int n)
{
If (n> 0)
{
Myexit ();
/* The program cannot arrive here */
}
Else
Return 0;
}
 
The output information displayed during compilation is:
 
$ Gcc-wall-C noreturn. c
Noreturn. C: In function 'test ':
Noreturn. C: 12: Warning: control reaches end of non-void Function
 
The warning information is also well understood, because you have defined a function test with returned values, but it may not return values. Of course, the program does not know what to do!
When _ attribute _ (noreturn) is added, the problem like this can be well handled.
Extern void myexit (); changed:
Extern void myexit () _ attribute _ (noreturn ));
After compilation, no warning information will appear.

Const
This attribute can only be used for functions with numeric type parameters. When a function with numeric parameters is repeatedly called, the compiler can optimize the function because the returned values are the same. In addition to the first operation, others only need to return the first result, which can improve the efficiency.
This attribute is mainly applicable to functions without static state and side effects, and the return value only depends on the input parameters.
To illustrate the problem, the following is a very "bad" example. This example will repeatedly call a function with the same parameter value, as shown below:
 
Extern int square (int n) _ attribute _ (const ));
...
For (I = 0; I <100; I ++)
{
Total + = square (5) + I;
}
By adding the _ attribute _ (const) Declaration, the compiler only calls the function once and then directly obtains the same return value.
In fact, the const parameter cannot be used in a function with a pointer type parameter, because this attribute not only affects the parameter value of the function, but also affects the data pointed to by the parameter, it may have serious or unrecoverable consequences for the Code itself.
In addition, functions with this attribute cannot have any side effects or static states. Therefore, functions similar to getchar () or time () are not suitable for this attribute.

-Finstrument-Functions
This parameter allows the program to generate an instrumentation call at the function entry and exit during compilation. Just after the function entry and just before the function exit, the following profiling function will be called using the current function address and call address.
(On some platforms, __builtin_return_address cannot work normally beyond the current function range, so calling address information may be invalid for the profiling function .)
 
Void _ cyg_profile_func_enter (void * this_fn, void * call_site );
Void _ cyg_profile_func_exit (void * this_fn, void * call_site );
 
Among them, the first parameter this_fn is the starting address of the current function, which can be found in the symbol table; the second parameter call_site is the address of the call.
Instrumentation can also be used for inline functions expanded in other functions. In terms of concept, the profiling call will indicate where to enter and exit the inline function. This means that such functions must be addressable. If the function contains inline, and all programs that use this function need to expand this inline, this will increase the code length. If you want
The Code uses the extern inline declaration and must provide the addressable form of this function.

You can specify the no_instrument_function attribute for a function. In this case, no instrumentation operation is performed.
For example, you can use the no_instrument_function attribute in the following situations: the profiling function listed above, the Interrupt Routine with a high priority, and any function that cannot guarantee normal profiling calls.

No_instrument_function
If-finstrument-functions is used, the profiling function will be called at the entry and exit points of the function compiled by most users. With this attribute, no instrument operation is performed.

Constructor/destructor
If the function is set to the constructor attribute, the function is automatically executed before the main () function is executed. Similarly, if a function is set to the Destructor attribute, the function is automatically executed after the main () function is executed or after the exit () function is called. Functions with such attributes are often implicitly used for program initialization data.
These two attributes have not been implemented in Object-Oriented C.

Use multiple attributes at the same time
Multiple _ attribute __s can be used in the same function declaration, which is very common in actual applications.
In terms of usage, you can select two separate _ attribute __, or write them together. You can refer to the following example:
 
/* Pass a message similar to printf to stderr and exit */
Extern void die (const char * format ,...) _ attribute _ (noreturn) _ attribute _ (format (printf, 1, 2 )));
Or write it as extern void die (const char * format,...) _ attribute _ (noreturn, format (printf, 1, 2 )));
If the custom function with this attribute is appended to the header file of the library, the program that calls this function must perform corresponding checks.
 
Compatibility with non-GNU Compilers
Fortunately, the design of __attribute _ is very clever, and it is easy to be compatible with other compilers. That is to say, if you work on other non-GNU compilers, this attribute can be easily ignored. Even if _ attribute _ uses multiple parameters, a pair of circular arc can be easily used for processing. For example:
 
/* If non-gnu c is used, ignore _ attribute __*/
# Ifndef _ gnuc __
# DEFINE _ attribute _ (x)/* nothing */
# Endif
It should be noted that __attribute _ applies to the declaration of functions rather than the definition of functions. Therefore, when you need to use the function of this attribute, it must be declared in the same file, for example:
 
/* Function declaration */
Void die (const char * format,...) _ attribute _ (noreturn) _ attribute _ (format (printf, 1, 2 )));
Void die (const char * format ,...){
/* Function definition */
}

Variable attributes)
You can also set attributes for variables or structure fields.
Here are several common parameter explanations. For more parameters, refer to the connection provided in this Article.
When using the _ attribute _ parameter, you can also add "_" (two underscores) before and after the parameter. For example, use _ aligned _ instead of aligned, in this way, you can use it in the corresponding header file without worrying about whether there is a macro definition with the same name in the header file.

Aligned (alignment)
This attribute specifies the smallest alignment format of a variable or struct Member, in bytes. For example:
Int X _ attribute _ (aligned (16) = 0;
The compiler allocates variables in 16-byte alignment mode.
You can also set this attribute for the struct member variable. For example, to create a double-font-aligned int pair, you can write it like this:
Struct Foo {int X [2] _ attribute _ (aligned (8 )));};
As mentioned above, you can manually specify the alignment format. Similarly, you can also use the default alignment mode.
If aligned is not followed by a specified number, the compiler will use the most useful aligned method based on your target machine. For example:
Short array [3] _ attribute _ (Aligned ));
Selecting the maximum alignment mode for the target machine can improve the efficiency of the copy operation.
The aligned attribute makes the set object occupy more space. On the contrary, using packed can reduce the space occupied by the object.
It should be noted that the effectiveness of attribute attributes is also related to your connector. If your connector supports 16-byte alignment at most, defining 32-byte alignment at this time will not help.

Packed
This attribute enables the smallest alignment mode for variables or struct members, that is, one-byte alignment for variables and bit alignment for fields.
In the following example, if the x member variable uses this attribute, its value is placed after:
 
Struct test {
Char;
Int X [2] _ attribute _ (packed ));
};
Other optional attribute values include cleanup, common, nocommon, deprecated, mode, section, shared, tls_model, transparent_union, unused, vector_size, weak, dllimport, and dlexport.

Type attribute)
You can also set attributes for struct or union. There are roughly six parameter values that can be set,
That is: aligned, packed, transparent_union, unused, deprecated, and may_alias.
When using the _ attribute _ parameter, you can also add "_" (two underscores) before and after the parameter. For example, use _ aligned _ instead of aligned, in this way, you can use it in the corresponding header file without worrying about whether there is a macro definition with the same name in the header file.

Aligned (alignment)
This attribute sets an alignment format (in bytes) of the specified size. For example:
Struct s {short f [3];} _ attribute _ (aligned (8 )));
Typedef int more_aligned_int _ attribute _ (aligned (8 )));
 
This statement forces the compiler to make sure that variables of the type struct s or more-Aligned-int use an 8-byte aligned-int to allocate space.
As mentioned above, you can manually specify the alignment format. Similarly, you can also use the default alignment mode. If aligned is not followed by a specified number, the compiler will use the most useful aligned method based on your target machine. For example:
Struct s {short f [3];} _ attribute _ (Aligned ));
 
Here, if the size of sizeof (short) is 2 (byte), the size of S is 6. Take the power of 2 so that the value is greater than or equal to 6, then the value is 8, so the compiler sets the alignment of the S type to 8 bytes.
Packed
Use this property to define the struct or union type and set the memory constraints for each variable of its type. When used in the enum type definition, it implies that the minimum complete type should be used (it indicates that the smallest integral type shoshould be used ).
In the following example, the values in the array of variables of the my-packed-struct type are closely tied, but the internal member variable S is not "pack ", if you want the internal member variables to be packed, you also need to use packed to constrain my-unpacked-struct.
 
Struct my_unpacked_struct
{
Char C;
Int I;
};

Struct my_packed_struct
{
Char C;
Int I;
Struct my_unpacked_struct S;
}__ Attribute _ (_ packed __));
 
For the meaning of other properties, see: http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Type-Attributes.html#Type-Attributes

Examples of variable attributes and type attributes
The following example uses the _ attribute to define some struct and Its variables, and provides output results and analysis of results.
The program code is:
 
Struct P
{
Int;
Char B;
Char C;
}__ Attribute _ (aligned (4) pp;
 
Struct Q
{
Int;
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;
}
 
Output result:
 
Sizeof (INT) = 4, sizeof (short) = 2. sizeof (char) = 1
Pp = 8, QQ = 24
 
Analysis:
Sizeof (PP ):
Sizeof (A) + sizeof (B) + sizeof (c) = 4 + 1 + 1 = 6 <23 = 8 = sizeof (PP)
Sizeof (qq ):
Sizeof (A) + sizeof (B) = 4 + 1 = 5
Sizeof (qN) = 8;
That is, qN is 8-byte aligned. Therefore, three spare bytes must be added after A and B before the Qn, 4 + 1 + (3) + 8 + 1 = 17 can be stored.
Because QQ uses 8-byte alignment, the QQ size must be an integer multiple of 8, that is, the QQ size is a minimum value greater than 17 and a multiple of 8.
17 <24 + 8 = 24 = sizeof (qq)
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.