[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: [avr-gcc-list] Q: volatile member of structure?

From: stevech
Subject: RE: [avr-gcc-list] Q: volatile member of structure?
Date: Mon, 11 Apr 2005 00:27:56 -0700

Thanks much!

I changed the structure's typedef to have the member(s) volatile, as some
suggested. Better than peppering the forced fetch cast to pointer in many

-----Original Message-----
From: address@hidden
[mailto:address@hidden On Behalf Of
David Brown
Sent: Sunday, April 10, 2005 11:41 PM
To: address@hidden
Subject: Re: [avr-gcc-list] Q: volatile member of structure?

(sorry about the failed quoting - OE sometimes has problems getting quoting
right when people post in html)

When you write "while (x == (volatile unsigned char) t.m) ", you are asking
the compiler to read t.m, and then convert it to a volatile unsigned char.
Since t.m itself is not volatile, the compiler does not have to re-read it
for every loop.  Hence the correctly generated assembly code for the
incorrectly writen source code.

There are two ways to deal with this one.  Either make .m volatile (in the
struct definition, or by making all of t volatile), or use something like:
    while (x == *(volatile unsigned char*) &t.m)
i.e., make the read into a read of a volatile unsigned char at the same
address as t.m.  You might want to use a macro:
    #define VolByte(x) (*(volatile unsigned char *) (&(x)))
    while (x == VolByte(t.m))



----- Original Message -----
From: stevech
To: address@hidden
Sent: Monday, April 11, 2005 2:37 AM
Subject: [avr-gcc-list] Q: volatile member of structure?

Is this a minor bug?

Some_structure contains 8 bit member - I'll call it "m" here.
That structure has a typedef and an instance in global memory - I'll call it
"t" here.

So t.m refers to that byte.

Now since my interrupt routine and my non-interrupt code both access t.m, I
coded this, in my non-interrupt code:

x = t.m;
while (x == (volatile unsigned char) t.m)

But the resultant assembly code shows that t.m is not re-fetched from memory
in the while loop. The while loop just compares two registers in a two
instruction loop.  This is with the default optimization setting. If I turn
off optimization, t.m is indeed repeatedly fetched from memory.

So, shouldn't the cast force the compiler to treat t.m as a volatile? Did I
code the cast correctly?

A cure, I suppose, is to declare the typedef'd structure or its instance as

AVR-GCC-list mailing list

AVR-GCC-list mailing list

reply via email to

[Prev in Thread] Current Thread [Next in Thread]