GCC Compiler Flags Explained: Optimization Flags That Shape Inference Builds

How CMake compile flags reach GCC and emcc for an inference build: -O levels, -march, LTO, fast-math risks, and how to audit what shipped.

GCC Compiler Flags Explained: Optimization Flags That Shape Inference Builds
Written by TechnoLynx Published on 11 Jul 2026

CMake compile flags reach GCC through several layers, passed in a fixed order. The global CMAKE_CXX_FLAGS string goes first on the command line, then the per-configuration flags chosen by CMAKE_BUILD_TYPE, then whatever add_compile_options() and target_compile_options() add. The pattern that holds up is this: let the build type own the -O level, attach -march and floating-point flags to specific targets, enable link-time optimisation through CMake’s IPO property instead of a raw -flto, and read compile_commands.json to confirm what was compiled. When the same project is configured with emcmake for WebAssembly, the compiler becomes emcc, which runs on Clang/LLVM.

If you want the short list of flags rather than the build-system mechanics, GCC flags that matter for inference and WASM builds is the quick-reference version.

How CMake Compile Flags Reach GCC, and Why Yours Get Overridden

CMAKE_<LANG>_FLAGS applies to every build type, and CMake initialises it from the environment: CMAKE_CXX_FLAGS from CXXFLAGS, CMAKE_C_FLAGS from CFLAGS. So a CXXFLAGS exported in a CI image or a developer’s shell profile ends up in the build without appearing in any CMakeLists.txt. The per-configuration variant, CMAKE_<LANG>_FLAGS_<CONFIG>, comes after it on the command line, and directory- and target-level options come after both.

That ordering matters because GCC honours the last -O option it sees. A -O2 passed through target_compile_options() lands last.

add_library(infer_core STATIC src/gemm.cpp src/attention.cpp src/softmax.cpp)

# Lands after CMAKE_CXX_FLAGS and CMAKE_CXX_FLAGS_RELEASE,
# so this -O2 beats the -O level from Release's flags for infer_core only.
target_compile_options(infer_core PRIVATE -O2)

The cleaner arrangement keeps -O out of both the global string and target options, changing it only by picking a build type or editing CMAKE_CXX_FLAGS_RELEASE in one place. Then a reviewer can answer “what optimisation level did this ship at?” from a single line.

Which -O Level Should an Inference Release Build Use?

GCC describes -O2 as performing nearly all supported optimisations that do not involve a space-speed trade-off. -O3 adds loop transformations on top, including -floop-interchange, -fpeel-loops, -funswitch-loops and -fvect-cost-model=dynamic. It also turns on function cloning for interprocedural constant propagation, which GCC warns can significantly increase code size. Optimisation also comes at the expense of compile time.

At the size end, -Os keeps the -O2 set minus the passes that often grow code, such as function and loop alignment. -Oz goes further and may execute more instructions if those instructions take fewer bytes to encode. -Og is GCC’s recommendation for the edit-compile-debug cycle.

An -O level does not enable the same passes on every target, either. Instruction scheduling to hide slow loads is conventionally on at -O2 and -O3, yet GCC disables it at all levels on x86 and enables it only at -O3 on AArch64. That is one reason to treat -O3 as a candidate to measure against -O2 on the deployment CPU, not a default to assume. For a bundle where download size and load time count, MinSizeRel deserves the same measured comparison. For a flag-by-flag walk through what each level switches on for ML code, see GCC optimisation switches for ML inference builds.

-march=native in a CMakeLists Bakes the Build Machine into the Binary

-march=cpu-type lets GCC emit instructions that may not run at all on other processors, while -mtune=cpu-type only tunes scheduling for that processor. -march=native detects the compiling machine and enables every instruction subset it supports, so the result might not run on a different machine. It also depends on what that GCC version recognises. In CMake the failure is quiet: the flag sits in a target option, the CI runner happens to be newer than the inference host, and the binary is built for hardware it will never be deployed on.

The distinction to keep is the one MaskRay (2022) draws between the execution domain and the optimisation domain. -march decides which instructions the code may use, and -mtune decides what it is optimised for without changing the ABI or the instruction set. Portable options follow from that:

  • A named ISA level. GCC’s micro-architecture-level cpu-type values select the corresponding level from the x86-64 psABI.
  • Generic tuning. -mtune=generic targets the most common processors when you do not know the user’s CPU, though its behaviour changes as GCC versions move.
  • Runtime dispatch. Applications that detect the CPU at run time must compile separate files for each supported architecture with the matching flags. GCC’s target_clones function attribute offers function multi-versioning on x86 instead.
set(INFER_MARCH "x86-64-v2" CACHE STRING "ISA level for infer_core (never 'native' for release)")
if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64")
  target_compile_options(infer_core PRIVATE -march=${INFER_MARCH} -mtune=generic)
endif()

Gating the value behind a cache variable means a developer can still build native locally, while the release pipeline pins a level that matches the fleet.

Probing a Flag with CheckCXXCompilerFlag Before Relying on It

