有没有办法将多个值作为C中单个定义的宏值传递给宏函数?

baj*_*tec 13 c macros gcc avr

我想在全局标头中将引脚定义声明为一条简单的行,例如:

#define STATUS_LED B,7
Run Code Online (Sandbox Code Playgroud)

然后,我想将此引脚定义传递给以上功能:

CMBset_out(STATUS_LED);
Run Code Online (Sandbox Code Playgroud)

我不知道该如何处理-MY_PIN格式正确,可以在预编译阶段替换。

#define CMBsbi(port, pin) (PORT##port) |= (1<<pin)
#define CMBset_out(port,pin) (DDR##port) |= (1<<pin)
// define pins 
#define STATUS_LED B,7
Run Code Online (Sandbox Code Playgroud)

Then, I want to pass this pin definition to function above (hw_init_states() is declared in the same header file called from main C file):

// runtime initialization
void hw_init_states(){
#ifdef STATUS_LED
    CMBset_out(STATUS_LED);
#endif
}
Run Code Online (Sandbox Code Playgroud)

But I get a compilation error:

Error   1   macro "CMBset_out" requires 2 arguments, but only 1 given   GENET_HW_DEF.h  68  23  Compass IO_proto
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 8

It is possible, but you need another level of macros to expand the argument:

#define CMBset_out_X(port,pin) (DDR##port) |= (1<<pin)
#define CMBset_out(x) CMBset_out_X(x)
Run Code Online (Sandbox Code Playgroud)

Of course this means that you can't use the CMBset_out macro with two explicit arguments.

  • @bajtec:因为预处理程序是通过运行的;第一遍将CMBset_out(STATUS_LED)替换为CMBset_out_X(B,7),然后第二遍将CMBset_out_X宏替换。 (4认同)

mos*_*svy 7

对先前答案的改进,它还允许您使用两个显式参数调用宏。

它应可与任何c99(或更高版本)的编译器一起使用:

#define CMBset_out_X(port,pin) (DDR##port) |= (1<<pin)
#define CMBset_out(...) CMBset_out_X(__VA_ARGS__)

#define STATUS_LED B,7
CMBset_out(STATUS_LED)
CMBset_out(B, 7)
Run Code Online (Sandbox Code Playgroud)