user994165
user994165

Reputation: 9512

Using a macro for a function

I'm having the following problem with a macro for a function. This was working until I added the print_heavyhitters function. I have this in 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

in m61.c, all of these functions are fine except print_heavyhitters(sz). I get " - Macro usage error on the function 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) {...}

Upvotes: 0

Views: 414

Answers (2)

Adam Rosenfield
Adam Rosenfield

Reputation: 400612

Using the same name for the macro and for the function name is OK as far as the preprocessor is concerned, since it won't expand it recursively, but it can easily lead to confusing errors such as this. You can do this as long as you're careful to #undef it in the right places, but I'd recommend using a different symbol name to avoid confusion.

I'd do something like this:

// 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
}

Upvotes: 2

usta
usta

Reputation: 6869

You use the same name for the macro and the function it was intended to expand to.

Upvotes: 8

Related Questions