#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__的作用

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