如何在 Cpp 中定义两个标记的宏
How to define a macro of two tokens in Cpp
在我的 Arduinoc (cpp) 代码中,我有这些宏 set/clear 寄存器 x 的位 y:
#define SET(x,y) x |= (1 << y)
#define CLEAR(x,y) x &= ~(1<< y)
然后我在几个地方使用:
CLEAR(PORTB,7)
或
SET(PORTB,7)
我想将一个宏定义为 PORTB,7 这样它只出现一次,在一个头文件中,而不是在我的所有代码中。 (我只展示了一个例子,但我的代码中有几个 PORTx,N 的组合)。
我试过了:
#define CLOCK PORTB,7
#define CLOCK_HIGH SET(CLOCK)
但它随后无法构建:
error: macro "SET" requires 2 arguments, but only 1 given CLOCK_HIGH; delay(DELAY); CLOCK_LOW; delay(DELAY);
有办法实现吗?
你必须先展开里面的宏。 IE。做另一遍。您的代码可能如下所示:
#define SET(x,y) do{ (x) |= (1u << (y)); }while(0)
#define CLEAR(x,y) do{ (x) &= ~(1u << (y)); }while(0)
#define HIGH(a) SET(a) // another empty pass, just forward
// the `a` is expanded and the second `SET` takes two arguments
// or better, but not fully compliant:
// #define HIGH(...) SET(__VA_ARGS__)
#define CLOCK PORTB, 7
#define CLOCK_HIGH() HIGH(CLOCK)
int main() {
int PORTB;
CLOCK_HIGH();
}
关于macro pitfalls and research good practices when writing macros.的一个很好的衡量研究。
在我的 Arduinoc (cpp) 代码中,我有这些宏 set/clear 寄存器 x 的位 y:
#define SET(x,y) x |= (1 << y)
#define CLEAR(x,y) x &= ~(1<< y)
然后我在几个地方使用:
CLEAR(PORTB,7)
或
SET(PORTB,7)
我想将一个宏定义为 PORTB,7 这样它只出现一次,在一个头文件中,而不是在我的所有代码中。 (我只展示了一个例子,但我的代码中有几个 PORTx,N 的组合)。
我试过了:
#define CLOCK PORTB,7
#define CLOCK_HIGH SET(CLOCK)
但它随后无法构建:
error: macro "SET" requires 2 arguments, but only 1 given CLOCK_HIGH; delay(DELAY); CLOCK_LOW; delay(DELAY);
有办法实现吗?
你必须先展开里面的宏。 IE。做另一遍。您的代码可能如下所示:
#define SET(x,y) do{ (x) |= (1u << (y)); }while(0)
#define CLEAR(x,y) do{ (x) &= ~(1u << (y)); }while(0)
#define HIGH(a) SET(a) // another empty pass, just forward
// the `a` is expanded and the second `SET` takes two arguments
// or better, but not fully compliant:
// #define HIGH(...) SET(__VA_ARGS__)
#define CLOCK PORTB, 7
#define CLOCK_HIGH() HIGH(CLOCK)
int main() {
int PORTB;
CLOCK_HIGH();
}
关于macro pitfalls and research good practices when writing macros.的一个很好的衡量研究。