GCC Optimization Flags Explained: -O2, -O3, -march and What They Mean for a Port

What each gcc optimization flag does (-O2, -O3, -march, -flto, -ffast-math), what flag tuning gains, and why the baseline must be tuned before a port.

GCC Optimization Flags Explained: -O2, -O3, -march and What They Mean for a Port
Written by TechnoLynx Published on 11 Jul 2026

A GCC optimization flag tells the compiler which transformations it may apply and which instructions it may use. For a C or C++ workload that someone wants to port, a fair baseline build looks like this: -O2 as the default, -O3 only where you have measured it to be faster, -march or -mtune set for the CPU you actually deploy on, -flto tried and kept if it pays for itself, and -ffast-math treated as a decision about numerical correctness, not a free speed-up. Until that build exists, a speedup estimate for a GPU or SIMD rewrite is partly measuring missing compiler work rather than the new hardware.

Published benchmark studies on GCC 3.3.3 and 4.x report average gains from further flag tuning and link-time optimisation of under 1% to about 6%. Those flags also carry costs in build time, portability or floating-point behaviour, and the sections below cover them.

How Does a GCC Optimization Flag Work, and What Does It Mean in Practice?

The -O levels are bundles. Each level switches on a set of individual -f optimisation passes, and the GCC documentation describes the trade: more optimisation buys performance or code size at the cost of compilation time and possibly debuggability. The exact set enabled at each level depends on the target and how GCC was configured, and gcc -Q --help=optimizers prints what is actually on for your compiler.

Inlining shows the mechanism well. GCC inlines at every optimisation level, but at -O1 only functions called once are inlined, at -O2 that constraint is relaxed, and by default the inliner only sees one source file at a time unless -flto makes it whole-program. Value range propagation, enabled at -O2 and higher, propagates ranges of values so the optimiser can delete array bounds checks and null pointer checks it can prove redundant.

A second, separate set of flags controls which instructions are legal at all. -march picks the instruction set the compiler may emit, and -mtune picks the processor the code is scheduled for. Keep these two sets apart when reading a build line. The -O level decides how hard the compiler works, the target flags decide what it is allowed to produce, and a slow binary can come from either one.

What Is the Practical Difference Between -O0, -O1, -O2, -O3 and -Os?

Level What GCC does Typical use
-O0 No optimisation; the default; fastest compilation and easiest debugging Debugging only; never a performance baseline
-O1 (or -O) Moderate optimisation without significantly degrading compile time; some variables disappear from the debugger Quick builds that still need to run reasonably
-Og A blend of optimisation, fast compilation and debugging experience, recommended for the edit-compile-debug cycle Day-to-day development
-O2 Nearly all supported optimisations that do not involve a space-speed trade-off The baseline this article recommends
-O3 Everything in -O2 plus loop interchange, loop distribution, unswitching, predictive commoning, partial PRE, IPA-CP cloning and the dynamic vectoriser cost model, among others Loop-heavy numeric code, kept only when measured faster
-Os -O2 minus optimisations that often grow code (such as function and loop alignment), plus further optimisations designed to reduce code size Size-constrained targets
-Oz Aggressive size optimisation, which may increase the number of instructions executed Very tight size budgets

-O2 already performs nearly all supported optimisations that do not trade space for speed. With GCC, -O0 means almost no optimisation, and the GNAT User’s Guide calls using it in production very unusual if execution time matters at all.

-O3 is not a free upgrade over -O2. The same guide says -O3 should not be automatically preferred over -O2, because it often produces larger executables that may run more slowly. A comparison of distribution packages built at -O2 and -O3 found regressions and size growth alongside improvements: the flac library grew by 33%, vorbis by 40% and opus by over 50%. In the same comparison, zstd at -O3 ranged from very little change through a small improvement to a sizable regression, depending on the x86-64 level it was built for.

The gap between -O2 and -O3 also depends on the GCC version. GCC 12 enabled the auto-vectoriser at -O2 with its “very cheap” cost model, which vectorises only when it can see the scalar iteration count is a multiple of four, while -O3 keeps the more thorough “dynamic” cost model. An -O2 versus -O3 comparison on GCC 11 and the same comparison on GCC 12 are therefore measuring different things.

What Do -march=native, -mtune and -flto Do, and When Are They Safe to Use?

-march Versus -mtune

-march=native enables every instruction subset the build machine supports, so the GCC documentation warns that the result might not run on different machines. -mtune changes scheduling and everything else except the ABI and the instruction set, so code tuned with -mtune=pentium4 for an i686 configuration still runs on any i686 machine. GCC has no -march=generic option, because no instruction set applies to every processor, whereas -mtune=generic targets the most common processors when that version of GCC was released, which means its behaviour changes when you upgrade GCC.

