假设我的代码如下所示:
gpios.h:
#define GPIO_BASE 0x08000100
#define GPIOA ((GpioRegs *) (GPIO_BASE + 0x04))
#define GPIOB ((GpioRegs *) (GPIO_BASE + 0x0C))
#define GPIOC ((GpioRegs *) (GPIO_BASE + 0x14))
开关.h:
#define SWITCH1_PORT GPIOA // On this particular system, both switches
#define SWITCH2_PORT GPIOA // are on the same port. This could change in the future
开关.c:
#if SWITCH1_PORT == SWITCH2_PORT
// Code is a lot simpler if both switches are on the same port
#else
// Otherwise do it the hard way
#endif
SWITCH1_PORT 和 SWITCH2_PORT 在编译时都是常量,因此在编译时比较它们应该是有效的,但在实践中我收到此错误消息:
gpios.h:772:45: error: operator '*' has no right operand
772 | #define GPIOA ((GpioReg *) (GPIO_BASE + 0x04))
| ^
switches.h:102:33: note: in expansion of macro 'GPIOA'
102 | #define SWITCH1_PORT GPIOA
| ^~~~~
switches.c:172:5: note: in expansion of macro 'SWITCH1_PORT'
172 | #if SWITCH1_PORT == SWITCH2_PORT
| ^~~~~~~~~~~~
我尝试将指针转换为 uint32_t,并尝试定义 COMPARE_POINTERS 宏,但没有任何帮助。
有办法在这里做我想做的事吗?
如果展开宏,您可以看到为什么它不能按预期工作:
#if ((GpioRegs *) (GPIO_BASE + 0x04)) == ((GpioRegs *) (GPIO_BASE + 0x04))
AFAIK,你不能在
#if
内部进行类型转换。 您可能必须制作一组不同的宏来解析为整数而不是指针,例如:
gpios.h:
#define GPIO_BASE 0x08000100
#define GPIOA_INT (GPIO_BASE + 0x04)
#define GPIOB_INT (GPIO_BASE + 0x0C)
#define GPIOC_INT (GPIO_BASE + 0x14)
#define GPIOA ((GpioRegs *) GPIOA_INT)
#define GPIOB ((GpioRegs *) GPIOB_INT)
#define GPIOC ((GpioRegs *) GPIOC_INT)
开关.h:
#define SWITCH1_PORT_INT GPIOA_INT
#define SWITCH2_PORT_INT GPIOA_INT
#define SWITCH1_PORT GPIOA
#define SWITCH2_PORT GPIOA
开关.c:
#if SWITCH1_PORT_INT == SWITCH2_PORT_INT
// Code is a lot simpler if both switches are on the same port
#else
// Otherwise do it the hard way
#endif