Search code examples
cmacrosprecompile

How Can I use double Macro in C


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..


Solution

  • 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;