I'm having a problem with optional arguments in #define statements in C, or more specifically with gcc 4.2:
bool func1(bool tmp) { return false; }
void func2(bool tmp, bool tmp2) {}
#define CALL(func, tmp, ...) func(tmp, ##__VA_ARGS__)
int main() {
// this compiles
CALL(func2, CALL(func1, false), false);
// this fails with: Implicit declaration of function 'CALL'
CALL(func2, false, CALL(func1, false));
}
That's obviously a contrived example, but does show the problem. Does anyone know how I can get the optional arguments to "resolve" correctly?
Additional information:
If I remove the ##
before __VA_ARGS__
, and do something like this:
bool func2(bool tmp, bool tmp2) { return false; }
#define CALL(func, tmp, ...) func(tmp, __VA_ARGS__)
int main() {
CALL(func2, false, CALL(func2, false, false));
}
That compiles, but it no longer works with zero arguments since it would resolve to func(tmp, )
EDIT: Right after converting all of my code to rely on P99 instead of what I had earlier (which ended up breaking my code considerably, whoops), I accidentally discovered that this works:
bool func1(bool tmp) { return false; }
void func2(bool tmp, bool tmp2) {}
#define CALL2(func, tmp, p...) func(tmp, ##p)
#define CALL(func, tmp...) CALL2(func, tmp)
int main() {
// works
CALL(func2, CALL(func1, false), false);
// ...also works
CALL(func2, false, CALL(func1, false));
}
Compiles and works with any number of parameters (and the correct values are passed in and returned), but... is this supposed to be legal?