2010年1月27日 星期三

[語言] __attribute__

這東西的用法很特別,來自GNU C,挑幾個我看過
OR用過的做ㄧ下筆記

會用跟搞清楚~~還真的有點距離。
用來檢查函數的格式:
可以叫complier幫你檢查如果你的函數長的像printf 或scanf 等等

example:

#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

int bbprintf(int i, const char *fmt, ...) __attribute__((format(printf,2,3)));

int bbprintf(int i, const char *fmt, ...)
{
    va_list args;

    printf("i = %d \n", i);

    va_start(args, fmt);
    return vfprintf(stdout, fmt, args);
}


int main()
{
    bbprintf(10 ,"num = %d \n", 5);
}

這樣他就會幫你把bbprintf()用printf檢查一番
例如: 故意把%d 換成%s

warning: format '%s' expects type 'char *', but argument 3 has type 'int'

指令說明:
format(printf,2,3)
第一格:printf -> 依照printf的樣子檢查
第二格:2 -> const char *fmt 這是第二欄
第三格:3 -> ... 這是第三欄

之前有遇過類似的問題,如果可以這個檢查應該可以避掉

--
這個也可以避掉void function 的呼叫被放在有return 的位置,
避免 complier 跟你靠腰

void myexit(void)  __attribute__ ((__noreturn__));

void myexit()
{
    printf("YA \n");
    exit(1);  <--- 不能省 不然你會看到更奇怪的靠腰,原因是程式需要在這裡終止。
}

int main()
{
    int n = 1;
    if( n > 0 )
    {
        myexit();
    }else
        return 0;
}

是意思是告訴complier myexit是沒有回傳的function 就算他放在需要回傳的function裡,也請睜ㄧ隻眼閉一隻眼。
abort() 就是用同樣的方式宣告。

否則你會看到以下的訊息
warning: control reaches end of non-void function

以上在complier時記得加上  -Wall 才看到的

當然還有
const
aligned
packed
使用該屬性可以使得變量或者結構體成員使用最小的對齊方式

還很多,packed有看過,沒用到就先不記錄了。

沒有留言:

張貼留言