功能:
__attribute__ format屬性可以給被聲明的函數加上類似printf或者scanf的特徵,它可以使編譯器檢查函數聲明和函數實際調用參數之間的格式化字符串是否匹配。format屬性告訴編譯器,按照printf, scanf等標準C函數參數格式規則對該函數的參數進行檢查。這在我們自己封裝調試信息的接口時非常的有用。
format的語法格式爲:
format (archetype, string-index, first-to-check)
其中,“archetype”指定是哪種風格;“string-index”指定傳入函數的第幾個參數是格式化字符串;“first-to-check”指定從函數的第幾個參數開始按上述規則進行檢查。
具體的使用如下所示:
__attribute__((format(printf, m, n)))
__attribute__((format(scanf, m, n)))
其中參數m與n的含義爲:
m:第幾個參數爲格式化字符串(format string);
n:參數集合中的第一個,即參數“…”裏的第一個參數在函數參數總數排在第幾。注意,有時函數參數(類成員函數)裏還有“隱身”的(this指針);
一般函數:
爲自己定義的一個帶有可變參數的函數,其功能類似於printf:
extern void myprint(const char *format,...) __attribute__((format(printf,1,2))); //m=1;n=2
extern void myprint(int l,const char *format,...) __attribute__((format(printf,2,3))); //m=2;n=3
類成員函數
需要特別注意的是,如果myprint是一個函數的成員函數,那麼m和n的值可有點“懸乎”了,例如:
extern void myprint(int l,const char *format,...) __attribute__((format(printf,3,4)));
其原因是,類成員函數的第一個參數實際上一個“隱身”的“this”指針。
這裏給出測試用例:test.c,代碼如下:
extern void myprint(const char *format,...) __attribute__((format(printf,1,2)));
void test()
{
myprint("i=%d\n",6);
myprint("i=%s\n",6);
myprint("i=%s\n","abc");
myprint("%s,%d,%d\n",1,2);
}
轉自:https://blog.csdn.net/zzhongcy/article/details/90057284
更多優質技術文章閱讀,IEEE、萬方文獻及國內外專利下載,請關注微信公衆號IEEE