同名的宏和函数 [英] Macro and function with same name
问题描述
我有以下代码
#define myfunc(a,b) myfunc(do_a(a), do_b(b))
void myfunc(int a, int b)
{
do_blah(a,b);
}
int main()
{
int x = 6, y = 7;
myfunc(x,y);
return 0;
}
我希望预处理器仅在调用时扩展函数 myfunc.预处理后所需的代码如下所示:
I want the pre-processor to expand function myfunc only at calling. Required code after pre-processing looks like this:
void myfunc(int a, int b)
{
do_blah(a,b);
}
int main()
{
int x = 6, y = 7;
myfunc(do_a(x),do_b(y));
return 0;
}
问题是函数定义也是这样展开的
The problem is that function definition is expanded also like this
void myfunc(do_a(int a), do_b(int b))
{
do_blah(a,b);
}
有没有办法让宏只在我们扩展函数调用时才扩展?我尝试了很多解决方案,似乎不可能,但我希望有人看到这样的情况..
Is there any way to make macro expands only if we are expanding a function call? I tried many solutions, and it seems impossible but I hope that some one saw situation like this..
注意:请不要告诉我重命名宏或函数名称:D
NOTE: please don't tell me to rename the macro or function names :D
更新1:谢谢你的帮助.但是我只能改变宏的定义,不能改变它的位置,也不能改变函数实现.
Update1: Thanks for you help. But I can only change the definition of the macro, I can't change its position and I can't change function implementation.
推荐答案
使用()
来阻止预处理器扩展函数定义:
Use ()
to stop the preprocessor from expanding the function definition:
#include <stdio.h>
#define myfunc(a, b) myfunc(do_a(a), do_b(b))
/* if you have a preprocessor that may be non-standard
* and enter a loop for the previous definition, define
* myfunc with an extra set of parenthesis:
#define myfunc(a, b) (myfunc)(do_a(a), do_b(b))
******** */
int (myfunc)(int a, int b) /* myfunc does not get expanded here */
{
printf("a=%d; b=%d
", a, b);
return 0;
}
int do_a(int a)
{
return a * 2;
}
int do_b(int b)
{
return b - 5;
}
int main(void)
{
myfunc(4, 0);
return 0;
}
这篇关于同名的宏和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!