0

Is there a way of optionally including code using #define like this?

#define TIMR_TO_USE TIM14

#if TIMR_TO_USE == TIM14
    // Do some stuff.
#elif TIMR_TO_USE == TIM16
    // Do some other stuff.
#endif

I feel like this ought to work but doesn't. Is there a way round it?

For info I want to optionally choose which timer to use on an STM32. I have lots of places where I have code like

TIMR_TO_USE->ARR = 1000;

But there are other places where I need different lines of code.

3
  • 2
    Better do #define USE_TIM14 and then #ifdef USE_TIM14 .... #elif defined(USE_TIM16) ... #endif. But why would you want something "around it"? Commented Jan 11, 2023 at 16:04
  • 1
    "where I need different lines of code:" it's unclear what you mean, show more sample code instead of describing it. Commented Jan 11, 2023 at 16:13
  • You need to define TIM14 and TIM16 to different integer values, e.g. 1 and 2. Commented Jan 11, 2023 at 16:36

1 Answer 1

2

Assuming TIM14 and TIM16 are defined as pointers you cannot define these as integers as proposed in a comment but you could use separate preprocessor symbols to select the implementation.

#define USE_TIM14
//#define USE_TIM16

#ifdef USE_TIM14
#    define TIMR_TO_USE TIM14
#elif defined(USE_TIM16)
#    define TIMR_TO_USE TIM16
#else
#    error "no timer selected"
#endif

void func(void)
{
#ifdef USE_TIM14
    // Do some stuff.
#elif defined(USE_TIM16)
    // Do some other stuff.
#endif

    TIMR_TO_USE->ARR = 1000;
}

The error handling could be improved to also detect if multiple USE_TIM* are defined.

Sign up to request clarification or add additional context in comments.

1 Comment

Good guess. That's probably what they're actually trying to achieve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.