#define DEBUG(format, ...) 以及 #、##、__VA_ARGS__和##__VA_ARGS__的作用

#define debug(…) printf(VA_ARGS)
缺省號代表一個可以變化的參數表。使用保留名 VA_ARGS 把參數傳遞給宏。當宏的調用展開時,實際的參數就傳遞給 printf()了。例如:
Debug(“Y = %d\n”, y);
而處理器會把宏的調用替換成:
printf(“Y = %d\n”, y);


#include<stdio.h>
#ifdef DEBUG
//#define debug(...) printf(__VA_ARGS__);
//#define debug(format, ...) printf(format, __VA_ARGS__);
#define debug(format, ...) printf("Info:[%s:%s(%d)]:" format "\n", __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define debug(format, ...);
#endif

#define XNAME(n) x##n
#define PRINT_XN(n) printf("x"#n "=%d\n", x##n);

#define DBG(format, arg...) printf(format, ##arg)
#define DBG1(format, arg...) printf(#format, ##arg)
int main()
{
        int value = 9;
        DBG("%s-%d\n", "hello", 4);
        DBG1(%s-%d\n, "world", 5);
        debug("Hi");
        debug();
        debug("value = %d", value);
        int XNAME(1) = 14; // x1 = 14
        PRINT_XN(1); // printf("x1=%d", x1);
}

使用參數-D 相當於在代碼中使用#define DEBUG

kayshi@ubuntu:~/code/debug_info$ gcc -o debug debug.c -D DEBUG
kayshi@ubuntu:~/code/debug_info$ ./debug 
hello-4
world-5
Info:[debug.c:main(20)]:Hi
Info:[debug.c:main(21)]:
Info:[debug.c:main(22)]:value = 9
x1=14

#define debug(format, …) printf(format, ##VA_ARGS);

##的意思是: 如果可變參數位空,則使預處理器去除前面的那個逗號。如果沒有##,例如:
#define debug(format, …) printf(format, VA_ARGS);,這樣只有format,沒有可變參數,會被預處理爲下面的樣子,並報error。 如果有##,預處理會把逗號去掉。

debug(”Hi“) printf(”HI\n“, )

kayshi@ubuntu:~/code/debug_info$ gcc -o debug debug.c -D DEBUG
debug.c: In function ‘main’:
debug.c:5:54: error: expected expression before ‘)’ token
 #define debug(format, ...) printf(format, __VA_ARGS__);
                                                      ^
debug.c:22:2: note: in expansion of macro ‘debug’
  debug("Hi\n");
  ^~~~~

ANSI C 有幾個標準的預定義宏,爲:

__FUNCTION__ :當前函數名

__FILE__ : 當前源代碼的文件名。

__LINE__: 當前源代碼的行號。

__DATE__:當前的編譯日期。

__TIME__:當前的編譯時間。

轉:#、##、__VA_ARGS__和##__VA_ARGS__的作用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章