[英]C macro redefined
I want to replace all the instances of a wrapper function around free() called myfree() with myfree2(). 我想用myfree2()替换名为myfree()的free()周围的包装函数的所有实例。 Unfortunately, I cannot get it to work because the second macro redefines the first. 不幸的是,我无法使其正常工作,因为第二个宏重新定义了第一个宏。 Why is the second macro redefining the first if it has no argument? 如果第二个宏没有参数,为什么要重新定义第一个宏呢?
// I must delete this function or the macro will replace it as well and cause a syntax error!
void myfree(void *p)
{
if(p != NULL)
free(p);
}
void myfree2(void *p)
{
if(p != NULL)
free(p);
}
#define myfree(p) do { myfree2(p); p = (void *)0xdeadbeef; } while (0);
#define myfree myfree2
myfree(p); // Wrapper around free().
afunc(arg, myfree); // Wrapper is used as a function argument!
The C preprocessor does not allow overloading of macros based on the number of arguments -- you can only have a single macro of a given name. C预处理器不允许基于参数的数量重载宏-您只能使用一个具有给定名称的宏。 You can get around this problem in your case by using redundant parentheses in the declaration of myfree
: 您可以通过在myfree
声明中使用多余的括号来解决此问题:
#define myfree(p) do { myfree(p); p = (void *)0xdeadbeef; } while (0)
void (myfree)(void *p)
{
if(p != NULL)
free(p);
}
myfree(p); // Wrapper around free().
afunc(arg, myfree); // Wrapper is used as a function argument!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.