skip to content

GCC

GCC turns C and C++ into binaries through preprocess, compile, assemble and link stages, steered by flags. Interviewers ask what a flag does and why a build fails to link.

on this pageshow

explore

questions

26

What do GCC's -O0, -O1, -O2, -O3, -Os and -Og each trade off, and which level is the default?

level: juniorimportance: must knowfreq 72%

answer

  1. speed, size, debuggability, build time
  2. -O0 is the default
  3. -O2: no space-speed trade
  4. -O3 grows loops and code
  5. -Og for edit-compile-debug

basics

~20 s

-O0, the default, barely optimizes so builds are fast and debugging is exact. -O1 adds cheap optimizations, -O2 nearly all that do not trade size for speed, -O3 adds aggressive loop work, -Os favours size, and -Og keeps debugging usable.

solid answer

~50 s

With no `-O` option GCC uses **`-O0`**: it compiles quickly and keeps every statement independent, so a debugger shows exactly what the source says. `-O1` (or `-O`) enables optimizations that do not take much compile time. **`-O2`** performs nearly all supported optimizations that do not involve a space-speed tradeoff, and in GCC 16 that includes loop and SLP vectorization with the `very-cheap` cost model; it is the usual release level. **`-O3`** adds loop unswitching, peeling, distribution, predictive commoning and the `dynamic` vectorizer cost model, which can make code faster but larger, and is not guaranteed to win. **`-Os`** is `-O2` without the alignment and other code-growing options, tuned for size. **`-Og`** enables most of `-O1` minus passes that interfere with debugging. The last `-O` on the command line wins, and `-Q --help=optimizers` lists what a level really enables.

go deeper

for a junior

Say that -O0 is the default and good for debugging, -O2 is the usual release level, and -Os optimizes for size.

for a middle

Explain what separates -O2 from -O3, why -O0 ignores individual optimization flags, and why the last -O option wins.

for a senior

Choose levels per component from measurements, and recognise when -O3's code growth costs more than it saves.

for a principal

Own the build configurations' optimization defaults, and require a benchmark before any component departs from them.

