#定义在C元组 [英] #define a tuple in C
问题描述
我希望能够定义一个元组从而重新presents其他宏所需要的参数。
I want to be able to define a tuple which represents the arguments needed by other macros.
我想表现出我想要的最好的办法就是展示一个例子:
I think the best way to show what I want is to show an example:
#include <avr/io.h>
#define LED_PORT PORTB
#define LED_DDR DDRB
#define LED_PIN PB7
#define LED LED_PORT, LED_DDR, LED_PIN
#define OUTPUT(port, ddr, pin) ddr |= 1 << pin
void main(void) {
OUTPUT(LED);
}
我想输出(LED)
然后扩展到:
LED_DDR |= 1 << LED_PIN
这是我得到的问题是与扩展的顺序做,并导致以下错误:
The problem that I get is to do with the order of expansion, and results in the following error:
微距输出需要3个参数,但只给出1
macro "OUTPUT" requires 3 arguments, but only 1 given
这是与定制硬件的AVR项目中,我已经定义了 LED
,并与相应的 LED_PORT $ C等成分的使用$ C>
LED_DDR
和 LED_PIN
。
This is for use with an AVR project with custom built hardware where I have defined LED
and other components with a respective LED_PORT
LED_DDR
and LED_PIN
.
然后,我希望定义可以利用这个LED,并使用适当的参数映射到可能的最简洁的方式更多的宏。
I then want to define more macros that can take this LED and use the appropriate arguments to map to the most succinct way possible.
这可能与标准的C preprocessor?
Is this possible with the standard C-preprocessor?
推荐答案
您可以间接层添加到宏来实现这一点:
You can add a level of indirection to the macro to achieve this:
#define OUTPUT_I(port, ddr, pin) ddr |= 1 << pin
#define OUTPUT(spec) OUTPUT_I(spec)
在重新扫描,规范
在 OUTPUT_I
扩大,因此 OUTPUT_I
宏看到三个参数。
During rescanning, spec
is expanded before OUTPUT_I
, so the OUTPUT_I
macro sees three parameters.
这篇关于#定义在C元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!