CMake’s CheckCXXCompilerFlag module provides check_cxx_compiler_flag(), which test-compiles a small source with the flag and stores the result in a variable. Probing is better than assuming, because the same CMakeLists.txt may be configured with an old GCC, a current Clang, or emcc.

include(CheckCXXCompilerFlag)
check_cxx_compiler_flag("-march=x86-64-v3" HAVE_MARCH_V3)
check_cxx_compiler_flag("-msimd128" HAVE_WASM_SIMD)

A passing check proves only that the compiler accepts the flag. It does not prove that the deployment CPU supports the instructions the flag unlocks, and that gap is exactly where -march failures live.

Turning on -flto Through CMake Instead of a Raw Flag

Link-time optimisation lets the compiler optimise across translation units, enabling more aggressive inlining and dead-code elimination over the whole program. CMake exposes it as interprocedural optimisation: the INTERPROCEDURAL_OPTIMIZATION target property, or CMAKE_INTERPROCEDURAL_OPTIMIZATION for every target in scope. The CheckIPOSupported module is meant to run first. With a RESULT variable, check_ipo_supported() reports YES or NO; without one, it stops the configure with a fatal error if IPO is unsupported. An OUTPUT variable captures the reason. A per-configuration INTERPROCEDURAL_OPTIMIZATION_<CONFIG> property overrides the base property when it is set.

include(CheckIPOSupported)
check_ipo_supported(RESULT ipo_ok OUTPUT ipo_msg LANGUAGES CXX)
if(ipo_ok)
  set_property(TARGET infer_core PROPERTY INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE)
else()
  message(WARNING "LTO unavailable for infer_core: ${ipo_msg}")
endif()

GCC’s LTO also has requirements on the link step. The GCC manual says -flto and the optimisation options have to be given at compile time and again at the final link, ideally the same options for every participating file. Giving -O only at link time is generally ineffective, because unoptimised compilation skips the passes that gather what the link-time optimiser needs. Honza Hubička (2014) makes the same point from the Firefox build: failing to pass the optimisation flags to the final link probably produces a poorly optimised binary. Without linker-plugin support, GCC always builds fat LTO objects, builds take about twice as long, and optimisation across exported symbols suffers. Static libraries add one more trap: slim LTO objects need nm, ar and ranlib with plugin support.

Hubička’s 2014 Firefox measurements also show that LTO is not automatically a size win. At -Os GCC’s LTO cut code and data by about 5%, while at -O2 and -O3 the code grew through inlining. Semantic flags such as -ffp-contract and -fno-strict-aliasing are passed to the link stage and merged conservatively across conflicting translation units. In our judgement, LTO earns its place when the inference hot path crosses files through small functions the compiler cannot inline without seeing both sides; a single large kernel file gains little.

Can -Ofast or -ffast-math Change What My Model Outputs?

Yes, and not only in the code you compiled with them. -Ofast is the only -O level that turns on -ffast-math and -ffinite-math-only, because they can produce incorrect output for programs that depend on exact IEEE or ISO behaviour. As Krister Walfridsson (2021) lists them, -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 non-local part comes at link time. Linking with -ffast-math makes the CPU treat subnormal numbers as zero. The documented mechanism is that crtfastmath.o is linked in and adds a static constructor that sets the FTZ/DAZ bits in MXCSR, affecting every static and shared library in the program. GCC skips this startup code when building a shared library, and -mdaz-ftz or -mno-daz-ftz set the behaviour explicitly. Sergei Trofimovich’s write-up describes libsodium enabling -Ofast by default, breaking reverse dependencies that relied on denormals, and rolling the default back. Because library test suites are usually not run under -Ofast, such breakage may go unnoticed until real data is corrupted. In an inference process that also loads a BLAS, a tokenizer and a pre-processing library, that is the risk to weigh.

Inside your own code, two sub-flags deserve particular attention. Simon Byrne names -ffinite-math-only as the most frequent cause of fast-math bug reports and the first option to disable when results go wrong. Reassociation is the subtler one: compensated arithmetic such as Kahan summation depends on operation order, and the same technique is often used inside exponential and trigonometric functions, where reassociating can give catastrophically wrong answers.

How sensitive model outputs can be to operation order is documented even without any compiler flag. A 2025 arXiv study traced up to 9% accuracy variation in DeepSeek-R1-Distill-Qwen-7B under BF16 greedy decoding to floating-point non-associativity, triggered by changes in GPU count, type and batch size. That study measured runtime configuration, not compiler flags. What it shows is that small reorderings can flip tokens when the top logits are close, and -fassociative-math is a licence for the compiler to reorder.

The safe process Byrne describes is: build validation tests and benchmarks, enable fast-math, then selectively enable and disable individual sub-flags to see which ones help and which break, using the minimum number of options in the fewest places. In CMake terms, that means a dedicated kernel target or set_source_files_properties() on one file, never CMAKE_CXX_FLAGS. On Clang, -ffp-model is the umbrella: precise is the default and disables value-unsafe optimisations while allowing FMA contraction, and fast and aggressive enable the unsafe set.

Do GCC Flags Carry over When Emcmake Builds the Same Project for WASM?

