Skip to content
Tutorials Center
My learning

Topics

Lesson 145 of 171 ยท Modern C++ and Beyond

Compilers, Flags and Optimization

Learn the C++ compiler flags that matter - warning sets, -O levels, debug info, sanitizers, LTO and hardening - and see how the optimizer transforms code, with live demos.

The same C++ source can become a slow, debuggable program or a fast, hard-to-debug one, a binary that catches memory bugs at run time or one that silently corrupts memory, all depending on the flags you pass to the compiler. Most beginners use whatever their IDE picked; professionals choose deliberately, and they know what the optimizer is allowed to do with their code.

This lesson is a practical tour of the flags that matter for GCC and Clang (with MSVC equivalents): warnings, language standard, debug information, optimization levels, link-time optimization, sanitizers and hardening. Along the way you'll see what an optimizer actually does, why "it worked in debug mode" is a warning sign, and how to inspect generated code with Compiler Explorer. Our editor compiles every example with g++ -std=c++23 -O1 -Wall -Wextra, and a few GCC-specific tricks let us compare optimization levels inside one program. It builds on How C++ Works: Compiling and Linking and Undefined Behavior and Memory Safety.

The three big compilers

GCC (g++) Clang (clang++) MSVC (cl)
Language standard -std=c++23 -std=c++23 /std:c++latest (/std:c++20)
Common warnings -Wall -Wextra -Wall -Wextra /W4
Warnings as errors -Werror -Werror /WX
Debug info -g -g /Zi
Optimize for speed -O2 / -O3 -O2 / -O3 /O2
Optimize for size -Os -Os / -Oz /O1
Link-time optimization -flto -flto / -flto=thin /GL + /LTCG
Address sanitizer -fsanitize=address -fsanitize=address /fsanitize=address
Define a macro -DNAME=value -DNAME=value /DNAME=value

Clang deliberately accepts GCC's flags, so on Linux and macOS most advice applies to both. Clang also ships clang-cl, a driver that accepts MSVC's flags. In a CMake project, you set most of these per target (see Build Systems: Make and CMake), and the build type (Debug, Release) picks optimization and debug flags for you.

Warnings: your cheapest bug finder

A warning is the compiler saying "this is legal, but it's probably not what you meant." Warnings are free, instant code review, and the defaults are far too quiet: plain g++ main.cpp shows almost nothing. A good everyday set:

Terminal
-Wall -Wextra -Wpedantic -Wshadow -Wconversion -Wsign-conversion -Wnon-virtual-dtor -Wold-style-cast
  • -Wall enables the common, low-noise warnings (unused variables, uninitialized use, misleading indentation and many more). Despite its name, it is not "all".
  • -Wextra adds more (unused parameters, signed/unsigned comparison, missing initializers).
  • -Wpedantic rejects compiler extensions that aren't standard C++, like variable-length arrays.
  • -Wshadow flags a local variable hiding another; -Wconversion and -Wsign-conversion flag implicit conversions that can lose data. These are noisier and especially worth it for new code.
  • -Werror turns warnings into errors. Use it in CI, so warnings can't accumulate, but think twice about forcing it on users building your library with a newer compiler that adds warnings.

Here are four bugs, all of which compile. Run it and read the compiler's output above the program's output:

C++ Warnings that point at real bugs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

GCC reports three of the four: the signed/unsigned comparison (-Wsign-compare, part of -Wextra), the unused variable, and the function that can fall off its end without returning a value (-Wreturn-type), which is undefined behavior for sign(0). The deposit bug, a local variable hiding the member, needs -Wshadow, which our editor doesn't enable; that's why many teams add it. Treat every warning as a bug report until proven otherwise.

Debug information and debug builds

-g stores debug information (line numbers, variable names, types) in the binary so debuggers like gdb, lldb and IDE debuggers can map machine code back to your source. It doesn't change the generated code, so you can and should use it with optimization too (-O2 -g, which CMake calls RelWithDebInfo); production builds often keep the debug info in a separate file.

Optimization makes debugging harder: variables are "optimized out", lines execute out of order, and functions disappear into their callers. For the best debugging experience use -O0 -g; GCC also offers -Og, which applies only optimizations that don't hurt debugging.

The NDEBUG macro is the other half of a release configuration: -DNDEBUG turns every assert() into nothing. Release build types add it automatically.

Optimization levels

Flag What you get
-O0 No optimization (the default). Fast compile, each statement maps to code, easiest debugging, slowest program.
-O1 Basic optimizations that don't take long to compile: register allocation, constant propagation, dead code removal, simple inlining.
-O2 The standard choice for release builds: nearly all optimizations that don't trade size for speed; includes vectorization since GCC 12.
-O3 More aggressive: heavier inlining, loop unrolling and vectorization. Sometimes faster than -O2, sometimes bigger and slower; measure.
-Os / -Oz Optimize for size (-Oz even more, Clang and GCC 12+). Useful for embedded and caches.
-Ofast -O3 plus -ffast-math: allows breaking IEEE floating-point rules (reordering sums, assuming no NaN/infinity). Results can change; avoid unless you understand the consequences.

