19

I have a situation where I have quite a few generated functions, and would like to point them at some generic functions that I have created (to allow me to reuse the base code when the generated function names change).

Essentially, I have a list of function names as follows:

void Callback_SignalName1(void);
void Callback_SignalName2(void);
...etc

Once these are generated, I would like to define a macro to allow them to be called generically. My idea was this, but I haven't had any luck implementing it...as the C pre-processor takes the name of the macro instead of what the macro is defined as:

#define SIGNAL1 SignalName1
#define SIGNAL2 SignalName2

#define FUNCTION_NAME(signal) (void  Callback_ ## signal ## (void))
...
...
FUNCTION_NAME(SIGNAL1)
{
  ..
  return;
}

The issue is that I receive

void Callback_SIGNAL1(void)

instead of

void Callback_SignalName1(void)

Is there a good way around this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
erik
  • 3,810
  • 6
  • 32
  • 63
  • shouldn't it be #define FUNCTION_NAME(funcName) void funcName(void)? – Shay Erlichmen Aug 10 '09 at 09:39
  • Sorry, edited for a bit more clarification...I left out an important part that there is another part of the function name to go in there... – erik Aug 10 '09 at 09:41
  • Note that the ## between `signal` and `(void)` is not correct. ## is for creating a single token by concatenating multiple tokens. The open parenthesis can't be (and shouldn't be!) part of the token that will be the function name. – CB Bailey Aug 10 '09 at 09:46

1 Answers1

37

You need to provide an extra level of "function-like macro" to ensure the proper expansion:

e.g.

#define SIGNAL1 SignalName1
#define SIGNAL2 SignalName2

#define MAKE_FN_NAME(x) void  Callback_ ## x (void)
#define FUNCTION_NAME(signal) MAKE_FN_NAME(signal)

FUNCTION_NAME(SIGNAL1)
{
    return;
}

output:

$ gcc -E prepro.cc 
# 1 "prepro.cc"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "prepro.cc"







void Callback_SignalName1 (void)
{
 return;
}
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • indeed; otherwise the ## operator will just concatenate the argument literally to the Callback_. – Adriaan Aug 10 '09 at 10:02