GCC __attribute__ (转载)

  • Post author:
  • Post category:其他


One of the best (but little known) features of GNU C is the

__attribute__

mechanism, which allows a developer to attach characteristics to function declarations to allow the compiler to perform more error checking. It was designed in a way to be compatible with non-GNU implementations, and we’ve been using this for

years

in highly portable code with very good results.

Note that


__attribute__


spelled with two underscores before and two after, and there are always

two

sets of parentheses surrounding the contents. There is a good reason for this – see below. Gnu CC needs to use the

-Wall

compiler directive to enable this (yes, there is a finer degree of warnings control available, but we are very big fans of max warnings anyway).

__attribute__ format

This

__attribute__

allows assigning

printf

-like or

scanf

-like characteristics to the declared function, and this enables the compiler to check the format string against the parameters provided throughout the code. This is

exceptionally

helpful in tracking down hard-to-find bugs.

There are two flavors:



  • __attribute__((format(printf,

    m

    ,

    n

    )))



  • __attribute__((format(scanf,

    m

    ,

    n

    )))

but in practice we use the first one much more often.

The (

m

) is the number of the “format string” parameter, and (

n

) is the numbe



版权声明:本文为tianqio原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。