## What an optimization level is An `-O` level is a bundle of individual `-f` flags plus pass settings. GCC's manual states the baseline: without any optimization option, the compiler's goal is to reduce the cost of compilation and to make debugging produce the expected results. Each higher level spends more compile time, and sometimes code size, to make the program faster. | Level | Goal | What it adds | Typical use | |---|---|---|---| | `-O0` | fast builds, exact debugging | almost nothing; **the default** | first debug builds | | `-O1` / `-O` | cheap wins | constant propagation, dead code elimination, `-fomit-frame-pointer` and others that are inexpensive to compute | large machine-generated code | | `-O2` | speed without size trade-offs | inlining of small and suitable functions, scheduling, `-fstrict-aliasing`, vectorization with the `very-cheap` cost model | release builds | | `-O3` | maximum speed attempts | `-funswitch-loops`, `-fpeel-loops`, `-ftree-loop-distribution`, `-fpredictive-commoning`, the `dynamic` vectorizer cost model | measured hot code | | `-Os` | small code | `-O2` minus alignment and other code-growing options, tuned for size | firmware, caches, downloads | | `-Og` | debuggable but optimized | `-O1` minus the passes that hurt debugging | edit-compile-debug loop | GCC 16 also has `-Oz`, which optimizes for size more aggressively than `-Os`, even if more instructions run. ## -O0 really means off The manual is explicit: at `-O0` most optimization passes are completely disabled and **do not run even if you enable them on the command line**. Adding `-finline-functions` to an `-O0` build changes nothing, because the analyses those passes need are only enabled from `-O1`. If you want one optimization, start from a level and add or remove flags on top of it. ## -O2 versus -O3 `-O2` is the level most projects ship. Its definition, nearly all optimizations without a space-speed tradeoff, keeps code size stable. In GCC 16 the `-O2` list includes `-ftree-loop-vectorize` and `-ftree-slp-vectorize` with `-fvect-cost-model=very-cheap`, so simple loops are vectorized only when the vectorizer is sure it pays. `-O3` removes that restraint. Loop transformations duplicate code, the `dynamic` cost model vectorizes more loops behind runtime checks, and cloning specializes functions for constant arguments. The result is often faster for numeric kernels and sometimes **slower** for branchy code, because bigger code puts more pressure on the instruction cache. The professional answer is to measure: build the hot component at both levels and benchmark it. ## -Os and -Og - `-Os` keeps the `-O2` optimizations except those that often increase size, such as function and loop alignment, and makes size the tuning goal. It is common for embedded firmware and for code where instruction-cache misses dominate. - `-Og` is what the manual recommends for the standard **edit-compile-debug** cycle. It enables the `-O1` flags except those known to interfere with debugging, and it turns on variable tracking, so a debugger shows more variables correctly than at `-O0` in function prologues and epilogues while the code still runs much faster than `-O0`. ## Rules that surprise people 1. If several `-O` options appear, **the last one wins**. A build system that appends `-O2` after your `-O3` silently gives you `-O2`. 2. A different result at `-O2` than at `-O0` almost always means the program has **undefined behaviour** or depends on unspecified details, not that the optimizer is wrong. Floating point is the honest exception: GCC's default `-ffp-contract=fast` for C++ lets optimized code fuse a multiply and an add on targets with FMA, which can change the last bits, and `-Ofast` relaxes the rules much further. 3. The exact flag set depends on the target and on how GCC was configured. `g++ -Q -O2 --help=optimizers` prints what is enabled for your compiler. 4. Higher levels make some warnings appear, because the analyses behind them only run when optimizing. ## Choosing in practice - Debug configuration: `-Og -g` or `-O0 -g`. - Release configuration: `-O2 -g`, with debug information split off. - Hot numeric code: try `-O3`, and keep it only where measurements show a gain. - Size-bound targets: `-Os`, or `-Oz` when every byte counts.

  • Why might a program be slower at -O3 than at -O2?
    `-O3` duplicates code through loop unswitching, peeling and versioning, and vectorizes more loops behind runtime checks. If those paths are cold or the loops are short, the extra code costs instruction-cache space and branch overhead without paying back. Measure per component instead of assuming higher is faster.
  • How do you see exactly which optimizations a level enables in your GCC?
    Run `g++ -Q -O2 --help=optimizers` and compare it with another level. The set depends on the target and configuration, so this beats memorizing lists, and it shows the effect of adding or removing individual `-f` flags.

  • GCC optimizes at -O2 unless told otherwise.
  • Adding -f flags to an -O0 build enables those optimizations.
  • -O3 is always faster than -O2.
  • If a program prints different results at -O0 and -O2, the optimizer must have a bug.
  • -Og means no optimization with extra debug information.

Assumes GCC 16, whose -O2 includes loop and SLP vectorization with the very-cheap cost model and which documents -Oz.

open as a page

What does GCC's -g option add to an object file, and how do -g1, -g3 and -ggdb differ?

level: juniorimportance: must knowfreq 60%

basics

~20 s

-g adds debugging information, normally DWARF sections describing types, variables and line numbers, without changing the generated instructions. -g1 keeps functions, external variables and line tables, the default -g2 adds locals, -g3 adds macro definitions, and -ggdb prefers GDB extensions.

open as a page

What stages does the g++ driver run, and where do the -E, -S and -c options stop it?

level: juniorimportance: must knowfreq 72%

basics

~20 s

g++ is a driver that runs the preprocessor, the compiler proper, the assembler and the linker in that order. -E stops after preprocessing, -S after producing assembly (.s), and -c after assembling an object file (.o).

open as a page

With GCC, does -Wall turn on every warning, and what do -Wextra and -Wpedantic add on top of it?

level: juniorimportance: must knowfreq 72%

basics

~10 s

No. GCC's -Wall is a curated set of easy-to-fix warnings; -Wextra adds more, such as unused parameters; -Wpedantic reports extensions ISO C++ forbids. Useful warnings like -Wconversion and -Wshadow are in none of them.

open as a page

When building a shared library with GCC, what do -fPIC, -shared and -fvisibility=hidden each contribute?

level: middleimportance: must knowfreq 58%

basics

~20 s

-fPIC compiles position-independent code that reaches globals through a table, so the library can load at any address. -shared makes the linker produce a .so. -fvisibility=hidden keeps symbols private unless marked default, shrinking exports and enabling direct calls.

open as a page

Why does `g++ -lgeo main.o` fail with undefined references to libgeo.a symbols while `g++ main.o -lgeo` links?