-march=native is safe when the build machine and the deployment machine are the same model, or the fleet is homogeneous and that will not change. For anything shipped to unknown hardware, the x86-64 microarchitecture levels offer defined instruction-set targets. AMD, Intel, Red Hat and SUSE defined them in summer 2020: x86-64-v2 adds vector instructions up to SSE4.2 and SSSE3 plus POPCNT and CMPXCHG16B, x86-64-v3 adds up to AVX2 plus MOVBE and further bit-manipulation instructions, and x86-64-v4 adds some AVX-512 variants. Red Hat chose x86-64-v2 as the baseline for RHEL 9, because programs that use newer instructions might not run on older CPUs. Raising the level does not guarantee a gain. The 2023 package comparison measured small but consistent gains from x86-64-v2 with three marked regressions, and for flac encoding -O3 virtually removed the benefit that x86-64-v3 had shown.

If one binary must use AVX2 where it exists and still run where it does not, GCC’s documentation states that applications doing run-time CPU detection must compile separate files for each supported architecture with the appropriate flags. Cross-compiling for a fixed device is a different case, and our breakdown of GCC compiler flags for edge inference covers it.

-flto

-flto makes GCC write its GIMPLE intermediate representation into the object files, then read all the function bodies back at link time as if they were one translation unit. The inliner can then inline functions from one object file into another. Without LTO, interprocedural optimisation at -O2 can only happen within an object file, and non-static functions can never be eliminated.

Two rules determine whether -flto does anything useful. The GCC documentation recommends passing -flto and the same optimisation options at compile time and at the final link. Passing an -O level only at link time is generally ineffective, for two reasons: compiling without optimisation suppresses the passes that gather the information link-time optimisation needs, and some early optimisations can only run at compile time. If no -O is given at link time, GCC uses the highest level used to compile the object files. The practical consequence is that a CMake or Makefile change that adds -flto only to the linker flags misses the compile-time step the documentation requires.

The measured costs and gains vary widely. A 2010 study of GCC’s then-new LTO found runtime improvements under 1% for both GCC itself and Firefox, and expected overall build time to at least double. A 2014 thesis on optimising large applications measured another 4-5% on SPEC benchmarks from LTO at the same optimisation level, with binaries 15-20% smaller, and about 50% on xalancbmk alone. The same thesis found Linux kernel compilation took four times longer with LTO on its PC configuration and reported memory peaks of 15 GB for a parallel GCC 4.8.0 build before a fix brought usage below 6 GB. LTO bytecode is also tied to one compiler release: the files are strictly versioned, so objects built with one GCC version do not work with an older or newer one. -flto is safe to use when the whole toolchain runs on a single pinned GCC version, the linker supports plugins (which slim LTO objects require), and the CI pipeline can absorb the build time.

What Are the Correctness and Portability Risks of Aggressive Optimization Flags Like -ffast-math?

-ffast-math enables -ffinite-math-only, -fno-signed-zeros, -fno-trapping-math, -fassociative-math, -fno-math-errno, -freciprocal-math, -funsafe-math-optimizations and -fcx-limited-range. The GCC documentation says no -O level turns these on except -Ofast, because they can produce incorrect output for programs that depend on exact IEEE or ISO rules. -Ofast sounds like a plain “go fast” setting, and it silently enables -ffast-math. A 2022 investigation also reported that -fno-fast-math did not actually disable fast math when combined with -Ofast.

The hazards are specific:

  • No NaNs or infinities. -ffinite-math-only lets the compiler assume no argument or result is NaN or ±Inf, so code that checks for them may have those checks optimised away.
  • Reassociation. -fassociative-math allows the compiler to change the order of evaluation in a sequence of floating-point operations, which changes results. Compensated algorithms such as Kahan summation depend strictly on that order. The Verificarlo authors showed that -O3 -ffast-math removes the compensation term from Kahan summation entirely. As a result, the -O3 -ffast-math version’s error grew with input size while the -O0 compensated version’s error stayed constant.
  • Approximate reciprocals. For single-precision arguments, with -funsafe-math-optimizations, -ffinite-math-only and -fno-trapping-math together, GCC can replace division and square root with reciprocal sequences whose precision can drop by up to 2 ulp.
  • Process-wide FTZ/DAZ. When -ffast-math is used at link time, GCC links in a constructor that sets the flush-to-zero and denormals-are-zero flags whenever the library is loaded, so even a shared library changes floating-point behaviour for the whole process. Some numerical algorithms fail to converge when subnormals are treated as zero.

The safer route is to enable the sub-flags you have reasoned about one at a time, rather than the umbrella flag. When fast-math causes trouble, Simon Byrne’s note recommends -fno-finite-math-only as the first thing to try.

The optimisation level alone has changed floating-point results, without fast-math. A paper on the pitfalls of verifying floating-point computations showed one program printing infinity with no optimisation, 1E308 at -O and infinity again at -O3, depending on spilling, register use and inlining. The paper singles out the x87 unit for caution, while x86-64 uses SSE for floating point by default. -ffp-contract=fast is already the default for C++ and GNU C, so the compiler may fuse a multiply and an add into one FMA instruction. Because a fused multiply-add is not equivalent to a separate multiply and add, a correctness check against a reference build belongs in every flag change.

How Should You Think About a GCC Optimization Flag in Practice?

