Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to tell GCC not to optimise a particular piece of code?

Tags:

I am working on a project that relies on compiler optimisations but I need some code not to be optimised by GCC. Is this possible?

like image 269
limp Avatar asked Apr 07 '11 11:04

limp


People also ask

How do I stop GCC 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. Show activity on this post.

Does GCC optimize code?

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).

How do I know if GCC is not optimized?

Compiler specific pragma gcc provides pragma GCC as a way to control temporarily the compiler behavior. By using pragma GCC optimize("O0") , the optimization level can be set to zero, which means absolutely no optimize for gcc.


2 Answers

GCC 4.4 has an attribute for that:

int foo(int i) __attribute__((optimize("-O3"))); 

It is documented at: https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gcc/Function-Attributes.html#index-g_t_0040code_007boptimize_007d-function-attribute-3195

like image 185
sehe Avatar answered Sep 16 '22 18:09

sehe


GCC has since 4.4. the #pragma GCC optimize ("whatever"). I would also recommend to wrap the particular code, that is annotated with this pragma with #pragma GCC push_options and #pragma GCC pop_options. The first will save the options as they were before your change, the later will restore them afterwards and the rest of the code will compile with the global options.

For details on the whatever string, you should look into the gcc doc, here the most important part of it: Arguments can either be numbers or strings. Numbers are assumed to be an optimization level. Strings that begin with O are assumed to be an optimization option, while other options are assumed to be used with a -f prefix..

That means if you dont want any optimizations on your particular code your whatever should just be "0".

like image 20
flolo Avatar answered Sep 20 '22 18:09

flolo