Yahoo Groups archive

AVR-Chat

Index last updated: 2026-04-28 22:41 UTC

Message

Re: gcc compiler bad behaviour

2012-04-13 by Don Kinzer

--- In AVR-Chat@yahoogroups.com, STEVEN HOLDER <s.holder123@...> wrote:
> Generally if you do have variables that are global and can be
> changed outside the main routine then declare them as volatile
I don't think this statement describes the issue precisely enough.  Firstly, the phrase "can be changed outside the main routine" is too broad because it includes normally called routines.  Secondly, the mention of "the main routine" may lead one to believe that the issue only applies to variables accessed in main().

The volatile attribute must be used on any variable that may be modified by a means that cannot be anticipated by the compiler given the code that it can see.  Examples include:
- variables representing hardware registers
- variables in multi-port memory
- variables modified by an interrupt handler
- variables modified by another thread/task/process that may run at any time

You may safely omit the volatile attribute (or cast it away) in cases where you are guaranteed that the variable cannot change unexpectedly, e.g. the variable is modified by an interrupt handler but interrupts are disabled.

It should be further noted that use of the volatile attribute does *not* guarantee atomic access.  This is an important consideration when working with variables wider than the data path (for 8-bit AVRs, multi-byte variables) and also for read-modify-write operations.

Don Kinzer
ZBasic Microcontrollers
http://www.zbasic.net

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.