level: middleimportance: must knowfreq 66%

basics

~20 s

The GNU linker reads inputs left to right and extracts archive members only for symbols already undefined at that point. With -lgeo first nothing is undefined yet, so no member is pulled and main.o's references stay unresolved.

open as a page

With GCC, what does -fsanitize=address detect, and how do you read its report for a use-after-free in a server?

level: middleimportance: must knowfreq 66%

basics

~20 s

-fsanitize=address instruments memory accesses to catch out-of-bounds reads and writes on the heap, stack and globals, use-after-free and use-after-scope. Its report shows the bad access's stack, then where that memory was freed and where it was allocated.

open as a page

A numerics kernel built with g++ -O3 -march=native is fast on a dev box but dies with an illegal instruction on a customer's older CPU; why, and how do you fix it?

level: seniorimportance: must knowfreq 48%

basics

~20 s

-march=native lets GCC use every instruction the build machine supports, so the binary executes instructions an older CPU lacks and dies with SIGILL. Build for a baseline -march, tune with -mtune, and clone hot functions with target_clones.

open as a page

Why do profilers show broken call stacks for an -O2 GCC build, and what does -fno-omit-frame-pointer change?

level: middleimportance: should knowfreq 38%

basics

~20 s

From -O1 GCC enables -fomit-frame-pointer, so functions no longer keep the frame-pointer chain that cheap stack walking follows. -fno-omit-frame-pointer restores the chain at the cost of one register and a short prologue, giving profilers usable stacks.

open as a page

With GCC, in what order are -iquote, -I and -isystem directories searched, and how do -D and -U define macros?

level: middleimportance: should knowfreq 55%

basics

~20 s

For #include "..." GCC searches the including file's directory, then -iquote, then -I, then -isystem and the system directories; #include <...> starts at -I. -D name defines it as 1, -D name=value sets a value, and -U cancels a definition.

open as a page

What C++ standard does GCC 16 compile by default, and how does -std=gnu++20 differ from -std=c++20?

level: middleimportance: should knowfreq 45%

basics

~20 s

GCC 16 defaults to -std=gnu++20, up from gnu++17 in GCC 11 to 15. The gnu++ dialects keep GNU extensions that conflict with ISO C++; -std=c++20 disables those, but other extensions remain until -Wpedantic diagnoses them.

open as a page

With GCC, what does -fsanitize=undefined check, and why can a CI job pass despite UBSan reports unless you add -fno-sanitize-recover?

level: middleimportance: should knowfreq 52%

basics

~20 s

-fsanitize=undefined inserts run-time checks for undefined operations such as signed overflow, bad shifts, division by zero and null or misaligned access. GCC enables recovery by default, so the program continues and may exit 0; -fno-sanitize-recover=undefined makes errors fatal.

open as a page

With GCC, how do #pragma GCC diagnostic push, ignored and pop silence one third-party header's warning under -Werror?

level: middleimportance: should knowfreq 38%

basics

~20 s

Wrap the #include in #pragma GCC diagnostic push, then ignored "-Wname", then pop: GCC ignores that warning only between them and keeps -Werror elsewhere. A pragma affects only diagnostics for lines after it, and pop restores the saved state.

open as a page

With GCC, how do you read a hundred-line error from calling std::sort on a std::list and find the line to fix?

level: middleimportance: should knowfreq 48%

basics

~20 s

Read the first error, then follow its instantiation notes to the one frame in your own source: that is the call to fix. Here std::sort needs random-access iterators and std::list has bidirectional ones, so call the list's own sort() instead.

open as a page

With GCC, what do -Wconversion and -Wshadow catch that -Wall -Wextra miss, and why does C++ need -Wsign-conversion separately?

level: middleimportance: should knowfreq 50%

basics

~20 s

-Wconversion warns on implicit conversions that may change a value, such as double to int; -Wshadow warns when a declaration hides another variable, parameter or class member. In C++, GCC's -Wconversion skips signed/unsigned changes unless -Wsign-conversion is enabled explicitly.

open as a page

What does GCC's -flto do at compile and link time, and what breaks with static libraries or mixed GCC versions?

level: seniorimportance: should knowfreq 38%

basics

~20 s

-flto stores GCC's intermediate representation in each object and optimizes the whole program again at link time, so inlining crosses files. Archives of such objects need gcc-ar, and the bytecode only works with the GCC version that wrote it.

