I actually did something similar quite recently and learned the pitfalls of passing in code as a macro argument.
For example try this seemingly correct code (using the first macro definition):
MY_MACRO(int foo(int a, int b)
,
{
int c = 1, d = 2;
return a + b + c + d;
}
)
You'll most likely see a compile error something to the tune of the macro expecting only 2 arguments while you provided 3.
What happens is that the macros are compiled by the pre-processor which doesn't care about C syntax. So in it's eyes, each ,
is a argument separator. So it thinks that the first argument to the macro is int foo(int a, int b)
, the second argument { int c = 1
and the third argument as d = 2; return a + b + c + d; }
.
So basically, the moral of the story is that "never pass in code as argument". Most macros that want to be flexible code-wise compile down into a if
or a for
statement (e.g. list_for_each
in http://lxr.free-electrons.com/source/include/linux/list.h#L407).
I'd suggest that you stick to standard #ifdef
ery in your situation. e.g.
#ifndef UNIT_TEST
int foo(...) {
//actual implementation
}
#else
int foo(..) {
return 0;
}
#endif
This sort of code is fairly standard: http://lxr.missinglinkelectronics.com/#linux+v3.13/include/linux/of.h (search for CONFIG_OF
)