C 对函数使用宏
函数的宏有以下问题。在我添加print_heavyhitters函数之前,它一直在工作。我在m61.h中有这个:C 对函数使用宏,c,macros,C,Macros,函数的宏有以下问题。在我添加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), __
#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_heavyhittersz之外,所有这些函数都很好。I get-函数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) {...}
对于宏和它要扩展到的函数,使用相同的名称。对于预处理器来说,使用相同的宏和函数名称是可以的,因为它不会递归地扩展它,但很容易导致类似这样的混淆错误。您可以这样做,只要您小心地在正确的位置取消定义它,但我建议使用不同的符号名称以避免混淆 我会这样做:
// 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
}
也许引入自参考宏扩展会让您陷入分辨率匹配?注意所有其他名称是如何映射到不同的名称的。