I'm having a problem with using C macros and was wondering if anybody could help.
I trying to replace callee function using C macro or remove parenthesis of function call. The callee function is passed to macro in form of function call.
I want to transform code to like this:
SOME_MACRO(any_function1(param0, param1)) -> myfunc(param0, param1)
SOME_MACRO(any_function2(param0, param1, param2)) -> myfunc(param0, param1, param2)
Is it possible?
Any help would be appreciated.
CodePudding user response:
You can't write a macro like SOME_MACRO(any_function(param0, param1))
because the contents would be regarded as one single preprocessor token and you wouldn't be able to grab the any_function
part of it.
Instead simply do #define any_function other_function
.
More advanced topic: in case you need to change parameters or add type safety etc, create a "wrapper macro". Take for example this artificial macro:
#define any_function(x, y) _Generic((x), int: other_function) (x,y,z)
This example does 3 things:
- Replace calls to
any_function
withother_function
- Enforce a stricter type safety on the first argument than what's required by a simple function call. For example if you require that the
x
argument must beint
and notunsigned int
,long
,short
or similar, which would otherwise be fine to pass to a function takingint
as parameter ("lvalue conversion" would occur). - Add a 3rd parameter
z
to the call, not present in the caller code, for compatibility reasons. Similarly, we could as well drop one of the parameters or change the order of them.