Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile C program without any optimization

Tags:

c

gcc

How can I compile a C program without undergoing any optimizations using gcc/g++?

like image 916
Sarath Babu Avatar asked Nov 28 '11 17:11

Sarath Babu


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

like image 93
Brendan Gregg Avatar answered Nov 04 '22 06:11

Brendan Gregg


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.

like image 30
Mysticial Avatar answered Nov 04 '22 06:11

Mysticial