0

I am new in this field. Previously i was doing microcontroller programming. where I used in volatile variable to avoid compiler optimization. But I never saw such volatile declaration before variable declaration.Does it mean compilation is done without any optimization in arago build. Here I have two doubts.

  1. How can I enable different types of optimization during compilation like speed and space optimization in angstrom build?
  2. If it already optimization compilation, why do not we need volatile declaration?
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Embedded Programmer
  • 519
  • 4
  • 8
  • 22

1 Answers1

0

Optimization is typically controlled via compiler settings - such as the compiler command line. It is not controlled in code.

However for doing optimization the compiler assumes that variables behave like "normal variables" while the code is not interrupted.

This may lead to the following error: Some example code:

int a;

void myFunc(void)
{
    a=1;
    /* Wait until the interrupt sets a back to 0 */
    while(a==1);
}

void interruptHandler(void)
{
    /* Some hardware interrupt */
    if(a==1) doSomeAction();
    a=0;
}

The compiler assumes that there are no interrupts. Therefore it would see that

  • "a" is set to 1 and never changed before the "while" loop
  • The while loop is an endless loop because "a" does not change whithin this loop
  • "a" is never read before this endless loop

Therefore the optimizing compiler may change the code internally like this:

void myFunc(void)
{
    while(1);
}

Leaving the "volatile" away may work but may not work.

If you do not have hardware interrupts (and no parallel threads, multi-core CPUs etc.) "volatile" makes the code only slower and has no benefit because it is not required.

Martin Rosenau
  • 17,897
  • 3
  • 19
  • 38
  • Another reason not to use globals. Use setter/getter to set/query a variable's value. – ott-- Sep 10 '13 at 20:52
  • what is setter and getter function? are these functions exist in linux C? – Embedded Programmer Sep 12 '13 at 09:49
  • @ott: Using setters or getters would not eliminate the problem if the compiler has a very good optimization. In this case it would see that the setter function sets a variable that is never read and so on... – Martin Rosenau Sep 13 '13 at 14:05
  • Of course you need to call `if (getA() == 1)` at least once, or the compiler would be right with optimization. – ott-- Sep 13 '13 at 16:18
  • @EmbeddedProgrammer This is not part of C, you have to make them yourself. You have them in OO programming languages. – ott-- Sep 13 '13 at 16:20