Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I "tell" to C compiler that the code shouldn't be optimized out?

Sometimes I need some code to be executed by the CPU exactly as I put it in the source. But any C compiler has it's optimization algorithms so I can expect some tricks. For example:

unsigned char  flag=0;

interrupt ADC_ISR(){
  ADC_result = ADCH;
  flag = 1;
}

void main(){
  while(!flag);
  echo ADC_result;
}

Some compilers will definitely make while(!flag); loop infinitive as it will suppose flag equals to false (!flag is therefore always true).

Sometimes I can use volatile keyword. And sometimes it can help. But actually in my case (AVR GCC) volatile keyword forces compiler to locate the variable into SRAM instead of registers (which is bad for some reasons). Moreover many articles in the Internet suggesting to use volatile keyword with a big care as the result can become unstable (depending on a compiler, its optimization settings, platform and so on).

So I would definitely prefer to somehow point out the source code instruction and tell to the compiler that this code should be compiled exactly as it is. Like this: volatile while(!flag);

Is there any standard C instruction to do this?

like image 259
Vlada Katlinskaya Avatar asked Aug 22 '16 11:08

Vlada Katlinskaya


People also ask

How do I disable compiler optimization?

Use the command-line option -O0 (-[capital o][zero]) to disable optimization, and -S to get assembly file. Look here to see more gcc command-line options.

How do compilers optimize code?

Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.

Which modifier will prevent a compiler from optimizing access to an item?

Use the volatile keyword when declaring variables that the compiler must not optimize. If you do not use the volatile keyword where it is needed, then the compiler might optimize accesses to the variable and generate unintended code or remove intended functionality.


2 Answers

The only standard C way is volatile. If that doesn't happen to do exactly what you want, you'll need to use something specific for your platform.

like image 178
David Schwartz Avatar answered Nov 05 '22 08:11

David Schwartz


You should indeed use volatile as answered by David Schwartz. See also this chapter of GCC documentation.

If you use a recent GCC compiler, you could disable optimizations in a single function by using appropriate function specific options pragmas (or some optimize function attribute), for instance

#pragma GCC optimize ("-O0");

before your main. I'm not sure it is a good idea.

Perhaps you want extended asm statements with the volatile keyword.

like image 39
Basile Starynkevitch Avatar answered Nov 05 '22 08:11

Basile Starynkevitch