DEV Community

Cover image for C++ Optimized Compilation Ways
Prathamesh Dhadbale
Prathamesh Dhadbale

Posted on

C++ Optimized Compilation Ways

The very common way we know to compile a C++ program is by running the following command:

g++ filename.cpp -o filename

Talking in terms of stages of optimized compilation, this method is the basic one — we can say stage 0, also written as:

g++ -O0 filename.cpp -o filename

There are a few more, from zero to three. Let's talk about these ways of compilation.

1] -O0 : No Optimization (Default)

  • Fast compile time.
  • Every variable gets a real stack slot; nothing gets reordered or removed.

2] -O1 : Basic Optimization

  • Some dead code elimination.
  • Simple register allocation.

3] -O2 : 'Standard' Optimization

  • Register allocation.
  • Dead code elimination.
  • Inlining small functions.
  • Loop unrolling and vectorization.
  • Constant folding/propagation.
  • Does not enable optimizations that trade accuracy/safety for speed.

4] -O3 : More Aggressive than -O2

  • Sometimes faster, sometimes not.
  • Can hurt cache performance.

Other than this, there is also a space-optimization option.

5] -Os : Optimization for Size Instead of Speed

The command to use these optimizations is as follows:

g++ -O2 filename.cpp -o filename

Remember, in -O2 the "O" is a capital letter, not a zero — the same applies to the other optimization levels.

If you don't know what's going on, or you just wish to compile C++ files the way developers do, use the following standard command:

g++ -O2 filename.cpp -o filename

Top comments (0)