|
From: | David Brown |
Subject: | Re: [avr-gcc-list] A Question Of Optmization |
Date: | Wed, 16 Apr 2008 09:20:34 +0200 |
User-agent: | Thunderbird 2.0.0.12 (Windows/20080213) |
Ruud Vlaming wrote:
Yeah, I think it is not as strange as it might seem. If you say -O0 the compiler will do exactly what you asked him to do. And this is what you intended. But if you let the compiler optimize, it recognizes that your variable TimerTick is set to 10 and will never change. So it will just make sure the locationreserved for the variable is correctly filled, and then will loop forever.You must tell the compiler explicitly the variable TimerTick may be changed by a 'backdoor'.Tryvolatile TimerTick = 10; Ruud.
Your answer here (after the little correction in your second post) is of course correct - he's missing the "volatile". However, your explanation is not entirely accurate. I don't know if my rant here applies to you (Ruud), but it is hopefully informative to the OP (Karl) at least.
It's a very common misunderstanding to think that "-O0" tells the compiler to "do exactly what the program asks", and turning on optimisation tells the compiler it can do smart tricks with your code.
In fact, the compiler will *always* do *exactly* what your program code asks (baring bugs in the compiler, of course). Optimisation flags are really no more than hints - they will not affect the correctness of your program if you have written your code according to the language C and the way C compilers are required to implement that language. The flags let you fine-tune tradeoffs such as space and speed, or test or avoid experimental compiler features. But using "-O0" is asking the compiler to be intentionally crippled and simple-minded as a possible aid to finding out what's wrong in your program. You are not *telling* the compiler to restrict itself in this way, merely *asking* it - a compiler can correctly return tightly optimised code when given a "-O0" flag. You are not asking it to interpret your code in any other way, and the compiler is still free to remove any parts of your source code that it is sure will never run, or any variables that are never used. All you are doing is asking it not to try so hard to find such code.
So while problems on the lines of "it works with -O0, but not -Os or -O2" are almost always solved by putting "volatile" in the right place, it is important to remember that the source code with the missing volatile is wrong, even if it happens to work with -O0. It's not a case of "you need volatile to make the code work with optimisations" - it's a case of "you need volatile to make the code correct".
mvh., David
[Prev in Thread] | Current Thread | [Next in Thread] |