Search code examples
cglobal-variablesmicrocontrollerinterrupt

Move an interrupt handler and variables from main to a include file


I've a newbie question about how to correctly move an interrupt handler to an include file. I've a SysTick handler in my main.c file defined in this way:

volatile int systick_timer_counter = 0;

void SysTick_Handler(void) {
    systick_timer_counter++;
}

I use this systick_timer_counter, that is increased every 10 ms, to trigger some checks after some time has passed, then reset it.

What I want is to use this systick_timer_counter also inside some functions that aren't in my main.c file, but in another function's .c file. So I want to create a file called systick_counter to include where I need to use it.

What I'm asking is, how should I do this in correct way? I can just create a .c file and place variable and interrupt header inside it, or should I add something more or change variable definition?


Solution

  • It sounds like you mean you want to have a global variable defined in one module (source file) that’s accessible from other modules.

    Assuming I’ve interpreted your question correctly, yes, that can be done by using the extern keyword. However, it would be irresponsible of me not to say that using globals unnecessarily is bad practice. It results in hard-to-maintain code, because an extern global might be changed from anywhere in the code base. You want to limit scope and visibility of your identifiers as much as you can.

    In this instance, I would recommend that you instead keep systick_timer_counter local to the module in which it’s defined, and use functions in that module to access it. It’s like defining a class with methods, in a language that doesn’t have explicit classes. Doing it this way, other modules can’t change the value except by calling reset_systick().

    int systick_timer_counter = 0;
    
    void reset_systick()
    {
        systick_timer_counter = 0;
    }
    
    void SysTick_Handler()
    {
        systick_timer_counter++;
    }
    
    int return_systick()
    {
        return systick_timer_counter;
    }