Hi, to disable and re-enable interrupts in a safe way, I wrote the following class:
class DisableIntsShortly { public: __forceinline DisableIntsShortly(){ __disable_irq(); } __forceinline ~DisableIntsShortly() {__enable_irq(); } };
Thus then I should be able to protect my code with non-atomic access to interrupt variables like this:
{ DisableIntsShortly DI(); ... do some things where interrupt needs to be disabled. }
Unfortunately this does not work - the DI is not used inside this block, therefore the optimizer seems to think that it is useless and just kills it.
To come around this, I tried it like this:
class DisableIntsShortly { public: __forceinline DisableIntsShortly( int i){ __disable_irq(); i=i; } __forceinline ~DisableIntsShortly() {__enable_irq(); } };
Then it works if I write this (at least in optimization level 1):
{ DisableIntsShortly DI( 0); ... do some things where interrupt needs to be disabled. }
Just one severe problem: If I write "DisableIntsShortly DI();" (omit the 0), then NO ERROR appears (and again the optimizer decides to just kill it - without any warning or error - could some people at Keil please solve this? Here definitely an error should appear.
(And further the optimizer should not remove class instances with custructor and/or destructor functions).
There are always issues with compilers doing global optimization.
What happens if you add a global, volatile, variable and have your constructor do var++ to force a volatile memory access? The advantage with that is that you would also be able to trace the number of critical sections your program visits.
The opimize-killing is not my main problem. (I solved it with the "i=i;" in the second example of the class).
My main problem is, that for the second class the C++ compiler accepts the statement
DisableIntsShortly DI();
He gives neither a warning nor an error for this command - but this should CLEARLY produce an error (as this class then has no empty constructor - it requires a variable i to be given for the constructor, otherwise the constructor function cannot be called in a good way).
The compiler is not wrong and not optimising anything away. This:
does not create an object; it declares a function that takes no arguments and returns an object.
Write it without the () to create an object.
See also www.parashift.com/.../empty-parens-in-object-decl.html
Ups - what a great idea - I really did not think about this.
I just tried in Visual C++ - you are right, Visual C++ also accepts this. But Visual C++ gives a very nice warning in such a case:
"warning C4930: 'DisableIntsShortly DI(void)': Function with prototype was not invoked (was a variable declaration intended?)"
I feel much more confident in my code if Keil C++ could also give such a warning in such a case... .