How can I tell the β€œcompiler” that the code should not be optimized?

Sometimes I need some code that will be executed by the processor in the same way as I put it in the source code. But any C compiler has 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 the while(!flag); infinitive while(!flag); since it is suppose flag is false ( !flag therefore always true).

Sometimes I can use the volatile keyword. And sometimes it can help. But actually in my case (AVR GCC) the volatile keyword causes the compiler to find the variable in SRAM instead of registers (which is bad for some reason). In addition, many articles on the Internet suggest using the volatile keyword with great care, as the result may become unstable (depending on the compiler, its optimization parameters, platform, etc.).

Therefore, I would definitely prefer to somehow indicate the instruction on the source code and tell the compiler that this code should be compiled exactly as it is. For example: volatile while(!flag);

Is there any standard C instruction for this?

+7
c compiler-optimization gcc
source share
3 answers

You really have to use volatile as David Schwartz answered . See also this chapter of the GCC documentation.

If you use the recent GCC compiler , you can turn off optimization in a single function using the corresponding functions of specific pragmas parameters (or some optimize attribute functions), for example

 #pragma GCC optimize ("-O0"); 

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

You might want extended asm instructions with the volatile keyword .

+3
source share

C's only standard way is volatile . If this is not the way you need it, you need to use something specific for your platform.

+8
source share

You have several options:

  • Compile without optimizations. Unlike some compilers, GCC is not optimized by default, so if you don’t tell it about optimization, you should get generated code that is very similar to your source C. Of course, you can optimize some C files and not others using simple make rules.

  • Derive the compiler from the equation and write the corresponding functions in the assembly. Then you can get the exactly generated code that you want.

  • Use volatile, which prevents the compiler from making any assumptions about a particular variable, so for any use of a variable in C, the compiler is forced to generate LOAD or STORE, even if this is not necessary.

+1
source share

All Articles