When has a variable to be declared volatile?
When it might be modified asynchronously by something outside of the
compiler's control, such as some hardware or another process (e.g.
shared memory). Also, atomic variables (using platform specific atomic
functions) should generally be volatile, at least on Win32, but you
may need memory barriers in addition to ensure that a read value is
the latest and a written value propogates to other processors on a
multiprocessor system.
I have a program wich sets the variable through an
interrupt. But its read only from within the same program.
If you set the value from an ISR and then read it from elsewhere in
the code, then usually you should make the variable volatile, but your
platform documentation should make this clear.
What if it would be multi-threaded?
In general, volatile is neither necessary or sufficient for
thread-safety. You need locking primitives (mutexes/critical sections)
to safely share resources, or atomic primitives for single variables.
All this is platform dependent though (although a lot of platforms
have standardised on POSIX).
Tom