Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pre-processor defining for generated function names

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?

like image 339
the_e Avatar asked Aug 10 '09 09:08

the_e


People also ask

What is __ function __ in C++?

(C++11) The predefined identifier __func__ is implicitly defined as a string that contains the unqualified and unadorned name of the enclosing function. __func__ is mandated by the C++ standard and is not a Microsoft extension.

What is the use of #define preprocessor in C?

#define is a preprocessor directive that is used to define macros in a C program. #define is also known as a macros directive. #define directive is used to declare some constant values or an expression with a name that can be used throughout our C program.

What is __ file __ in C?

__FILE__ This macro expands to the name of the current input file, in the form of a C string constant. This is the path by which the preprocessor opened the file, not the short name specified in ' #include ' or as the input file name argument. For example, "/usr/local/include/myheader.

What to use instead of #define in C?

If you accidentally redefine a name with a #define , the compiler silently changes the meaning of your program. With const or enum you get an error message.


1 Answers

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;
}
like image 99
CB Bailey Avatar answered Oct 24 '22 06:10

CB Bailey