如何在 C 中使用双宏

How Can I use double Macro in C

让我们看看我的代码T.T

我定义的宏如下所示

这是我的宏头文件。 macro.h

#define BUZZER_PWM                                  PWMA
#define BUZZER_PWM_CH                               0
#define ENABLE_PWM(pwm,ch)      (pwm)->POE |= PWM_POE_PWM##ch##_Msk     

并在另一个cfile中调用宏

ENABLE_PWM(BUZZER_PWM,BUZZER_PWM_CH);

我预编译后的结果是

PWMA -> POE |= PWM_POE_PWM0_Msk;

但是

PWMA -> POE |= PWM_POEBUZZER_PWM_CH_Msk;

结果。 有什么解决办法吗??

对不起,我的英语水平很差..

为确保宏参数(在您的情况下具体为 BUZZER_PWM_CH)在串联 (PWM_POE_PWM##ch##_Msk) 之前得到扩展,请使用额外的宏。

示例文件macro.c

#define BUZZER_PWM                                  PWMA
#define BUZZER_PWM_CH                               0
#define ENABLE_PWM(pwm,ch)      ENABLE_PWM_(pwm,ch)
#define ENABLE_PWM_(pwm,ch)      (pwm)->POE |= PWM_POE_PWM##ch##_Msk     

/* expected expansion */
ENABLE_PWM(BUZZER_PWM,BUZZER_PWM_CH);

/* wrong expansion */
ENABLE_PWM_(BUZZER_PWM,BUZZER_PWM_CH);

扩展为

$ gcc -E macro.c
# 1 "macro.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "macro.c"






(PWMA)->POE |= PWM_POE_PWM0_Msk;


(PWMA)->POE |= PWM_POE_PWMBUZZER_PWM_CH_Msk;