_ Attribute _ mechanism in C Language

Source: Internet
Author: User

_ Attribute _ mechanism in C Language

Source: chinaunix blog Date: 2008.09.25 (0 comments in total) I want to comment

A major feature of gnu c (but not known to beginners) is the _ attribute _ mechanism. _ Attribute _ FUNCTION attribute, variable attribute, and type attribute can be set ).

The _ attribute _ writing feature has two underscores (_) on the front and back of __attribute _, which are followed by a pair of original arc. The corresponding _ attribute _ parameter is in the ARC.
The syntax format of _ attribute _ is:
_ Attribute _ (Attribute-list ))
Its location constraints are:
Placed before the end of the statement.
Function attribute)
Function Attributes can help developers add some features to the function declaration, which makes the compiler more powerful in error checking. The _ attribute _ mechanism can also be easily compatible with non-GNU applications.

Gnu cc requires the-wall compiler to enable the function. This is a good way to control warning information. The following describes several common attribute parameters.
_ Attribute _ format
The _ attribute can add features similar to printf or scanf to the declared function. It allows 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 that, according to printf, scanf,
The format rules of the strftime or strfmon parameter table check the parameters of the function. "Archetype" specifies the style. "string-index" specifies the first parameters of the Input Function to format the string; "First-to-check" specifies the number of parameters of the function to be 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". For example:
// M = 3; n = 4
Extern void myprint (int l, const char * format ,...)
_ Attribute _ (format (printf, 3,4 )));
The reason is that the first parameter of the class member function is actually a "invisible" "This" pointer. (C ++ users all know the point this pointer. Do you still know it here ?)
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
In attribute. in C, the function declaration removes _ attribute _ (format (printf, 1, 2) and re-compiles it to run $ gcc-wall-C attribute. c attribute does not output any warning information.

Note that by default, the compiler recognizes "standard" library functions similar to printf.
_ Attribute _ noreturn
This attribute notifies the compiler function to never return a value. When a function similar to this attribute requires a return 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. Set
Extern void myexit (); changed:
Extern void myexit () _ attribute _ (noreturn); after compilation, no warning information will appear.
_ Attribute _ 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
{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 address and call address of the current function will be used to call the following

Profiling
Function. (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
It 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. To use extern inline declaration in C code, you 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
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 */
}
For more attributes, refer:
Http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html

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 a variable in 16 bytes (note that byte is not bit) alignment. 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 described above, you can manually specify the aligned format. Similarly, you can also use the default Alignment Method. 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); select the maximum aligned mode for the target machine to 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,

For more information, see:

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

Type attribute)
You can also set attributes for struct or union. There are roughly six parameter values that can be set: 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.

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
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 meanings of other attributes, 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
Http://gcc.gnu.org/
Below are some convenient connections: GCC 4.0 function attributes; GCC 4.0 variable attributes; GCC 4.0 type
Attributes; GCC 3.2 Function Attributes; GCC 3.2 variable attributes; GCC 3.2
Type attributes; GCC 3.1 function attributes; GCC 3.1 variable attributes
Reference:
1. A brief introduction to _ attribute:
Http://www.unixwiz.net/techtips/gnu-c-attributes.html
2. _ attribute _ details:
Http://gcc.gnu.org/

This article is from the chinaunix blog, If you view the original, click: http://blog.chinaunix.net/u2/78225/showart_1223477.html

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.