在C99中已經有對可變參數宏的擴充,在IAR的幫助文檔中,有這樣的描述 __VA_ARGS__ :
__VA_ARGS__
Syntax
#define P(...) __VA_ARGS__
#define P(x, y, ...) x + y + __VA_ARGS__
__VA_ARGS__
will contain all variadic arguments concatenated, including the separating commas.
Description
Variadic macros are the preprocessor macro equivalents of
printf
style functions.
__VA_ARGS__
is part of the C99 standard.
Example
#if DEBUG
#define DEBUG_TRACE(S, ...) printf(S, __VA_ARGS__)
#else
#define DEBUG_TRACE(S, ...)
#endif
/* Place your own code here */
DEBUG_TRACE("The value is:%d/n",value);
will result in:
這樣子,我們在進行可變參數傳遞的時候,可以參數上面的方案。但是,上的處理方法,在IAR ARM 4.X的環境中會有問題,當我們禁用DEBUG的時候,編譯有時候會出錯:
比如:
DEBUG_TRACE("This is a ideal day!");,
這樣語句會報錯,報錯類型為參數不對。在DEBUG_TRACE所要求的參數與這條語句中的參數不一樣。
DEBUG_TRACE("This is number %d", value);
上面的語句就不會報錯。
這樣,我們從于調試考慮的宏定義就沒有多大的意義了,因為不好禁用調試。
但是,有另外一種方案,這樣方案是一種技巧性的:
#if DEBUG
#define DEBUG_TRACE(args) (printf args)
#else
#define DEBUG_TRACE(args)
#endif
但是在調用DEBUG_TRACE時候,要用兩個引号:
DEBUG_TRACE(("This is a good day!"));
DEBUG_TRACE(("This is number %d",value));
這樣是可用的。太牛B了,當DEBUG使能的時候,其為可變參數,當DEBUG禁能的時候,其為固定參數,因而可以通過編繹連結!