3

Let's see my code T.T

I defined my macros as shown as below

This is my macro header file. macro.h

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

and call macro in another cfile

ENABLE_PWM(BUZZER_PWM,BUZZER_PWM_CH);

I pretected the result after precompile is

PWMA -> POE |= PWM_POE_PWM0_Msk;

But

PWMA -> POE |= PWM_POEBUZZER_PWM_CH_Msk;

is resulted. Is there any solution??

Sorry for my ugly English skills..

Bodo
  • 9,287
  • 1
  • 13
  • 29
Setian
  • 43
  • 4
  • 1
    Essentially duplicate of [this](https://stackoverflow.com/a/3221914/10404680). – WENDYN Jun 25 '20 at 12:05
  • when writing header files, always include the include guards: at the top of the file: `#ifndef MACRO_H` and `#define MACRO_H` then at the end of the file: `#endif // MACRO_H` – user3629249 Jun 26 '20 at 05:37

1 Answers1

1

To make sure the macro arguments (specifically BUZZER_PWM_CH in your case) get expanded before the concatenation (PWM_POE_PWM##ch##_Msk) use an additional macro.

Example file 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);

is expanded as

$ 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;
Bodo
  • 9,287
  • 1
  • 13
  • 29