2012-10-03 73 views
0

我对函数的宏有以下问题。这是工作,直到我加入了print_heavyhitters功能。我在m61.h中有:使用宏作为函数

#if !M61_DISABLE 
#define malloc(sz)  m61_malloc((sz), __FILE__, __LINE__) 
#define free(ptr)  m61_free((ptr), __FILE__, __LINE__) 
#define realloc(ptr, sz) m61_realloc((ptr), (sz), __FILE__, __LINE__) 
#define calloc(nmemb, sz) m61_calloc((nmemb), (sz), __FILE__, __LINE__) 
#define print_heavyhitters(sz) print_heavyhitters((sz), __FILE__, __LINE__) 
#endif 

在m61.c中,除print_heavyhitters(sz)外,所有这些函数都很好。我得到“ - 宏的用法错误的功能print_heavyhitters:

- Macro usage error for macro: 
print_heavyhitters 
- Syntax error 

m61.c:

#include "m61.h" 
... 

void *m61_malloc(size_t sz, const char *file, int line) {...} 

void print_heavyhitters(size_t sz, const char *file, int line) {...} 
+1

也许引进一个自引用宏扩展可能会扔你进分辨率适合?请注意所有其他人如何映射到*不同的*名称。 – WhozCraig

回答

8

您为宏和它的目的是扩展到功能使用相同的名称

2

就预处理器而言,对于宏和函数名使用相同的名称是可以的,因为它不会递归地扩展它,但它可能会导致如此混淆的错误。只要你仔细地对#undef它在正确的地方,但我建议使用不同的符号名称以避免混淆。

我会做这样的事情:

// Header file 
#if !M61_DISABLE 
... 
#define print_heavyhitters(sz) m61_print_heavyhitters((sz), __FILE__, __LINE__) 
#endif 

// Source file 
#include "m61.h" 

#if !M61_DISABLE 
#undef print_heavyhitters 
#endif 

void print_heavyhitters(size_t sz) 
{ 
    // Normal implementation 
} 

void m61_print_heavyhitters(size_t sz, const char *file, int line) 
{ 
    // Debug implementation 
}