Summary of attribute usage

Source: Internet
Author: User
Document directory
  • Function attribute)
  • Variable attributes)
  • Type attribute)

_ 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.

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 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 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 use,_ Attribute _ (format (printf, m, n )))Is commonly used, but the other is rarely seen. The following is an example.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 ?)

_ 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 < 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.

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.

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, you must declare it in the same file.

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 will assign a variable in 16-byte (note that byte is not bit) alignment.
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 a;
            int x[2] __attribute__ ((packed));
          };
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 __));

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.