I'm trying to use a macro to define several similar functions based on the macro's parameters. However the number and types of parameters that the resulting function needs to take isn't the same across all of the functions, but I also need to pass all of the function's arguments into another variadic function inside the function's body.
A minimal example of what I'm trying to accomplish:
#define COMMAND(__COMMAND__, __FORMAT__, ...) \
void __COMMAND__ ( __VA_ARGS__ ) { \
printf( __FORMAT__, ##__VA_ARGS__ ); \
}
COMMAND( Start, "m start %c\r", (char) unit )
COMMAND( Home, "m home\r" )
COMMAND( Add_To_Chart, "cv 0 %d %d\r", (int) ch1, (int) ch2 )
// literally hundreds of additional COMMANDs needed here.
(Note that the actual logic of the function is much more complicated.)
However, I can't figure out a syntax that's valid both as the argument list in a function definition and in a function call.
Using the form (type)arg
isn't valid syntax for the function definition, but I can pass it to the printf
just fine (it's treated as a cast).
COMMAND( A, "cv 0 %d %d\r", (int)ch1, (int)ch2 )
// error: expected declaration specifiers or ‘...’ before ‘(’ token
// void A ( (int)ch1, (int)ch2 ) {
// printf( "cv 0 %d %d\r", (int)ch1, (int)ch2 );
// }
Doing it the other way, type(arg)
, appears to work for the function declaration, but function-style casts are only available in C++, not C, so it fails on printf
.
COMMAND( B, "cv 0 %d %d\r", int(ch1), int(ch2) )
// error: expected expression before ‘int’
// void B ( int(ch1), int(ch2) ) {
// printf( "cv 0 %d %d\r", int(ch1), int(ch2) );
// }
How can I use the variadic macro arguments as both the function's parameter definition and as parameters passed to another function?