I would like to have a macro that prints it's own name (among other things), but I can't find a way to expand the macros' name in the macro itself. Basically, I want the equivalent of __FUNCTION__
for a macro name.
For example:
#define F(a, b, c) do { \
printf("%s: %s,%s,%s\n", __MACRO__, #a, #b, #c); \
c = a+b; b=a; \
} while(0)
F(x,y,z);
I would like this to print "F: x,y,z" when called.
This is indeed an XY problem.
Here is really what I'm trying to do: Soft linking symbols from a library using dlopen and dlsyms.
In order to do so the typical way i know of is: 1) Include the headers from the library. 2) Declare a variable of the type of the function you are trying to import 3) Initialize said variable with a call to dlsym 4) The call the actual function through that variable instead of calling the symbol directly.
When you have many such function to soft link, it becomes very repetitive, so macro can help.
For an full fledge example of that, see here: https://github.com/WebKit/webkit/blob/master/Source/WebCore/platform/mac/SoftLinking.h
The problem in that example and others is that you still need to manually copy the parameters list for each the functions you want to soft link. I'm trying to improve on that, and was experimenting with macro tricks, one of which would have been helped by being able to answer my initial question.
--
Beside my soft linking issues, there are other situation where this could be useful. For example for debugging purpose, one might want to print some diagnostic information before or after every call to certain functions. One could do so by overriding functions names with macros:
#define funcA(...) \
printf("Before call to %s:%d - %d\n", #funcA, __LINE__, g_count); \
funcA(__VA_ARGS__) \
printf("After call to %s:%d - %d\n", #funcA, __LINE__, g_count);
This works well enough but if I want to do this for a bunch of function, I have to copy that macro and change funcA to funcB 4 times for each new macro. I'd rather copy it and just change the name of the macros, without having to change what's inside.
I can optimize the above by defining an internal macro p, similar to what Basile suggested:
#define funcA(...) WRAP(funcA, __VA_ARGS__)
But that's still means I need to change funcA to the new function name twice every time I copy the macro for another function.
#define P(f, ...) printf("%s%s\n", f, __VA_ARGS__)
– Droopycom