Treat each flag beyond the -O level as a hypothesis about one workload on one CPU, not as a setting that is good in general. Compiler optimisations interact in unpredictable ways, and researchers at Purdue argued that this is why finding the best combination for a program requires a search. Their own data shows the dependency: disabling strict aliasing improved the art benchmark by about 60% on a Pentium IV, where it caused heavy register spilling, but did not hurt performance on a SPARC machine that has more registers.

That suggests three groups of flags. The first is the default you set without a measurement (-O2). The second is choices you keep only with a measurement in hand (-O3, -march or an x86-64 level, -flto, profile feedback). The third is flags that change program semantics and need a correctness check as well as a timing (-ffast-math, -Ofast). Writing the group next to each flag in a build file makes the reasoning visible to the next engineer who reads it. For the AI-specific side of this, we cover separately which GCC compiler flags change AI workload performance when porting.

Why Can Building at -O0 Make a Porting Decision Look Artificially Favourable?

A speedup is a ratio, and an unoptimised baseline makes the numerator larger. -O0 is GCC’s default and means almost no optimisation, and the GNAT User’s Guide also notes that many other compilers do substantial optimisation even when “no optimisation” is requested. Comparing a GCC -O0 build against anything else therefore measures GCC’s choice to do nothing as much as the other side’s merits.

The same conclusion appears for CPU-versus-GPU performance claims in a retrospective on the GPU vs. CPU myth. Any claimed performance should be sanity-checked against the architecture’s own performance or roofline model, which by itself rules out unoptimised baselines. They also hold that two architectures should not be compared unless each gets its own best algorithm. The same fairness applies on the port side, so the GPU build deserves the same care, from tuning nvcc, Clang and SYCL builds to its kernels.

If the compile command carries no -O flag, GCC stays at its default, -O0. Our article on how CMake compile flags shape inference builds covers where that setting lives. Before any speedup figure is trusted, check the actual compile command, not the build file’s intentions.

How Much Speedup Can Flag Tuning Alone Deliver Before You Consider a Port?

The gain from -O0 to -O2 has no single number, because it depends on the application and the hardware.

  • An orchestration study at Purdue tuned all 38 options of GCC 3.3.3’s -O3, and its best algorithm improved performance by an average of 6.01% over -O3, with tuning averaging hours per benchmark on a Pentium IV.
  • The large-applications thesis measured about 4% on SPEC, another 4-5% from LTO at the same optimisation level, and found LTO combined with PGO the fastest configuration.
  • The 2010 GCC LTO study measured under 1% runtime improvement on GCC and Firefox.
  • Outliers exist: about 60% on art from disabling strict aliasing on one CPU, and about 50% on xalancbmk from LTO.

These numbers come from GCC versions such as 3.3.3 and 4.x on benchmark suites, not from your workload. Treat them as an order of magnitude, not a forecast. They still support a working rule. If a port promises a large multiple over a properly built native binary, the averages above, from under 1% to about 6%, are far smaller. If the promised gain is the same order as these figures, tuning, LTO and profile feedback may capture enough of it to defer the rewrite. The Purdue authors also point out a ceiling: GCC’s options at the time did not include dependence-based transformations such as loop tiling, which limited tuning on floating-point benchmarks. Code that needs that kind of restructuring is where algorithmic or hardware changes start to earn their cost.

Where Do Compiler Flags Fit in a Performance and Porting Assessment Baseline?

When TechnoLynx runs a performance and porting assessment, the flag-tuned native build is the baseline that the assessment’s speedup and ROI estimates are measured against. The sequence we would follow:

  1. Record what the current build actually does: the real compile and link commands, the GCC version, and gcc -Q --help=optimizers for the level in use.
  2. Rebuild at -O2 with -march or -mtune matching the deployment CPU, or an x86-64 level if the fleet is mixed.
  3. Try -O3 and keep it only if it measures faster on the real workload.
  4. Try -flto with the -O level passed at both compile and link time, and record the build-time cost.
  5. Optionally add profile feedback, which needs a two-phase build.
  6. Compare numerical outputs against a reference build within an agreed tolerance before keeping any flag.
  7. Freeze that configuration as the baseline, then compare the port against it.

Our article on what a performance and porting assessment tells you before you commit covers the full scope, and the engagement itself is listed under our engineering services.

When the Tuned Baseline Changes the Verdict

The most useful result of the sequence above is sometimes a smaller number. A projected gain that looked convincing against an -O0 or untuned build can shrink to the point where the rewrite stops paying for its engineering cost, and that is a legitimate outcome of the assessment, not a failure of it. When the gain holds up, the next question is which runtime to port to, and the framework for when porting Python inference to C++ or WASM earns its engineering cost depends on a correctly flag-tuned native build before any target runtime is compared.

FAQ

How Do You Disable Compiler Optimization in GCC?

Pass -O0, or no -O option at all, since -O0 is GCC’s default and produces unoptimised code with the fastest compilation and easiest debugging. For the edit-compile-debug cycle, the GCC documentation recommends -Og.

What Is the GCC Program on My PC?

GCC is the GNU Compiler Collection, an open-source compiler established in 1987 that compiles C, C++, Fortran and other languages.