#include <stdio.h>
#define ABC(x) DEF(x)
#define DEF(x) GHI(x)
#define GHI(x) printf(x)
int main(void)
{
int x = 100;
int y = 200;
ABC(("Sum of x + y is %d", x + y));
return 0;
}
以上代码的输出给出无效的内存引用(SIGSEGV)。
答案 0 :(得分:1)
如果您考虑过这些警告,就可以确定自己的身份
macro1.c: In function ‘main’:
macro1.c:11:3: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast [enabled by default]
ABC(("Sum of x + y is %d", x + y));
^
In file included from macro1.c:1:0:
/usr/include/stdio.h:362:12: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
extern int printf (const char *__restrict __format, ...);
^
macro1.c:11:3: warning: format not a string literal and no format arguments [-Wformat-security]
ABC(("Sum of x + y is %d", x + y));
这显然表明您正在向int
传递string
而不是printf
。
因为预处理后您的代码如下所示。
printf(("Sum of x + y is %d", x + y))
要使其正常工作,您可以执行以下操作。
#include <stdio.h>
#define ABC(x,y) DEF(x,y)
#define DEF(x,y) GHI(x,y)
#define GHI(x,y) printf(x,y)
int main(void)
{
int x = 100;
int y = 200;
ABC("Sum of x + y is %d", x + y);
return 0;
}
或者您可以删除x
中printf
周围的括号
#include <stdio.h>
#define ABC(x) DEF(x)
#define DEF(x) GHI(x)
#define GHI(x) printf x
int main(void)
{
int x = 100;
int y = 200;
ABC(("Sum of x + y is %d", x + y));
return 0;
}