我想用myfree2()替换名为myfree()的free()周围的包装函数的所有实例。不幸的是,我无法让它工作,因为第二个宏重新定义了第一个宏。如果第二个宏没有参数,为什么重新定义第一个?
// 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!
答案 0 :(得分:0)
C预处理器不允许根据参数的数量重载宏 - 您只能拥有给定名称的单个宏。通过在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!