open as a page

A program links cleanly with g++ -L/opt/geo/lib -lgeo but fails at startup because libgeo.so cannot be found; why, and how do rpath and runpath fix it?

level: seniorimportance: should knowfreq 52%

basics

~20 s

-L only tells the linker where to find libraries while linking; the executable records just the library's name. At startup the dynamic loader searches its own path list, so embed one with -Wl,-rpath or install the library where the loader looks.

open as a page

What does GCC's -Ofast enable beyond -O3, and why can it silently break a correct floating-point program?

level: seniorimportance: should knowfreq 42%

basics

~20 s

-Ofast is -O3 plus -ffast-math and -fallow-store-data-races. Fast-math assumes no NaNs or infinities, allows reordering floating-point operations and skips errno, so NaN checks can vanish, sums change, and on x86 linked startup code flushes denormals to zero.

open as a page

A GCC build mis-expands a macro and an inline asm block returns garbage; how do -E, -dD, -save-temps and -S -fverbose-asm show what the compiler received and emitted?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Rerun the exact compile line with -E, adding -dD or -dM, to see expanded code and macro definitions, or with -save-temps to keep the .ii and .s. Then read -S -fverbose-asm output for the registers GCC gave the inline asm.

open as a page

With GCC 16, what do -fhardened, _FORTIFY_SOURCE, _GLIBCXX_ASSERTIONS and -fstack-protector-strong add to a production C++ build?

level: seniorimportance: should knowfreq 38%

basics

~20 s

They are low-cost protections meant to ship, unlike sanitizers: bounds-checked string and memory calls, library precondition assertions, stack canaries. -fhardened (GCC 14+, GNU/Linux) enables them plus zeroed locals, PIE, RELRO and stack-clash protection. _FORTIFY_SOURCE only takes effect when optimizing.

open as a page

A multithreaded C++ server crashes only under load; how do you use GCC's sanitizers to find the cause, and why need two separate builds?

level: seniorimportance: should knowfreq 50%

basics

~10 s

Build two instrumented binaries and replay the load against each: -fsanitize=address,undefined for memory errors, -fsanitize=thread for data races. GCC rejects -fsanitize=thread together with address or leak, so one build cannot run both.

open as a page

With GCC 16, why can a C++ build pass -Werror at -O0 but fail at -O2 on -Wmaybe-uninitialized, and what does -fanalyzer add?

level: seniorimportance: should knowfreq 34%

basics

~20 s

Some GCC warnings use data-flow analysis that only runs when optimizing: -Wmaybe-uninitialized is impossible at -O0, so an -O2 build sees new reports. -fanalyzer adds costly path-based checking, but the GCC 16 manual calls it suitable only for C code.

open as a page

For a C++ product built with GCC, how do you decide between static and shared linking for your own libraries, libstdc++ and the C library?

level: principalimportance: should knowfreq 40%

basics

~20 s

Decide per layer. Your own libraries are usually static for simple deployment and LTO, unless plugins or several executables share them. libstdc++ can be linked statically with -static-libstdc++. The C library usually stays shared because the system patches it.

open as a page

How would you design the CI sanitizer matrix for a large multithreaded C++ server built with GCC, and what does each job cost?

level: principalimportance: should knowfreq 38%

basics

~20 s

Separate jobs, because thread cannot share a build with address or leak: ASan with UBSan and leak checks on every change, TSan on the concurrency tests, a hardened release build, all failing on the first report. Run the slow suites nightly.

open as a page

You lead a C++ codebase with 4,000 GCC warnings: how do you choose the team's warning set and roll out -Werror without stalling delivery?

level: principalimportance: should knowfreq 40%

basics

~20 s

Fix the warning set first, freeze today's count, then ratchet: -Werror=<flag> for categories already clean, -Wno-error=<flag> for noisy ones, and new code held clean. Enforce -Werror in your CI, not in flags that users or newer compilers inherit.

open as a page

How does profile-guided optimization with GCC's -fprofile-generate and -fprofile-use work, and what makes its training run trustworthy?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

Build with -fprofile-generate, run a representative workload so the program writes .gcda count files, then rebuild with -fprofile-use. GCC then knows hot branches and loops, but the result is only as good as the training run.

open as a page