GCC __attribute__特性の妙用


GCCには、コンパイラに宣言されたプロパティを通知する機能があり、コンパイルフェーズでシンボルを参照する場所で呼び出し方がプロパティに合っているかどうかを確認し、エラーを早期に発見できるように警告情報を生成します.
attribute formatはprintf-likeまたはscanf-likeの関数宣言にattribute((format(printf,m,n))またはattribute((format(scanf,m,n))を加える.コンパイル時に関数呼び出し位置をチェックすることを示します.デジタルmはformat stringを表すいくつかのパラメータであり、nは変長パラメータがいくつかのパラメータに位置することを表す.直観的な例を挙げる.
<!-- lang: cpp -->
// gccattr.c
extern void myprintf(const int level, const char *format, ...) 
    __attribute__((format(printf, 2, 3))); // format 2 , ... 3 

void func()
{
    myprintf(1, "s=%s
", 5); myprintf(2, "n=%d,%d,%d
", 1, 2); }

そしてgccでこのファイルをコンパイルし、コンパイルアラーム-Wallを開くことに注意します.
<!-- lang: shell -->
$ gcc -Wall -c gccattr.c -o gccattr.o
gccattr.c: In function ‘func’:
gccattr.c:5: warning: format ‘%s’ expects type ‘char *’, but argument 3 has type ‘int’
gccattr.c:7: warning: too few arguments for format

コンパイラはattributeに基づいてmyprintf関数のパラメータをチェックし、長くなるパラメータのタイプが正しくないためにアラートが発生したことがわかります.このチェックは、myprintf(1,“s=%s”,5)などのパラメータの誤用によるプログラムのクラッシュを回避し、アクセスが無効なアドレスセグメントエラーを引き起こすことを回避します.
attributeには、変数またはタイプチェックで使用できる他の宣言プロパティもあります.gnuのマニュアルを参照してください.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 http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Type-Attributes.html
http://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Function-Attributes.html http://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Variable-Attributes.html http://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Type-Attributes.html