How can I compile a C program without undergoing any optimizations using gcc/g++?
-
On the off chance that you're not looking for a compiler switch you might be looking to declare your variable(s) `volatile`. – user786653 Nov 28 '11 at 17:21
-
Why do you want them turned off? Do you have some reason to believe optimizations are 1) enabled, and 2) causing you problems? It's rare for an optimization to cause problems with correctly written code. However, it's often useful to use -O0 in combination with -ggdb for debugging. – Brian McFarland Nov 28 '11 at 17:22
5 Answers
Using -O0 is the closest I know of, however, unlike other replies, this does not mean zero optimizations. You can count the number of enabled optimizations for the different gcc optimization levels like this (this is gcc 4.8.2):
$ gcc -Q -O0 --help=optimizers | grep enabled | wc -l
52
$ gcc -Q -O1 --help=optimizers | grep enabled | wc -l
80
$ gcc -Q -O2 --help=optimizers | grep enabled | wc -l
110
$ gcc -Q -O3 --help=optimizers | grep enabled | wc -l
119
So at -O0, there are 52 optimizations enabled. I suppose one could disable them one-by-one, but I've never seen that done.
Note that the gcc man page says:
-O0 Reduce compilation time and make debugging produce the expected results. This is the default.
It's not promising zero optimizations.
I'm not a gcc developer, but I would guess they would say that the -O0 optimizations have become so standard that they can barely be called optimizations anymore, rather, "standards". If that's true, it's a little confusing, since gcc still has them in the optimizers list. I also don't know the history well enough: perhaps for a prior version -O0 really did mean zero optimizations...

- 965
- 8
- 10
-
Pretty useful comment, didn't knew that - I'm at my 5th year of CS studies and all of my teachers since the beginning told us that `-O0` meant no optimization. – Nino Filiu Sep 06 '18 at 15:26
-
Followup question https://stackoverflow.com/questions/33278757/disable-all-optimization-options-in-gcc. – ks1322 Dec 08 '22 at 13:55
gcc main.c
or
g++ main.cpp
by default it doesn't do any optimizations. Only when you specify -O1, -O2, -O3, etc...
does it do optimizations.
Or you can use the -O0
switch to make it explicit.

- 464,885
- 45
- 335
- 332
-
This seems not to be true. Check Grendan's answer: https://stackoverflow.com/a/23327860/130758. – devoured elysium Apr 25 '19 at 16:27
-
It definitely still does some optimizations, such as checking for basic dead code – Vendetta Jun 23 '22 at 21:09
You shouldn't get any optimizations unless you ask for them via the -O
flag. If you need to undo some defaults provided by your build system, -O0
will do that for you, as long as it's the last -O
flag in the command line.

- 219,201
- 40
- 422
- 469
-
Not quite. The gcc compiler does basic optimizations regardless of specified O level – Vendetta Jun 23 '22 at 21:09