Two related flags matter for speed:

  • -march=native lets the compiler use every instruction your CPU supports (AVX2, AVX-512 and so on). The binary may crash with "illegal instruction" on older machines, so use it for local builds or with an explicit target like -march=x86-64-v3.
  • -flto enables link-time optimization: the compiler keeps an intermediate representation in the object files, and optimization happens again at link time across all files, so a function in one .cpp file can be inlined into another. Typical gains are 5 to 15 percent, at the cost of longer links. Profile-guided optimization (-fprofile-generate, run typical workloads, then -fprofile-use) goes further by optimizing for how the program actually behaves.

GCC lets you change the optimization level of a single function with the [[gnu::optimize]] attribute. It's meant for debugging the compiler, not for production code, but it lets us compare three levels in one program:

C++ The same loop at O0, O1 and O3

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

All three produce the same checksum (unsigned arithmetic wraps around, which is well-defined). On our server the -O0 version is typically 5 to 8 times slower than -O1: at -O0, v.size() and v[i] are real function calls on every iteration and total lives in memory instead of a register. -O3 is faster again, often by 1.5 to 2 times, because it vectorizes the loop, processing four values per instruction with SIMD registers. Timings on a shared server are noisy, so run it a few times; the ratios are what matter. This is also why you must never benchmark, or judge the speed of C++, at -O0.

What the optimizer actually does

Optimizers apply hundreds of transformations. The most important ones:

  • Constant folding and propagation: compute at compile time whatever can be computed. int seconds = 24 * 60 * 60; becomes 86400.
  • Inlining: replace a function call with the function's body, removing call overhead and, more importantly, letting the other optimizations see through the call. This is why small functions, getters and templates cost nothing in optimized C++ (see inline Functions).
  • Dead code elimination: delete computations whose results are never used.
  • Loop optimizations: hoisting invariant code out of loops, unrolling, vectorization (SIMD), and sometimes replacing a whole loop with a formula.
  • Devirtualization: turning a virtual call into a direct (and inlinable) call when the compiler can prove the dynamic type.

The best way to see these is Compiler Explorer at godbolt.org, a free website that shows the assembly for your code with any compiler, version and flags, side by side and color-coded by source line. For example, with GCC and -O2:

C++
int square(int x) { return x * x; }
int answer() { return square(6) + 6; }
TEXT
square(int):
        imul    edi, edi        # x * x (the argument arrives in edi)
        mov     eax, edi        # return value goes in eax
        ret
answer():
        mov     eax, 42         # square(6) + 6 was computed at compile time
        ret

answer() never calls square: the call was inlined, 6 * 6 + 6 was folded, and the function returns the constant 42. Experimenting there with small functions is the fastest way to build intuition about what's cheap in C++.

The as-if rule, and why undefined behavior bites

The optimizer may transform your program in any way that doesn't change its observable behavior (input/output and volatile accesses). That's the as-if rule. Its consequence: for a program with undefined behavior, there is no behavior to preserve, so the compiler may assume UB never happens and optimize on that assumption.

C++ The optimizer assumes no signed overflow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first line prints false: GCC simplified x + 1 < x to false at compile time, because it would only be true after undefined behavior. At -O0 the same code may print true. Programs with UB that "work in debug and break in release" usually have exactly this kind of problem. Write checks that don't rely on UB (or use __builtin_add_overflow, and C++26's saturating std::add_sat), and find UB with the sanitizers below.

Sanitizers: catching bugs at run time

Sanitizers are compiler instrumentation that checks your program while it runs and reports bugs with a precise message and stack trace. They're the single most effective tool for finding memory bugs, and every C++ developer should use them in development and CI:

Flag Finds Slowdown
-fsanitize=address (ASan) Out-of-bounds reads/writes on heap, stack and globals, use-after-free, double free, leaks about 2x
-fsanitize=undefined (UBSan) Signed overflow, invalid shifts, null dereference, misaligned access, bad casts small
-fsanitize=thread (TSan) Data races between threads 5 to 15x
-fsanitize=memory (MSan, Clang only) Reads of uninitialized memory about 3x

ASan and UBSan combine well: -fsanitize=address,undefined -fno-omit-frame-pointer -g. TSan can't be combined with ASan, so it needs a separate build. A typical ASan report looks like this (shortened):

TEXT
==4211==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000020
READ of size 4 at 0x502000000020 thread T0
    #0 0x401234 in average(std::vector<int> const&) stats.cpp:12
    #1 0x401567 in main main.cpp:8
