If the variable is accessed by both the interrupt and main code then it must be visible to both, either at file scope or globally between files. Declaring the variable as static
is not a problem.
With regards to volatile
, if you are setting a flag in the interrupt function that is then polled by the main code to detect the occurrence of the interrupt event then you must declare the variable as volatile
or you can get what appears as incorrect code operation, but is in fact totally legal.
e.g. waiting in a loop for a flag to be set by the interrupt
while ( !Interrupt_Flag )
{
}
If the variable Interrupt_Flag
is not declared volatile
then the compiler can read its value just once and either loop forever or skip over the loop without ever entering the loop. If it is declared volatile
then the variable will be read on every iteration of the loop.
Just because a variable is used in the interrupt function does not make it volatile.
If you modify the value of the variable in the interrupt function and main code, e.g. set the flag in the interrupt and clear in the main code, then you must remember to disable interrupts around the lines where you modify the value in the main code or strange things will happen.