gpt4 book ai didi

c - 如何在 C 中使用双宏

转载 作者:行者123 更新时间:2023-12-04 04:05:28 25 4
gpt4 key购买 nike

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

我定义了我的宏,如下所示

这是我的宏头文件。宏.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;

关于c - 如何在 C 中使用双宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62572209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com