Jim Blum
Jim Blum

Reputation: 2646

Are programs that are compiled gcc optimised by default?

While at University I learned that compiler optimises our code, in order for the executable to be faster. For example when a variable is not used after a point, it will not be calculated.

So, as far as I understand, that means that if I have a program that calls a sorting algorithm, if the results of the algorithm are printed then the algorithm will run. However, if nothing is printed(or used anywhere else), then there is no reason for the program to even make that call.

So, my question is:

Does these things(optimisation) happen by default when compiling with gcc? Or only when the code is compiled with O1, O2, O3 flags?

Upvotes: 1

Views: 97

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476970

When you meet a new program for the first time, it is helpful to type man followed by the program name. When I did it for gcc, it showed me this:

Most optimizations are only enabled if an -O level is set on the command line. Otherwise they are disabled, even if individual optimization flags are specified.

...

-O0 Reduce compilation time and make debugging produce the expected results. This is the default.

To summarize, with -O0, all code that is in the execution path that is taken will actually execute. (Program text that can never be in any execution path, such as if (false) { /* ... */ }, may not generate any machine code, but that is unobservable.) The executed code will feel "as expected", i.e. it'll do what you wrote. That's the goal, at least.

Upvotes: 4

Related Questions