0x502000000020 is located 0 bytes after 16-byte region allocated by thread T0 here:
    #0 ... in operator new(unsigned long)
    #1 ... in main main.cpp:6

It names the bug, the file and line of the bad access, and where the memory was allocated. Without ASan the same bug might print a plausible wrong number, or crash somewhere unrelated much later.

Our editor can't pass sanitizer flags, but it can show a lighter cousin: the C++ standard library's assertions mode. Defining _GLIBCXX_ASSERTIONS (libstdc++; libc++ has "hardening modes") before any include adds bounds checks to operator[] and other precondition checks, with very low overhead. The program below indexes out of bounds on purpose, so it stops with an error:

C++ Library assertions catch an out-of-bounds index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first sum prints 175. (The fflush matters: output is buffered, and an aborting program never empties its buffers, so without it even that line would be lost. That's a classic reason why "my debug print never appeared" before a crash.) The second call aborts with a message naming std::vector<int>::operator[] and the failed assertion __n < this->size(), and the run reports a crash (signal SIGABRT). Without the macro, the same code would silently read whatever memory follows the vector and print a garbage total. Many Linux distributions build their packages with this option, and C++26 standardizes the idea as a hardened standard library.

Hardening flags for production

Beyond sanitizers (which are for testing), a few low-cost flags make release binaries harder to exploit:

  • -D_FORTIFY_SOURCE=3 (with optimization): checks buffer sizes in C library calls like memcpy and strcpy.
  • -fstack-protector-strong: detects stack buffer overflows before a function returns.
  • -D_GLIBCXX_ASSERTIONS: the library precondition checks shown above.
  • -fPIE -pie, -Wl,-z,relro,-z,now: position-independent executables and read-only relocations for stronger address-space randomization.

Many distributions enable most of these by default. Compilers have also started offering a single umbrella option (GCC 14's -fhardened) that turns on a recommended set.

Terminal
# Everyday development
g++ -std=c++23 -Wall -Wextra -Wpedantic -Wshadow -g -O0 -fsanitize=address,undefined

# Continuous integration (also run a separate -fsanitize=thread build for threaded code)
g++ -std=c++23 -Wall -Wextra -Wpedantic -Wshadow -Werror -O1 -g -fsanitize=address,undefined

# Release
g++ -std=c++23 -Wall -Wextra -O2 -g -DNDEBUG -flto -D_FORTIFY_SOURCE=3 -fstack-protector-strong

Static analyzers complement the compiler: clang-tidy (hundreds of checks, including modernize-* and bugprone-*), cppcheck, and the analyzers built into GCC (-fanalyzer) and MSVC (/analyze).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about -Wall is true?

    Despite the name, -Wall is a curated set. -Wextra, -Wpedantic, -Wshadow and -Wconversion add further warnings, and -Werror makes them errors.
  2. 2. A benchmark compiled with -O0 shows that a function using std::vector::operator[] is slow. What's the right conclusion?

    At -O0 every tiny function is a real call and values live in memory. Optimized builds inline them, so performance must always be measured with -O2 or similar.
  3. 3. bool f(int x) { return x + 1 < x; } returns false for INT_MAX in an optimized build. Why?

    Under the as-if rule, a program with UB has no behavior to preserve. The optimizer assumes x + 1 doesn't overflow, so x + 1 < x is always false.
  4. 4. Which tool reports use-after-free and heap buffer overflows with the exact source line?

    AddressSanitizer instruments memory accesses and reports bad accesses with stack traces for the access and the allocation. The other flags change optimization or warnings.
  5. 5. What does -flto add on top of -O2?

    Normally each .cpp file is optimized alone. With link-time optimization, the linker sees the whole program's intermediate code and can optimize across files.

Summary

  • GCC and Clang share flags (-std=c++23, -Wall -Wextra, -O2, -g); MSVC uses /W4, /O2, /Zi, /std:c++latest.
  • Turn on many warnings (-Wall -Wextra -Wpedantic -Wshadow, optionally -Wconversion) and use -Werror in CI. Warnings are free code review.
  • -O0 -g for debugging, -O2 (or -O3, measured) for release, -g alongside for debuggable release builds, -DNDEBUG to disable asserts. Never benchmark unoptimized code.
  • Optimizers fold constants, inline, remove dead code and vectorize loops; Compiler Explorer shows you the result. Under the as-if rule they assume undefined behavior never happens.
  • Sanitizers (-fsanitize=address,undefined, thread) catch memory bugs, UB and data races at run time; _GLIBCXX_ASSERTIONS adds cheap library checks.
  • For more speed use -flto, PGO and a suitable -march; for safer releases add _FORTIFY_SOURCE, stack protectors and library hardening.

Next: Writing Fast C++, where you'll measure real programs and learn which habits make the biggest difference to speed.