Some carry over in name, but not always in meaning. For how the runtime itself executes code, see how Pyodide and WASM work; the build side starts with emcmake, which sets the CMake toolchain file so that emcc replaces gcc. The Emscripten toolchain file teaches CMake about the compiler, and its usage notes list the Debug, RelWithDebInfo, Release and MinSizeRel build types. Read what that toolchain file assigns to each configuration’s flags before assuming your Release string survives. emcc uses Clang/LLVM underneath and defines __clang__.

Optimisation levels look familiar but are not GCC’s. Emscripten says its -O1, -O2 and so on resemble gcc and clang but differ, because optimising WebAssembly involves extra kinds of optimisation. At link, Emscripten runs the Binaryen optimiser, generates and optimises JavaScript, and removes unused code across the Wasm and JS boundary. Emscripten recommends the same optimisation flags at compile and at link, though linking at -O0 or -O1 is a legitimate way to skip that work during iteration. In CMake that makes the link line as important to audit as the compile lines.

SIMD is the flag that matters most. -msimd128 enables WebAssembly SIMD and LLVM’s autovectorisers at -O2 and -O3, and -fno-vectorize -fno-slp-vectorize turn the autovectoriser back off. Existing SSE through AVX2 and FMA code compiles with -msimd128 plus an instruction-set flag, but most 256-bit AVX and AVX2 instructions are emulated by two 128-bit ones. ARM NEON code fares similarly: only the 128-bit “q” variants map cleanly, and the rest is scalarised. An x86 -march value describes x86 CPUs, so -march=native has nothing to buy back on a WebAssembly target. The FTZ/DAZ flags behind fast-math’s global side effect live in the x86 SSE MXCSR register, so do not assume they describe a WebAssembly build’s subnormal behaviour either.

The ceiling is real. The USENIX ATC 2019 study found WebAssembly 1.55× slower than native in Chrome and 1.45× slower in Firefox on average across SPEC CPU. The study ties extra loads to register availability and extra branches to safety checks; mapping inference across CPU, GPU and WASM covers where each part should run.

Flag Carry-over from Native GCC to Emscripten

Flag or mechanism What it controls Native GCC through CMake Under emcmake / emcc
-O2 / -O3 Optimisation passes Owned by CMAKE_BUILD_TYPE; last -O wins Similar names, different pass sets; Binaryen runs at link
-Os / -Oz Code size versus speed MinSizeRel or per-config flags Size focus, longer compile
-msse*, -mavx2, -mfma x86 vector ISA Enables those instructions in generated code Supported with -msimd128; most 256-bit ops emulated as two 128-bit
-flto Cross-file optimisation INTERPROCEDURAL_OPTIMIZATION after check_ipo_supported() Binaryen also optimises the whole program at link

Auditing the CMake Compile Flags That Actually Shipped

The tuned flag set only counts if it is the one in the artefact. Run this sequence for every release candidate:

  1. Configure with CMAKE_EXPORT_COMPILE_COMMANDS=ON, which writes compile_commands.json with the exact compiler call for every translation unit. Only Makefile and Ninja generators implement it; other generators ignore it.
  2. For each inference target, read the final -O, -march and any fast-math flags in those entries, remembering that the last -O on the line is the one GCC uses.
  3. Check the link command separately from the build log, because compile_commands.json records compile calls only, and LTO depends on the optimisation flags reaching the final link.
  4. Build release objects with GCC’s -frecord-gcc-switches, which records the compiler command line into the object file, so the shipped binary can be checked later without the build tree.
  5. Under emcmake, confirm the compiler in compile_commands.json is emcc and that -msimd128 appears where you expect vectorised kernels.

Does the Tuned Flag Set Clear the Latency and Footprint Target?

Profile before you optimise: whether a “best practice” flag helps depends on context, and that context comes from profiling the workload, not from reading blog posts. For a flag pass, that means a baseline build at -O2 on the deployment target, one flag class changed at a time (level, ISA, LTO, floating-point), and latency, binary size and load time recorded for each. Byrne’s order starts with validation tests and ends by validating numeric results, so a faster build that changed outputs is caught. For Emscripten builds, --profiling keeps enough information in an optimised build to profile it. Code-size and cold-start regressions from aggressive flags belong in the release-readiness decision for an AI feature, because they surface in the deployed bundle.

TechnoLynx runs this build-tuning step as part of its GPU performance engineering work, checking whether the chosen compiler flags clear the latency and footprint target on the real deployment target before a port is committed. When this pass feeds a decision to port, it is part of a wider question that a performance and porting assessment answers: how much compute the compiled build can actually recover before the migration is funded.

Change the fleet’s CPU generation, move from GCC to emcc, or ship to a browser instead of a server, and the flag set needs proving again.

FAQ

What Is the Purpose of the -g and -O Flags in GCC?

-g emits debug information and -O selects an optimisation level. They can be combined, but higher optimisation trades away some debuggability for performance.

What Is the -c Flag in GCC?

-c compiles or assembles source files into object files without linking. With LTO, the final link step that follows still needs the optimisation flags.