Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn off all optimizations in GCC

How to turn off all optimizations in GCC? Using -O0 does not work since it still optimizes out the statements that have no effects, or any code that is after an infinite loop without any break statements.

like image 696
user2124324 Avatar asked Nov 27 '13 16:11

user2124324


People also ask

How do I disable GCC optimizations?

The gcc option -O enables different levels of optimization. Use -O0 to disable them and use -S to output assembly.

Is GCC optimized?

GCC has a range of optimization levels, plus individual options to enable or disable particular optimizations. The overall compiler optimization level is controlled by the command line option -On, where n is the required optimization level, as follows: -O0 . (default).

What optimization does GCC do?

The compiler optimizes to reduce the size of the binary instead of execution speed. If you do not specify an optimization option, gcc attempts to reduce the compilation time and to make debugging always yield the result expected from reading the source code.

How many optimization levels are there in GCC?

GCC has since added -Og to bring the total to 8. From the man page: -O0 (do no optimization, the default if no optimization level is specified) -O1 (optimize minimally)


2 Answers

There is no way to make gcc not ignore unreachable code and statments that have no effect.

What you can do is make code that is unreachable appear to be reachable by using volatile variables.

volatile bool always_true = true;

if( always_true  )
{
     //infinite loop
     //return something
}

//Useless code

in the above example, gcc won't optomize out useless code because it cannot know it is infact useless

int a = 5;
int b = 5;
volatile int c = 9;

c += 37;
return a + b;

In this example, integer c won't be optimized out because gcc does can't know it is dead weight code.

like image 107
8bitwide Avatar answered Sep 20 '22 15:09

8bitwide


You have to make your code nearly impossible to be optimized by the compiler. For example:

  • use volatile keyword on variables that you wish not to be optimized
  • make sure the code has effect, for example: not just only changing the variable value but also print the value or store it to another variable or do arithmetic to the variable and store it in another variable
  • reference/change the variable in other function to make sure the compiler cannot judge it is not used in compile time
like image 34
dragon135 Avatar answered Sep 18 '22 15:09

dragon135