GCC(1)

📦 version 12.2.0, in nixpkgs unstable

💅 gcc(1) — GNU project C and C++ compiler 💅

okay bestie, gather round the group chat 💖 this is the manual page for gcc, aka the GNU project C and C++ compiler. We're doing the whole compiler-pipeline thing, but make it make sense, fr fr. ✨


🌸 NAME 🌸

gcc — GNU project C and C++ compiler


🦋 SYNOPSIS 🦋

gcc [-c|-S|-E] [-std=standard]
    [-g] [-pg] [-Olevel]
    [-Wwarn...] [-Wpedantic]
    [-Idir...] [-Ldir...]
    [-Dmacro[=defn]...] [-Umacro]
    [-foption...] [-mmachine-option...]
    [-o outfile] [@file] infile...

Only the most useful options are listed here; see below for the remainder. g++ accepts mostly the same options as gcc.


✨ DESCRIPTION ✨

When you invoke GCC, it normally does preprocessing, compilation, assembly and linking. The "overall options" allow you to stop this process at an intermediate stage. For example, the -c option says not to run the linker. Then the output consists of object files output by the assembler. 🛠️

Other options are passed on to one or more stages of processing. Some options control the preprocessor and others the compiler itself. Yet other options control the assembler and linker; most of these are not documented here, since you rarely need to use any of them.

Most of the command-line options that you can use with GCC are useful for C programs; when an option is only useful with another language (usually C++), the explanation says so explicitly. If the description for a particular option does not mention a source language, you can use that option with all supported languages. 💖

The usual way to run GCC is to run the executable called gcc, or machine-gcc when cross-compiling, or machine-gcc-version to run a specific version of GCC. When you compile C++ programs, you should invoke GCC as g++ instead. 👑

The gcc program accepts options and file names as operands. Many options have multi-letter names; therefore multiple single-letter options may not be grouped: -dv is very different from -d -v. 😭

You can mix options and other arguments. For the most part, the order you use doesn't matter. Order does matter when you use several options of the same kind; for example, if you specify -L more than once, the directories are searched in the order specified. Also, the placement of the -l option is significant. 🌈

Many options have long names starting with -f or with -W---for example, -fmove-loop-invariants, -Wformat, and so on. Most of these have both positive and negative forms; the negative form of -ffoo is -fno-foo. This manual documents only one of these two forms, whichever one is not the default. 💅

Some options take one or more arguments typically separated either by a space or by the equals sign (=) from the option name. Unless documented otherwise, an argument can be either numeric or a string. Numeric arguments must typically be small unsigned decimal or hexadecimal integers. Hexadecimal arguments must begin with the 0x prefix. Arguments to options that specify a size threshold of some sort may be arbitrarily large decimal or hexadecimal integers followed by a byte size suffix designating a multiple of bytes such as "kB" and "KiB" for kilobyte and kibibyte, respectively, "MB" and "MiB" for megabyte and mebibyte, "GB" and "GiB" for gigabyte and gigibyte, and so on. Such arguments are designated by byte-size in the following text. Refer to the NIST, IEC, and other relevant national and international standards for the full listing and explanation of the binary and decimal byte size prefixes. 🧚


🛠️ OPTIONS 🛠️

🌟 Option Summary 🌟

Here is a summary of all the options, grouped by type. Explanations are in the following sections. 💖

🌈 Overall Options 🌈

-c  -S  -E  -o file -dumpbase dumpbase  -dumpbase-ext auxdropsuf
-dumpdir dumppfx  -x language -v  -###  --help[=class[,...]]
--target-help  --version -pass-exit-codes  -pipe  -specs=file
-wrapper @file  -ffile-prefix-map=old=new -fplugin=file
-fplugin-arg-name=arg -fdump-ada-spec[-slim]  -fada-spec-parent=unit
-fdump-go-spec=file

🍓 C Language Options 🍓

-ansi  -std=standard  -aux-info filename
-fallow-parameterless-variadic-functions  -fno-asm -fno-builtin
-fno-builtin-function  -fcond-mismatch -ffreestanding  -fgimple
-fgnu-tm  -fgnu89-inline  -fhosted -flax-vector-conversions
-fms-extensions -foffload=arg  -foffload-options=arg -fopenacc
-fopenacc-dim=geom -fopenmp  -fopenmp-simd
-fpermitted-flt-eval-methods=standard -fplan9-extensions
-fsigned-bitfields  -funsigned-bitfields -fsigned-char
-funsigned-char  -fsso-struct=endianness

💜 C++ Language Options 💜

-fabi-version=n  -fno-access-control -faligned-new=n
-fargs-in-order=n  -fchar8_t  -fcheck-new -fconstexpr-depth=n
-fconstexpr-cache-depth=n -fconstexpr-loop-limit=n
-fconstexpr-ops-limit=n -fno-elide-constructors
-fno-enforce-eh-specs -fno-gnu-keywords -fno-implicit-templates
-fno-implicit-inline-templates -fno-implement-inlines
-fmodule-header[=kind] -fmodule-only -fmodules-ts
-fmodule-implicit-inline -fno-module-lazy
-fmodule-mapper=specification -fmodule-version-ignore
-fms-extensions -fnew-inheriting-ctors -fnew-ttp-matching
-fno-nonansi-builtins  -fnothrow-opt  -fno-operator-names
-fno-optional-diags  -fpermissive -fno-pretty-templates -fno-rtti
-fsized-deallocation -ftemplate-backtrace-limit=n -ftemplate-depth=n
-fno-threadsafe-statics  -fuse-cxa-atexit -fno-weak  -nostdinc++
-fvisibility-inlines-hidden -fvisibility-ms-compat
-fext-numeric-literals -flang-info-include-translate[=header]
-flang-info-include-translate-not -flang-info-module-cmi[=module]
-stdlib=libstdc++,libc++ -Wabi-tag  -Wcatch-value  -Wcatch-value=n
-Wno-class-conversion  -Wclass-memaccess -Wcomma-subscript
-Wconditionally-supported -Wno-conversion-null
-Wctad-maybe-unsupported -Wctor-dtor-privacy  -Wno-delete-incomplete
-Wdelete-non-virtual-dtor  -Wno-deprecated-array-compare
-Wdeprecated-copy -Wdeprecated-copy-dtor
-Wno-deprecated-enum-enum-conversion
-Wno-deprecated-enum-float-conversion -Weffc++  -Wno-exceptions
-Wextra-semi  -Wno-inaccessible-base -Wno-inherited-variadic-ctor
-Wno-init-list-lifetime -Winvalid-imported-macros
-Wno-invalid-offsetof  -Wno-literal-suffix -Wmismatched-new-delete
-Wmismatched-tags -Wmultiple-inheritance  -Wnamespaces  -Wnarrowing
-Wnoexcept  -Wnoexcept-type  -Wnon-virtual-dtor -Wpessimizing-move
-Wno-placement-new  -Wplacement-new=n -Wrange-loop-construct
-Wredundant-move -Wredundant-tags -Wreorder  -Wregister
-Wstrict-null-sentinel  -Wno-subobject-linkage  -Wtemplates
-Wno-non-template-friend  -Wold-style-cast -Woverloaded-virtual
-Wno-pmf-conversions -Wsign-promo -Wsized-deallocation
-Wsuggest-final-methods -Wsuggest-final-types  -Wsuggest-override
-Wno-terminate  -Wuseless-cast  -Wno-vexing-parse
-Wvirtual-inheritance -Wno-virtual-move-assign  -Wvolatile
-Wzero-as-null-pointer-constant

🦋 Objective-C and Objective-C++ Language Options 🦋

-fconstant-string-class=class-name -fgnu-runtime  -fnext-runtime
-fno-nil-receivers -fobjc-abi-version=n -fobjc-call-cxx-cdtors
-fobjc-direct-dispatch -fobjc-exceptions -fobjc-gc -fobjc-nilcheck
-fobjc-std=objc1 -fno-local-ivars
-fivar-visibility=[public|protected|private|package]
-freplace-objc-classes -fzero-link -gen-decls -Wassign-intercept
-Wno-property-assign-default -Wno-protocol -Wobjc-root-class
-Wselector -Wstrict-selector-match -Wundeclared-selector

🎀 Diagnostic Message Formatting Options 🎀

-fmessage-length=n -fdiagnostics-plain-output
-fdiagnostics-show-location=[once|every-line]
-fdiagnostics-color=[auto|never|always]
-fdiagnostics-urls=[auto|never|always]
-fdiagnostics-format=[text|json] -fno-diagnostics-show-option
-fno-diagnostics-show-caret -fno-diagnostics-show-labels
-fno-diagnostics-show-line-numbers -fno-diagnostics-show-cwe
-fdiagnostics-minimum-margin-width=width
-fdiagnostics-parseable-fixits  -fdiagnostics-generate-patch
-fdiagnostics-show-template-tree  -fno-elide-type
-fdiagnostics-path-format=[none|separate-events|inline-events]
-fdiagnostics-show-path-depths -fno-show-column
-fdiagnostics-column-unit=[display|byte]
-fdiagnostics-column-origin=origin
-fdiagnostics-escape-format=[unicode|bytes]

💅 Warning Options 💅

okay bestie, buckle up, because this is the section where the sheer number of flags is going to vibe-check your scrolling finger. These are the warning-ish flags in alphabetical-ish order, sprinkled with a few -f friends that gate or shape the warnings. We're not summarizing, we're not skipping, we're listing every single one like the icons they are. 💖

  • -fsyntax-only, -fmax-errors=n, -Wpedantic, -pedantic-errors, -w
  • -Wextra, -Wall, -Wabi=n, -Waddress, -Wno-address-of-packed-member
  • -Waggregate-return, -Walloc-size-larger-than=byte-size, -Walloc-zero
  • -Walloca, -Walloca-larger-than=byte-size, -Wno-aggressive-loop-optimizations
  • -Warith-conversion, -Warray-bounds, -Warray-bounds=n, -Warray-compare
  • -Wno-attributes, -Wattribute-alias=n, -Wno-attribute-alias, -Wno-attribute-warning
  • -Wbidi-chars=[none|unpaired|any|ucn], -Wbool-compare, -Wbool-operation
  • -Wno-builtin-declaration-mismatch, -Wno-builtin-macro-redefined
  • -Wc90-c99-compat, -Wc99-c11-compat, -Wc11-c2x-compat
  • -Wc++-compat, -Wc++11-compat, -Wc++14-compat, -Wc++17-compat, -Wc++20-compat
  • -Wno-c++11-extensions, -Wno-c++14-extensions, -Wno-c++17-extensions, -Wno-c++20-extensions, -Wno-c++23-extensions
  • -Wcast-align, -Wcast-align=strict, -Wcast-function-type, -Wcast-qual
  • -Wchar-subscripts, -Wclobbered, -Wcomment, -Wconversion
  • -Wno-coverage-mismatch, -Wno-cpp, -Wdangling-else, -Wdangling-pointer, -Wdangling-pointer=n
  • -Wdate-time, -Wno-deprecated, -Wno-deprecated-declarations, -Wno-designated-init
  • -Wdisabled-optimization, -Wno-discarded-array-qualifiers, -Wno-discarded-qualifiers, -Wno-div-by-zero
  • -Wdouble-promotion, -Wduplicated-branches, -Wduplicated-cond, -Wempty-body, -Wno-endif-labels
  • -Wenum-compare, -Wenum-conversion, -Werror, -Werror=* ← the absolute main character of the warning world ✨
  • -Wexpansion-to-defined, -Wfatal-errors, -Wfloat-conversion, -Wfloat-equal
  • -Wformat, -Wformat=2, -Wno-format-contains-nul, -Wno-format-extra-args
  • -Wformat-nonliteral, -Wformat-overflow=n, -Wformat-security, -Wformat-signedness
  • -Wformat-truncation=n, -Wformat-y2k, -Wframe-address, -Wframe-larger-than=byte-size
  • -Wno-free-nonheap-object, -Wno-if-not-aligned, -Wno-ignored-attributes, -Wignored-qualifiers
  • -Wno-incompatible-pointer-types, -Wimplicit, -Wimplicit-fallthrough, -Wimplicit-fallthrough=n
  • -Wno-implicit-function-declaration, -Wno-implicit-int, -Winfinite-recursion
  • -Winit-self, -Winline, -Wno-int-conversion, -Wint-in-bool-context
  • -Wno-int-to-pointer-cast, -Wno-invalid-memory-model, -Winvalid-pch, -Wjump-misses-init
  • -Wlarger-than=byte-size, -Wlogical-not-parentheses, -Wlogical-op, -Wlong-long, -Wno-lto-type-mismatch
  • -Wmain, -Wmaybe-uninitialized, -Wmemset-elt-size, -Wmemset-transposed-args, -Wmisleading-indentation
  • -Wmissing-attributes, -Wmissing-braces, -Wmissing-field-initializers, -Wmissing-format-attribute
  • -Wmissing-include-dirs, -Wmissing-noreturn, -Wno-missing-profile, -Wno-multichar
  • -Wmultistatement-macros, -Wnonnull, -Wnonnull-compare
  • -Wnormalized=[none|id|nfc|nfkc], -Wnull-dereference, -Wno-odr
  • -Wopenacc-parallelism, -Wopenmp-simd, -Wno-overflow, -Woverlength-strings, -Wno-override-init-side-effects
  • -Wpacked, -Wno-packed-bitfield-compat, -Wpacked-not-aligned, -Wpadded, -Wparentheses
  • -Wno-pedantic-ms-format, -Wpointer-arith, -Wno-pointer-compare, -Wno-pointer-to-int-cast
  • -Wno-pragmas, -Wno-prio-ctor-dtor, -Wredundant-decls, -Wrestrict, -Wno-return-local-addr
  • -Wreturn-type, -Wno-scalar-storage-order, -Wsequence-point, -Wshadow
  • -Wshadow=global, -Wshadow=local, -Wshadow=compatible-local, -Wno-shadow-ivar
  • -Wno-shift-count-negative, -Wno-shift-count-overflow, -Wshift-negative-value, -Wno-shift-overflow, -Wshift-overflow=n
  • -Wsign-compare, -Wsign-conversion, -Wno-sizeof-array-argument, -Wsizeof-array-div
  • -Wsizeof-pointer-div, -Wsizeof-pointer-memaccess, -Wstack-protector, -Wstack-usage=byte-size
  • -Wstrict-aliasing, -Wstrict-aliasing=n, -Wstrict-overflow, -Wstrict-overflow=n, -Wstring-compare
  • -Wno-stringop-overflow, -Wno-stringop-overread, -Wno-stringop-truncation
  • -Wsuggest-attribute=[pure|const|noreturn|format|malloc]
  • -Wswitch, -Wno-switch-bool, -Wswitch-default, -Wswitch-enum, -Wno-switch-outside-range, -Wno-switch-unreachable
  • -Wsync-nand, -Wsystem-headers, -Wtautological-compare, -Wtrampolines, -Wtrigraphs
  • -Wtrivial-auto-var-init, -Wtsan, -Wtype-limits, -Wundef, -Wuninitialized, -Wunknown-pragmas
  • -Wunsuffixed-float-constants, -Wunused
  • -Wunused-but-set-parameter, -Wunused-but-set-variable, -Wunused-const-variable, -Wunused-const-variable=n
  • -Wunused-function, -Wunused-label, -Wunused-local-typedefs, -Wunused-macros, -Wunused-parameter
  • -Wno-unused-result, -Wunused-value, -Wunused-variable, -Wno-varargs, -Wvariadic-macros
  • -Wvector-operation-performance, -Wvla, -Wvla-larger-than=byte-size, -Wno-vla-larger-than
  • -Wvolatile-register-var, -Wwrite-strings, -Wzero-length-bounds

the way that list just kept *going*… anyway, she ate. 💀✨


🧚 Static Analyzer Options 🧚

these are the analyzer girlies — the -fanalyzer family plus a whole constellation of -fdump-analyzer-* and -Wno-analyzer-* flags. still no notes on what each one does in this list, so just… take the full roster, bestie. every name, exactly as written, no cap. 🫶

  • -fanalyzer, -fanalyzer-call-summaries, -fanalyzer-checker=name
  • -fno-analyzer-feasibility, -fanalyzer-fine-grained, -fno-analyzer-state-merge, -fno-analyzer-state-purge
  • -fanalyzer-transitivity, -fanalyzer-verbose-edges, -fanalyzer-verbose-state-changes, -fanalyzer-verbosity=level
  • -fdump-analyzer, -fdump-analyzer-callgraph, -fdump-analyzer-exploded-graph
  • -fdump-analyzer-exploded-nodes, -fdump-analyzer-exploded-nodes-2, -fdump-analyzer-exploded-nodes-3
  • -fdump-analyzer-exploded-paths, -fdump-analyzer-feasibility, -fdump-analyzer-json
  • -fdump-analyzer-state-purge, -fdump-analyzer-stderr, -fdump-analyzer-supergraph, -fdump-analyzer-untracked
  • -Wno-analyzer-double-fclose, -Wno-analyzer-double-free, -Wno-analyzer-exposure-through-output-file
  • -Wno-analyzer-file-leak, -Wno-analyzer-free-of-non-heap, -Wno-analyzer-malloc-leak
  • -Wno-analyzer-mismatching-deallocation, -Wno-analyzer-null-argument, -Wno-analyzer-null-dereference
  • -Wno-analyzer-possible-null-argument, -Wno-analyzer-possible-null-dereference
  • -Wno-analyzer-shift-count-negative, -Wno-analyzer-shift-count-overflow, -Wno-analyzer-stale-setjmp-buffer
  • -Wno-analyzer-tainted-allocation-size, -Wno-analyzer-tainted-array-index, -Wno-analyzer-tainted-divisor
  • -Wno-analyzer-tainted-offset, -Wno-analyzer-tainted-size, -Wanalyzer-too-complex
  • -Wno-analyzer-unsafe-call-within-signal-handler, -Wno-analyzer-use-after-free
  • -Wno-analyzer-use-of-pointer-in-stale-stack-frame, -Wno-analyzer-use-of-uninitialized-value
  • -Wno-analyzer-write-to-const, -Wno-analyzer-write-to-string-literal

🎀 C and Objective-C-only Warning Options 🎀

these ones are exclusive — C and Objective-C only, so if you're in C++ land this is not your vibe. still iconic though. 🌸

  • -Wbad-function-cast, -Wmissing-declarations, -Wmissing-parameter-type, -Wmissing-prototypes
  • -Wnested-externs, -Wold-style-declaration, -Wold-style-definition, -Wstrict-prototypes
  • -Wtraditional, -Wtraditional-conversion, -Wdeclaration-after-statement, -Wpointer-sign

🦋 Debugging Options 🦋

the debug info corner of the universe — all the -g girlies plus the -f friends that shape what debug info actually gets emitted and how it's written out. every variant is here, including the -gno- negations, -gz[=type], -gsplit-dwarf, and the -fdebug-* / -femit-* / -fvar-tracking* crew. 💜

  • -g, -glevel, -gdwarf, -gdwarf-version
  • -gbtf, -gctf, -gctflevel, -ggdb
  • -grecord-gcc-switches, -gno-record-gcc-switches
  • -gstabs, -gstabs+
  • -gstrict-dwarf, -gno-strict-dwarf
  • -gas-loc-support, -gno-as-loc-support
  • -gas-locview-support, -gno-as-locview-support
  • -gcolumn-info, -gno-column-info
  • -gdwarf32, -gdwarf64
  • -gstatement-frontiers, -gno-statement-frontiers
  • -gvariable-location-views, -gno-variable-location-views
  • -ginternal-reset-location-views, -gno-internal-reset-location-views
  • -ginline-points, -gno-inline-points
  • -gvms, -gxcoff, -gxcoff+
  • -gz[=type], -gsplit-dwarf
  • -gdescribe-dies, -gno-describe-dies
  • -fdebug-prefix-map=old=new, -fdebug-types-section

and the last little cluster of debug-shaping -f flags, all present and accounted for:

  • -fno-eliminate-unused-debug-types
  • -femit-struct-debug-baseonly, -femit-struct-debug-reduced, -femit-struct-debug-detailed[=spec-list]
  • -fno-eliminate-unused-debug-symbols, -femit-class-debug-always
  • -fno-merge-debug-strings, -fno-dwarf2-cfi-asm
  • -fvar-tracking, -fvar-tracking-assignments

not me counting every single one to make sure nothing got left behind 😭 — but like, that's the whole roster, fr fr. 💖

Optimization Options 💅

okay bestie, this is the motherlode — the flags that make your code actually go. there are like a hundred of them and I'm not skipping a single one, so buckle up 🎀

  • -faggressive-loop-optimizations, -falign-functions[=n[:m:[n2[:m2]]]], -falign-jumps[=n[:m:[n2[:m2]]]], -falign-labels[=n[:m:[n2[:m2]]]], -falign-loops[=n[:m:[n2[:m2]]]], -fno-allocation-dce, -fallow-store-data-races, -fassociative-math — alignment squad ✨ note how -falign-functions, -falign-jumps, -falign-labels and -falign-loops all take that same gorgeous =n[:m:[n2[:m2]]] shape. iconique.
  • -fauto-profile, -fauto-profile[=path], -fauto-inc-dec, -fbranch-probabilities, -fcaller-saves, -fcombine-stack-adjustments, -fconserve-stack, -fcompare-elim — the profile-and-tidy girlies 🦋
  • -fcprop-registers, -fcrossjumping, -fcse-follow-jumps, -fcse-skip-blocks, -fcx-fortran-rules, -fcx-limited-range, -fdata-sections, -fdce — -fcse-* twins, we love a matched set 💖
  • -fdelayed-branch, -fdelete-null-pointer-checks, -fdevirtualize, -fdevirtualize-speculatively, -fdevirtualize-at-ltrans, -fdse, -fearly-inlining, -fipa-sra — three whole -fdevirtualize variants, she's thorough 💅
  • -fexpensive-optimizations, -ffat-lto-objects, -ffast-math, -ffinite-math-only, -ffloat-store, -fexcess-precision=style, -ffinite-loops, -fforward-propagate
  • -ffp-contract=style, -ffunction-sections, -fgcse, -fgcse-after-reload, -fgcse-las, -fgcse-lm, -fgraphite-identity, -fgcse-sm
  • -fhoist-adjacent-loads, -fif-conversion, -fif-conversion2, -findirect-inlining, -finline-functions, -finline-functions-called-once, -finline-limit=n, -finline-small-functions — inline gang, all seven of y'all 🫶
  • -fipa-modref, -fipa-cp, -fipa-cp-clone, -fipa-bit-cp, -fipa-vrp, -fipa-pta, -fipa-profile, -fipa-pure-const — the -fipa- cinematic universe starts here and honestly it does NOT stop
  • -fipa-reference, -fipa-reference-addressable, -fipa-stack-alignment, -fipa-icf, -fira-algorithm=algorithm, -flive-patching=level, -fira-region=region, -fira-hoist-pressure
  • -fira-loop-pressure, -fno-ira-share-save-slots, -fno-ira-share-spill-slots, -fisolate-erroneous-paths-dereference, -fisolate-erroneous-paths-attribute, -fivopts, -fkeep-inline-functions, -fkeep-static-functions — those two -fisolate-erroneous-paths-* names are a whole mouthful, respect 🫡
  • -fkeep-static-consts, -flimit-function-alignment, -flive-range-shrinkage, -floop-block, -floop-interchange, -floop-strip-mine, -floop-unroll-and-jam, -floop-nest-optimize — loop girlies, this is YOUR moment 💃
  • -floop-parallelize-all, -flra-remat, -flto, -flto-compression-level, -flto-partition=alg, -fmerge-all-constants, -fmerge-constants, -fmodulo-sched
  • -fmodulo-sched-allow-regmoves, -fmove-loop-invariants, -fmove-loop-stores, -fno-branch-count-reg, -fno-defer-pop, -fno-fp-int-builtin-inexact, -fno-function-cse, -fno-guess-branch-probability
  • -fno-inline, -fno-math-errno, -fno-peephole, -fno-peephole2, -fno-printf-return-value, -fno-sched-interblock, -fno-sched-spec, -fno-signed-zeros
  • -fno-toplevel-reorder, -fno-trapping-math, -fno-zero-initialized-in-bss, -fomit-frame-pointer, -foptimize-sibling-calls, -fpartial-inlining, -fpeel-loops, -fpredictive-commoning
  • -fprefetch-loop-arrays, -fprofile-correction, -fprofile-use, -fprofile-use=path, -fprofile-partial-training, -fprofile-values, -fprofile-reorder-functions, -freciprocal-math
  • -free, -frename-registers, -freorder-blocks, -freorder-blocks-algorithm=algorithm, -freorder-blocks-and-partition, -freorder-functions, -frerun-cse-after-loop, -freschedule-modulo-scheduled-loops — yes -free is literally a flag name and no it does not mean free as in money 😭
  • -frounding-math, -fsave-optimization-record, -fsched2-use-superblocks, -fsched-pressure, -fsched-spec-load, -fsched-spec-load-dangerous, -fsched-stalled-insns-dep[=n], -fsched-stalled-insns[=n] — -fsched-spec-load-dangerous really said main character with a warning label 💀
  • -fsched-group-heuristic, -fsched-critical-path-heuristic, -fsched-spec-insn-heuristic, -fsched-rank-heuristic, -fsched-last-insn-heuristic, -fsched-dep-count-heuristic, -fschedule-fusion, -fschedule-insns — six heuristics, she's an overachiever 👑
  • -fschedule-insns2, -fsection-anchors, -fselective-scheduling, -fselective-scheduling2, -fsel-sched-pipelining, -fsel-sched-pipelining-outer-loops, -fsemantic-interposition, -fshrink-wrap
  • -fshrink-wrap-separate, -fsignaling-nans, -fsingle-precision-constant, -fsplit-ivs-in-unroller, -fsplit-loops, -fsplit-paths, -fsplit-wide-types, -fsplit-wide-types-early
  • -fssa-backprop, -fssa-phiopt, -fstdarg-opt, -fstore-merging, -fstrict-aliasing, -fipa-strict-aliasing, -fthread-jumps, -ftracer
  • -ftree-bit-ccp, -ftree-builtin-call-dce, -ftree-ccp, -ftree-ch, -ftree-coalesce-vars, -ftree-copy-prop, -ftree-dce, -ftree-dominator-opts — the -ftree- fam is huge, hydrate before continuing 🍓
  • -ftree-dse, -ftree-forwprop, -ftree-fre, -fcode-hoisting, -ftree-loop-if-convert, -ftree-loop-im, -ftree-phiprop, -ftree-loop-distribution
  • -ftree-loop-distribute-patterns, -ftree-loop-ivcanon, -ftree-loop-linear, -ftree-loop-optimize, -ftree-loop-vectorize, -ftree-parallelize-loops=n, -ftree-pre, -ftree-partial-pre
  • -ftree-pta, -ftree-reassoc, -ftree-scev-cprop, -ftree-sink, -ftree-slsr, -ftree-sra, -ftree-switch-conversion, -ftree-tail-merge
  • -ftree-ter, -ftree-vectorize, -ftree-vrp, -ftrivial-auto-var-init, -funconstrained-commons, -funit-at-a-time, -funroll-all-loops, -funroll-loops
  • -funsafe-math-optimizations, -funswitch-loops, -fipa-ra, -fvariable-expansion-in-unroller, -fvect-cost-model, -fvpt, -fweb, -fwhole-program
  • -fwpa, -fuse-linker-plugin, -fzero-call-used-regs, --param name=value, -O, -O0, -O1, -O2, -O3, -Os, -Ofast, -Og, -Oz — and we close with the optimization levels, the ones everybody actually types 😌 -O -O0 -O1 -O2 -O3 -Os -Ofast -Og -Oz, all thirteen of 'em, --param name=value snuggled in right before. periodt 🎀

Program Instrumentation Options 🔍

these are the "watch me, tell me what I'm doing, and also maybe catch me when I fall" flags. sanitizers, stack protectors, profiling — the whole support system bestie 💖

  • -p, -pg, -fprofile-arcs, --coverage, -ftest-coverage, -fprofile-abs-path, -fprofile-dir=path, -fprofile-generate, -fprofile-generate=path, -fprofile-info-section, -fprofile-info-section=name
  • -fprofile-note=path, -fprofile-prefix-path=path, -fprofile-update=method, -fprofile-filter-files=regex, -fprofile-exclude-files=regex, -fprofile-reproducible=[multithreaded|parallel-runs|serial] — look at that big beautiful bracketed choice, three options, pick your girl 🌈
  • -fsanitize=style, -fsanitize-recover, -fsanitize-recover=style, -fasan-shadow-offset=number, -fsanitize-sections=s1,s2,..., -fsanitize-undefined-trap-on-error, -fbounds-check
  • -fcf-protection=[full|branch|return|none|check], -fharden-compares, -fharden-conditional-branches, -fstack-protector, -fstack-protector-all, -fstack-protector-strong, -fstack-protector-explicit — four whole stack-protector levels, protect her at all costs 🛡️
  • -fstack-check, -fstack-limit-register=reg, -fstack-limit-symbol=sym, -fno-stack-limit, -fsplit-stack, -fvtable-verify=[std|preinit|none], -fvtv-counts, -fvtv-debug
  • -finstrument-functions, -finstrument-functions-exclude-function-list=sym,sym,..., -finstrument-functions-exclude-file-list=file,file,..., -fprofile-prefix-map=old=new

Preprocessor Options 🧚

the # girlies! macrose, includes, dependency files — everything that happens before your code even becomes your code ✨

  • -Aquestion=answer, -A-question[=answer], -C, -CC, -Dmacro[=defn], -dD, -dI, -dM, -dN, -dU — yes that's -C and -CC, and five separate lowercase-d flags. no, I'm not joking 💅
  • -fdebug-cpp, -fdirectives-only, -fdollars-in-identifiers, -fexec-charset=charset, -fextended-identifiers, -finput-charset=charset, -flarge-source-files, -fmacro-prefix-map=old=new, -fmax-include-depth=depth
  • -fno-canonical-system-headers, -fpch-deps, -fpch-preprocess, -fpreprocessed, -ftabstop=width, -ftrack-macro-expansion, -fwide-exec-charset=charset, -fworking-directory, -H
  • -imacros file, -include file, -M, -MD, -MF, -MG, -MM, -MMD, -MP, -MQ, -MT, -Mno-modules — the capital-M alphabet soup 😭 -M -MD -MF -MG -MM -MMD -MP -MQ -MT -Mno-modules, collect them all
  • -no-integrated-cpp, -P, -pthread, -remap, -traditional, -traditional-cpp, -trigraphs, -Umacro, -undef, -Wp,option, -Xpreprocessor option — and yes -pthread shows up here and later in Linker. she's booked and busy in two sections fr fr

Assembler Options 🔧

  • -Wa,option — pass option straight to the assembler
  • -Xassembler option — same energy, different spelling, we stan options 💜

Linker Options 🔗

this is where everything gets stitched together and it's giving backstage-at-a-fashion-show energy 👑

  • object-file-name — yes that's not even a flag, it's just... an object file name. love that for us
  • -fuse-ld=linker, -llibrary, -nostartfiles, -nodefaultlibs, -nolibc, -nostdlib, -e entry, --entry=entry
  • -pie, -pthread, -r, -rdynamic, -s, -static, -static-pie
  • -static-libgcc, -static-libstdc++, -static-libasan, -static-libtsan, -static-liblsan, -static-libubsan — the static-lib squad, one for basically every sanitizer 🫶
  • -shared, -shared-libgcc, -symbolic, -T script, -Wl,option, -Xlinker option, -u symbol, -z keyword — and that's the tail end, -u symbol and -z keyword closing us out 💖

Directory Options 📁

where does GCC look for stuff? these flags answer that. it's giving "let me check my notes" energy 🎀

  • -Bprefix, -Idir, -I-, -idirafter dir, -imacros file, -imultilib dir, -iplugindir=dir, -iprefix file, -iquote dir
  • -isysroot dir, -isystem dir, -iwithprefix dir, -iwithprefixbefore dir, -Ldir, -no-canonical-prefixes, --no-sysroot-suffix
  • -nostdinc, -nostdinc++, --sysroot=dir — -nostdinc gets a ++ sibling and honestly that's sibling goals 💜

Code Generation Options 🏗️

the absolute deep-lore flags. registers, calling conventions, PIC, PIE, enums, wchar — the whole personality of your binary 💅

  • -fcall-saved-reg, -fcall-used-reg, -ffixed-reg, -fexceptions, -fnon-call-exceptions, -fdelete-dead-exceptions, -funwind-tables, -fasynchronous-unwind-tables, -fno-gnu-unique
  • -finhibit-size-directive, -fcommon, -fno-ident, -fpcc-struct-return, -fpic, -fPIC, -fpie, -fPIE, -fno-plt, -fno-jump-tables, -fno-bit-tests
  • -frecord-gcc-switches, -freg-struct-return, -fshort-enums, -fshort-wchar, -fverbose-asm, -fpack-struct[=n], -fleading-underscore
  • -ftls-model=model, -fstack-reuse=reuse_level, -ftrampolines, -ftrapv, -fwrapv, -fvisibility=[default|internal|hidden|protected], -fstrict-volatile-bitfields, -fsync-libcalls — -fpic vs -fPIC vs -fpie vs -fPIE is the case-sensitivity jumpscare of the century 😭

Developer Options 🛠️

okay these are for the girlies who are inside the compiler, not just using it. debug dumps, pass control, timing, temp files. extremely iykyk 💀

  • -dletters, -dumpspecs, -dumpmachine, -dumpversion, -dumpfullversion, -fcallgraph-info[=su,da], -fchecking, -fchecking=n, -fdbg-cnt-list, -fdbg-cnt=counter-value-list
  • -fdisable-ipa-pass_name, -fdisable-rtl-pass_name, -fdisable-rtl-pass-name=range-list, -fdisable-tree-pass_name, -fdisable-tree-pass-name=range-list — note the two flavors bestie: pass_name with an underscore and pass-name=range-list with a dash 🫡
  • -fdump-debug, -fdump-earlydebug, -fdump-noaddr, -fdump-unnumbered, -fdump-unnumbered-links, -fdump-final-insns[=file], -fdump-ipa-all, -fdump-ipa-cgraph, -fdump-ipa-inline
  • -fdump-lang-all, -fdump-lang-switch, -fdump-lang-switch-options, -fdump-lang-switch-options=filename, -fdump-passes, -fdump-rtl-pass, -fdump-rtl-pass=filename, -fdump-statistics
  • -fdump-tree-all, -fdump-tree-switch, -fdump-tree-switch-options, -fdump-tree-switch-options=filename, -fcompare-debug[=opts], -fcompare-debug-second
  • -fenable-kind-pass, -fenable-kind-pass=range-list, -fira-verbose=n, -flto-report, -flto-report-wpa, -fmem-report-wpa, -fmem-report, -fpre-ipa-mem-report, -fpost-ipa-mem-report
  • -fopt-info, -fopt-info-options[=file], -fprofile-report, -frandom-seed=string, -fsched-verbose=n, -fsel-sched-verbose, -fsel-sched-dump-cfg, -fsel-sched-pipelining-verbose, -fstats, -fstack-usage
  • -ftime-report, -ftime-report-details, -fvar-tracking-assignments-toggle, -gtoggle, -print-file-name=library, -print-libgcc-file-name, -print-multi-directory, -print-multi-lib, -print-multi-os-directory
  • -print-prog-name=program, -print-search-dirs, -Q, -print-sysroot, -print-sysroot-headers-suffix, -save-temps, -save-temps=cwd, -save-temps=obj, -time[=file] — save-temps really said "I'm keeping the receipts" and honestly valid 💖

Machine-Dependent Options 🖥️

these only exist for specific chip families, and the page kicks off with AArch64. the options are literally different per machine, so check which one you're on, bestie 🦋

AArch64 Options

  • -mabi=name, -mbig-endian, -mlittle-endian, -mgeneral-regs-only, -mcmodel=tiny, -mcmodel=small, -mcmodel=large, -mstrict-align, -mno-strict-align — three whole -mcmodel= sizes, pick your vibe 💅
  • -momit-leaf-frame-pointer, -mtls-dialect=desc, -mtls-dialect=traditional, -mtls-size=size, -mfix-cortex-a53-835769, -mfix-cortex-a53-843419 — those two -mfix-cortex-a53- flags are literally numbered bug fixes and I find that so iconic 🔥
  • -mlow-precision-recip-sqrt, -mlow-precision-sqrt, -mlow-precision-div, -mpc-relative-literal-loads, -msign-return-address=scope, -mbranch-protection=none|standard|pac-ret[+leaf +b-key]|bti — look at that -mbranch-protection value list, she's got layers 🧅✨
  • -mharden-sls=opts, -march=name, -mcpu=name, -mtune=name, -moverride=string, -mverbose-cost-dump, -mstack-protector-guard=guard, -mstack-protector-guard-reg=sysreg, -mstack-protector-guard-offset=offset, -mtrack-speculation, -moutline-atomics — -march, -mcpu, -mtune triad closing in, and -moutline-atomics bringing up the rear 🎀

🎀 Adapteva Epiphany Options 🎀

Ok bestie, here's the Epiphany roster — tiny parallel-computing icon energy ✨

  • -mhalf-reg-file — half reg file, half vibe 💅
  • -mprefer-short-insn-regs — short insns in regs? preferred, periodt
  • -mbranch-cost=num — you set the num, it sets the branch cost 🧮
  • -mcmove — cmove mode: on
  • -mnops=num — num nops, whatever you say queen 👑
  • -msoft-cmpsf — soft compare-float, cute
  • -msplit-lohi — split the lo and the hi, neatly 🍓
  • -mpost-inc — post-increment girlie
  • -mpost-modify — post-modify girlie, the sequel
  • -mstack-offset=num — stack offset of num, exactly that
  • -mround-nearest — nearest. not floor. nearest. 🎯
  • -mlong-calls — long calls, we go the distance 🦋
  • -mshort-calls — short calls, efficient queen
  • -msmall16 — small16, love that for you
  • -mfp-mode=mode — fp mode is mode, you pick it
  • -mvect-double — vector double ✨
  • -max-vect-align=num — max vector alignment num
  • -msplit-vecmove-early — split vecmove EARLY, no waiting
  • -m1reg-reg — one reg to rule them all 💀

🧚 AMD GCN Options 🧚

  • -march=gpu — you name the gpu, it's the arch
  • -mtune=gpu — same gpu, tuning flavored
  • -mstack-size=bytes — stack size, measured in bytes, obviously

🌸 ARC Options 🌸

  • -mbarrel-shifter — barrel shifter yes please
  • -mjli-always — jli, always, never not 💅
  • -mcpu=cpu — cpu = cpu, go off
  • -mA6 — A6 era
  • -mARC600 — ARC600 era
  • -mA7 — A7 era
  • -mARC700 — ARC700 era, the icon
  • -mdpfp — dpfp: on
  • -mdpfp-compact — dpfp but compact 🎀
  • -mdpfp-fast — dpfp but fast 🔥
  • -mno-dpfp-lrsr — no dpfp lrsr, we said what we said
  • -mea — ea, slay
  • -mno-mpy — no mpy 🙅
  • -mmul32x16 — 32x16 multiply math
  • -mmul64 — 64 multiply, big numbers core
  • -matomic — atomic 💥
  • -mnorm — norm, normalized, gorgeous
  • -mspfp — spfp: on
  • -mspfp-compact — spfp compact 🍓
  • -mspfp-fast — spfp fast ⭐
  • -msimd — SIMD yes bestie
  • -msoft-float — soft float, gentle math 🌸
  • -mswap — swap!
  • -mcrc — crc, checksum cutie
  • -mdsp-packa — dsp packa, packing it up
  • -mdvbf — dvbf, iconic letters
  • -mlock — lock it down 🔒
  • -mmac-d16 — mac d16
  • -mmac-24 — mac 24
  • -mrtsc — rtsc, that's the vibe
  • -mswape — swape, yes it's spelled like that 🙈
  • -mtelephony — telephony!! phone girlie 📞
  • -mxy — xy
  • -misize — isize
  • -mannotate-align — annotate your alignment, an icon
  • -marclinux — arclinux, we're so linux
  • -marclinux_prof — arclinux but _prof (yes, with the underscore 💀)
  • -mlong-calls — long calls
  • -mmedium-calls — medium calls, the middle child
  • -msdata — sdata
  • -mirq-ctrl-saved — irq ctrl, saved ✅
  • -mrgf-banked-regs — rgf banked regs
  • -mlpc-width=width — lpc width = width
  • -G num — capital G, then num
  • -mvolatile-cache — volatile cache, spicy 🌶️
  • -mtp-regno=regno — tp regno = regno
  • -malign-call — align the call
  • -mauto-modify-reg — auto-modify reg, hands-free ✨
  • -mbbit-peephole — bbit peephole 🫣
  • -mno-brcc — no brcc
  • -mcase-vector-pcrel — case vector pcrel
  • -mcompact-casesi — compact casesi, tidy lil thing
  • -mno-cond-exec — no cond exec
  • -mearly-cbranchsi — early cbranchsi, punctual queen 🕐
  • -mexpand-adddi — expand adddi
  • -mindexed-loads — indexed loads
  • -mlra — LRA: on
  • -mlra-priority-none — LRA priority: none
  • -mlra-priority-compact — LRA priority: compact
  • -mlra-priority-noncompact — LRA priority: noncompact
  • -mmillicode — millicode, tiny but mighty
  • -mmixed-code — mixed code 🎨
  • -mq-class — q class
  • -mRcq — Rcq (exact casing, we don't touch it 💅)
  • -mRcw — Rcw, same deal
  • -msize-level=level — size level = level
  • -mtune=cpu — tune for cpu
  • -mmultcost=num — mult cost = num
  • -mcode-density-frame — code density frame
  • -munalign-prob-threshold=probability — unalign prob threshold = probability 🎲
  • -mmpy-option=multo — mpy option = multo
  • -mdiv-rem — div AND rem, doing both 🫶
  • -mcode-density — code density, dense
  • -mll64 — ll64
  • -mfpu=fpu — fpu = fpu
  • -mrf16 — rf16
  • -mbranch-index — branch index 📇

🦋 ARM Options 🦋

  • -mapcs-frame — APCS frame, we ball
  • -mno-apcs-frame — no APCS frame, bye 👋
  • -mabi=name — ABI = name
  • -mapcs-stack-check — APCS stack check ✅
  • -mno-apcs-stack-check — no stack check, living dangerously 😭
  • -mapcs-reentrant — reentrant yes
  • -mno-apcs-reentrant — reentrant no
  • -mgeneral-regs-only — general regs ONLY, no extras 💅
  • -msched-prolog — sched prolog
  • -mno-sched-prolog — no sched prolog
  • -mlittle-endian — little endian 🐣
  • -mbig-endian — BIG endian 🌈
  • -mbe8 — be8
  • -mbe32 — be32
  • -mfloat-abi=name — float ABI = name
  • -mfp16-format=name — fp16 format = name
  • -mthumb-interwork — thumb interwork 🤝
  • -mno-thumb-interwork — no interwork, solo era
  • -mcpu=name — cpu = name
  • -march=name — arch = name
  • -mfpu=name — fpu = name
  • -mtune=name — tune = name
  • -mprint-tune-info — print the tune info, nosy and we love it 🖨️
  • -mstructure-size-boundary=n — structure size boundary = n
  • -mabort-on-noreturn — abort on noreturn, dramatic 💀
  • -mlong-calls — long calls
  • -mno-long-calls — no long calls
  • -msingle-pic-base — single PIC base
  • -mno-single-pic-base — not single PIC base
  • -mpic-register=reg — PIC register = reg
  • -mnop-fun-dllimport — nop fun dllimport (fun! allegedly)
  • -mpoke-function-name — poke function name 👉
  • -mthumb — thumb mode
  • -marm — arm mode
  • -mflip-thumb — FLIP thumb 🤸
  • -mtpcs-frame — tpcs frame
  • -mtpcs-leaf-frame — tpcs LEAF frame 🍃
  • -mcaller-super-interworking — caller super interworking, super indeed
  • -mcallee-super-interworking — callee super interworking, equally super
  • -mtp=name — tp = name
  • -mtls-dialect=dialect — TLS dialect = dialect 🗣️
  • -mword-relocations — word relocations
  • -mfix-cortex-m3-ldrd — fix that cortex-m3 ldrd bug, hero behavior 🦸
  • -mfix-cortex-a57-aes-1742098 — fix for the a57 AES thing, id 1742098
  • -mfix-cortex-a72-aes-1655431 — fix for the a72 AES thing, id 1655431
  • -munaligned-access — unaligned access, chaotic but allowed
  • -mneon-for-64bits — NEON for 64bits ✨
  • -mslow-flash-data — slow flash data, we're patient
  • -masm-syntax-unified — unified asm syntax, one syntax to bind them
  • -mrestrict-it — restrict IT
  • -mverbose-cost-dump — verbose cost dump, yap away 🗣️
  • -mpure-code — pure code 🕊️
  • -mcmse — cmse
  • -mfix-cmse-cve-2021-35465 — fix for CVE-2021-35465, security queen 🔐
  • -mstack-protector-guard=guard — stack protector guard = guard
  • -mstack-protector-guard-offset=offset — the guard's offset = offset
  • -mfdpic — fdpic

🐛 AVR Options 🐛

  • -mmcu=mcu — mcu = mcu, pick your chip
  • -mabsdata — absdata
  • -maccumulate-args — accumulate those args 🧺
  • -mbranch-cost=cost — branch cost = cost
  • -mcall-prologues — call prologues
  • -mgas-isr-prologues — gas isr prologues
  • -mint8 — int8
  • -mdouble=bits — double = bits
  • -mlong-double=bits — long double = bits
  • -mn_flash=size — n_flash = size (underscore stays 💅)
  • -mno-interrupts — no interrupts, quiet mode
  • -mmain-is-OS_task — main IS an OS_task, respect it
  • -mrelax — relax 🧘
  • -mrmw — rmw
  • -mstrict-X — strict X, capital X, don't play
  • -mtiny-stack — tiny stack, small but fierce 🐜
  • -mfract-convert-truncate — fract convert truncate
  • -mshort-calls — short calls
  • -nodevicelib — no devicelib
  • -nodevicespecs — no devicespecs
  • -Waddr-space-convert — a W flag, addr space convert warning
  • -Wmisspelled-isr — warns you misspelled your ISR, so real 😭

💜 Blackfin Options 💜

  • -mcpu=cpu[-sirevision] — cpu = cpu, optional -sirevision in brackets
  • -msim — sim mode
  • -momit-leaf-frame-pointer — omit the leaf frame pointer 🍂
  • -mno-omit-leaf-frame-pointer — don't omit it
  • -mspecld-anomaly — specld anomaly
  • -mno-specld-anomaly — no specld anomaly
  • -mcsync-anomaly — csync anomaly
  • -mno-csync-anomaly — no csync anomaly
  • -mlow-64k — low 64k
  • -mno-low64k — no low 64k
  • -mstack-check-l1 — stack check l1
  • -mid-shared-library — id shared library
  • -mno-id-shared-library — no id shared library
  • -mshared-library-id=n — shared library id = n
  • -mleaf-id-shared-library — leaf id shared library 🍃
  • -mno-leaf-id-shared-library — not that
  • -msep-data — sep data
  • -mno-sep-data — no sep data
  • -mlong-calls — long calls
  • -mno-long-calls — no long calls
  • -mfast-fp — fast fp 🔥
  • -minline-plt — inline plt
  • -mmulticore — multicore, multiple mains of character
  • -mcorea — core A energy
  • -mcoreb — core B energy
  • -msdram — sdram
  • -micplb — icplb

⭐ C6X Options ⭐

  • -mbig-endian — big endian
  • -mlittle-endian — little endian
  • -march=cpu — arch = cpu
  • -msim — sim
  • -msdata=sdata-type — sdata = sdata-type

🎀 CRIS Options 🎀

  • -mcpu=cpu — cpu = cpu
  • -march=cpu — arch = cpu
  • -mtune=cpu — tune = cpu
  • -mmax-stack-frame=n — max stack frame = n
  • -metrax4 — etrax4
  • -metrax100 — etrax100, ten times the etrax
  • -mpdebug — pdebug
  • -mcc-init — cc init
  • -mno-side-effects — no side effects, purity 🕊️
  • -mstack-align — stack align
  • -mdata-align — data align
  • -mconst-align — const align
  • -m32-bit — 32-bit
  • -m16-bit — 16-bit
  • -m8-bit — 8-bit, baby steps
  • -mno-prologue-epilogue — no prologue, no epilogue, no notes
  • -melf — elf 🧝
  • -maout — aout
  • -sim — yes, single dash sim, that's just how it is 💅
  • -sim2 — and sim2, the sequel
  • -mmul-bug-workaround — work around the mul bug, we gotchu
  • -mno-mul-bug-workaround — rawdog the mul bug (kidding, it just turns it off) 😭

🌸 CR16 Options 🌸

  • -mmac — mac
  • -mcr16cplus — cr16cplus
  • -mcr16c — cr16c
  • -msim — sim
  • -mint32 — int32
  • -mbit-ops — bit ops, tiny operations
  • -mdata-model=model — data model = model

🫶 C-SKY Options 🫶

  • -march=arch — arch = arch
  • -mcpu=cpu — cpu = cpu
  • -mbig-endian — big endian
  • -EB — EB, the short way to say it
  • -mlittle-endian — little endian
  • -EL — EL, short and sweet
  • -mhard-float — hard float 💪
  • -msoft-float — soft float 🌸
  • -mfpu=fpu — fpu = fpu
  • -mdouble-float — double float
  • -mfdivdu — fdivdu
  • -mfloat-abi=name — float ABI = name
  • -melrw — elrw
  • -mistack — istack
  • -mmp — mp
  • -mcp — cp
  • -mcache — cache
  • -msecurity — security 🔐
  • -mtrust — trust 🤝
  • -mdsp — dsp
  • -medsp — edsp
  • -mvdsp — vdsp
  • -mdiv — div
  • -msmart — smart 🧠
  • -mhigh-registers — high registers, high key
  • -manchor — anchor ⚓
  • -mpushpop — pushpop, adorable
  • -mmultiple-stld — multiple stld
  • -mconstpool — constpool
  • -mstack-size — stack size (no value here, it just is)
  • -mccrt — ccrt
  • -mbranch-cost=n — branch cost = n
  • -mcse-cc — cse cc
  • -msched-prolog — sched prolog
  • -msim — sim

💀 Darwin Options 💀

Darwin brought its entire friend group, bestie. Brace yourself.

  • -all_load — all load
  • -allowable_client — allowable client
  • -arch — arch
  • -arch_errors_fatal — arch errors fatal, no mercy
  • -arch_only — arch only
  • -bind_at_load — bind at load
  • -bundle — bundle 🎁
  • -bundle_loader — bundle loader
  • -client_name — client name
  • -compatibility_version — compatibility version
  • -current_version — current version
  • -dead_strip — dead strip 💀
  • -dependency-file — dependency file
  • -dylib_file — dylib file
  • -dylinker_install_name — dylinker install name
  • -dynamic — dynamic
  • -dynamiclib — dynamic lib
  • -exported_symbols_list — exported symbols list
  • -filelist — filelist
  • -flat_namespace — flat namespace
  • -force_cpusubtype_ALL — force cpusubtype ALL, capital ALL, do not test her
  • -force_flat_namespace — force flat namespace
  • -headerpad_max_install_names — headerpad max install names
  • -iframework — iframework
  • -image_base — image base
  • -init — init
  • -install_name — install name
  • -keep_private_externs — keep private externs 🤫
  • -multi_module — multi module
  • -multiply_defined — multiply defined
  • -multiply_defined_unused — multiply defined unused
  • -noall_load — no all load, the anti
  • -no_dead_strip_inits_and_terms — no dead strip inits and terms
  • -nofixprebinding — nofixprebinding
  • -nomultidefs — nomultidefs
  • -noprebind — noprebind
  • -noseglinkedit — noseglinkedit
  • -pagezero_size — pagezero size
  • -prebind — prebind
  • -prebind_all_twolevel_modules — prebind all twolevel modules
  • -private_bundle — private bundle 🎁
  • -read_only_relocs — read only relocs
  • -sectalign — sectalign
  • -sectobjectsymbols — sectobjectsymbols
  • -whyload — whyload, honestly relatable name 😭
  • -seg1addr — seg1addr
  • -sectcreate — sectcreate
  • -sectobjectsymbols — yep, listed a second time in the original, we keep it exactly as-is 🙈
  • -sectorder — sectorder
  • -segaddr — segaddr
  • -segs_read_only_addr — segs read only addr
  • -segs_read_write_addr — segs read write addr
  • -seg_addr_table — seg addr table
  • -seg_addr_table_filename — seg addr table filename
  • -seglinkedit — seglinkedit
  • -segprot — segprot
  • -segs_read_only_addr — again, third appearance overall, untouched 💅
  • -segs_read_write_addr — and this one repeats too, we don't question the ancestors
  • -single_module — single module
  • -static — static
  • -sub_library — sub library
  • -sub_umbrella — sub umbrella ☂️
  • -twolevel_namespace — twolevel namespace
  • -umbrella — umbrella ☂️
  • -undefined — undefined
  • -unexported_symbols_list — unexported symbols list
  • -weak_reference_mismatches — weak reference mismatches
  • -whatsloaded — whatsloaded
  • -F — capital F, that's it, that's the flag
  • -gused — gused
  • -gfull — gfull
  • -mmacosx-version-min=version — macosx version min = version
  • -mkernel — kernel
  • -mone-byte-bool — one byte bool, smol bool 🐣

🧮 DEC Alpha Options 🧮

  • -mno-fp-regs — no fp regs
  • -msoft-float — soft float
  • -mieee — ieee, standards girlie
  • -mieee-with-inexact — ieee WITH inexact, extra
  • -mieee-conformant — ieee conformant, fully compliant queen 👑
  • -mfp-trap-mode=mode — fp trap mode = mode
  • -mfp-rounding-mode=mode — fp rounding mode = mode
  • -mtrap-precision=mode — trap precision = mode
  • -mbuild-constants — build constants
  • -mcpu=cpu-type — cpu = cpu-type
  • -mtune=cpu-type — tune = cpu-type
  • -mbwx — bwx
  • -mmax — max
  • -mfix — fix
  • -mcix — cix
  • -mfloat-vax — float vax
  • -mfloat-ieee — float ieee
  • -mexplicit-relocs — explicit relocs, say it with your chest
  • -msmall-data — small data
  • -mlarge-data — large data
  • -msmall-text — small text
  • -mlarge-text — large text
  • -mmemory-latency=time — memory latency = time ⏱️

🌈 eBPF Options 🌈

  • -mbig-endian — big endian
  • -mlittle-endian — little endian
  • -mkernel=version — kernel = version
  • -mframe-limit=bytes — frame limit = bytes
  • -mxbpf — xbpf
  • -mco-re — co-re
  • -mno-co-re — no co-re
  • -mjmpext — jmpext
  • -mjmp32 — jmp32
  • -malu32 — alu32
  • -mcpu=version — cpu = version

🍓 FR30 Options 🍓

  • -msmall-model — small model, smol model
  • -mno-lsim — no lsim

🧚 FT32 Options 🧚

  • -msim — sim
  • -mlra — lra
  • -mnodiv — no div
  • -mft32b — ft32b
  • -mcompress — compress 🗜️
  • -mnopm — nopm

💅 FRV Options 💅

  • -mgpr-32 — gpr 32
  • -mgpr-64 — gpr 64
  • -mfpr-32 — fpr 32
  • -mfpr-64 — fpr 64
  • -mhard-float — hard float
  • -msoft-float — soft float
  • -malloc-cc — alloc cc
  • -mfixed-cc — fixed cc
  • -mdword — dword
  • -mno-dword — no dword
  • -mdouble — double
  • -mno-double — no double
  • -mmedia — media 🎬
  • -mno-media — no media
  • -mmuladd — muladd
  • -mno-muladd — no muladd
  • -mfdpic — fdpic
  • -minline-plt — inline plt
  • -mgprel-ro — gprel ro
  • -multilib-library-pic — multilib library pic
  • -mlinked-fp — linked fp
  • -mlong-calls — long calls
  • -malign-labels — align labels
  • -mlibrary-pic — library pic
  • -macc-4 — acc 4
  • -macc-8 — acc 8
  • -mpack — pack
  • -mno-pack — no pack
  • -mno-eflags — no eflags
  • -mcond-move — cond move
  • -mno-cond-move — no cond move
  • -moptimize-membar — optimize membar
  • -mno-optimize-membar — no optimize membar
  • -mscc — scc
  • -mno-scc — no scc
  • -mcond-exec — cond exec
  • -mno-cond-exec — no cond exec
  • -mvliw-branch — vliw branch
  • -mno-vliw-branch — no vliw branch
  • -mmulti-cond-exec — multi cond exec
  • -mno-multi-cond-exec — no multi cond exec
  • -mnested-cond-exec — nested cond exec
  • -mno-nested-cond-exec — no nested cond exec
  • -mtomcat-stats — tomcat stats 🐱, no further questions
  • -mTLS — capital TLS
  • -mtls — lowercase tls, they're different, bestie
  • -mcpu=cpu — cpu = cpu

🐧 GNU/Linux Options 🐧

  • -mglibc — glibc girlie
  • -muclibc — uclibc
  • -mmusl — musl, alpine icon 🏔️
  • -mbionic — bionic
  • -mandroid — android 🤖
  • -tno-android-cc — no android cc
  • -tno-android-ld — no android ld

🌸 H8/300 Options 🌸

  • -mrelax — relax 🧘
  • -mh — h
  • -ms — s
  • -mn — n
  • -mexr — exr
  • -mno-exr — no exr
  • -mint32 — int32
  • -malign-300 — align 300

👑 HPPA Options 👑

  • -march=architecture-type — arch = architecture-type
  • -mcaller-copies — caller copies
  • -mdisable-fpregs — disable fpregs
  • -mdisable-indexing — disable indexing
  • -mfast-indirect-calls — fast indirect calls ⚡
  • -mgas — gas
  • -mgnu-ld — gnu ld
  • -mhp-ld — hp ld
  • -mfixed-range=register-range — fixed range = register-range
  • -mjump-in-delay — jump in delay
  • -mlinker-opt — linker opt
  • -mlong-calls — long calls
  • -mlong-load-store — long load store
  • -mno-disable-fpregs — don't disable fpregs
  • -mno-disable-indexing — don't disable indexing
  • -mno-fast-indirect-calls — no fast indirect calls
  • -mno-gas — no gas
  • -mno-jump-in-delay — no jump in delay
  • -mno-long-load-store — no long load store
  • -mno-portable-runtime — no portable runtime
  • -mno-soft-float — no soft float
  • -mno-space-regs — no space regs
  • -msoft-float — soft float
  • -mpa-risc-1-0 — pa risc 1.0
  • -mpa-risc-1-1 — pa risc 1.1
  • -mpa-risc-2-0 — pa risc 2.0
  • -mportable-runtime — portable runtime
  • -mschedule=cpu-type — schedule = cpu-type
  • -mspace-regs — space regs 🚀
  • -msio — sio
  • -mwsio — wsio
  • -munix=unix-std — unix = unix-std
  • -nolibdld — no libdld
  • -static — static
  • -threads — threads 🧵

💜 IA-64 Options 💜

  • -mbig-endian — big endian
  • -mlittle-endian — little endian
  • -mgnu-as — gnu as
  • -mgnu-ld — gnu ld
  • -mno-pic — no pic
  • -mvolatile-asm-stop — volatile asm stop
  • -mregister-names — register names
  • -msdata — sdata
  • -mno-sdata — no sdata
  • -mconstant-gp — constant gp
  • -mauto-pic — auto pic
  • -mfused-madd — fused madd 🔥
  • -minline-float-divide-min-latency — inline float divide, min latency
  • -minline-float-divide-max-throughput — inline float divide, max throughput
  • -mno-inline-float-divide — no inline float divide
  • -minline-int-divide-min-latency — inline int divide, min latency
  • -minline-int-divide-max-throughput — inline int divide, max throughput
  • -mno-inline-int-divide — no inline int divide
  • -minline-sqrt-min-latency — inline sqrt, min latency
  • -minline-sqrt-max-throughput — inline sqrt, max throughput
  • -mno-inline-sqrt — no inline sqrt
  • -mdwarf2-asm — dwarf2 asm
  • -mearly-stop-bits — early stop bits
  • -mfixed-range=register-range — fixed range = register-range
  • -mtls-size=tls-size — tls size = tls-size
  • -mtune=cpu-type — tune = cpu-type
  • -milp32 — ilp32
  • -mlp64 — lp64
  • -msched-br-data-spec — sched br data spec
  • -msched-ar-data-spec — sched ar data spec
  • -msched-control-spec — sched control spec
  • -msched-br-in-data-spec — sched br in data spec
  • -msched-ar-in-data-spec — sched ar in data spec
  • -msched-in-control-spec — sched in control spec
  • -msched-spec-ldc — sched spec ldc
  • -msched-spec-control-ldc — sched spec control ldc
  • -msched-prefer-non-data-spec-insns — prefer non data spec insns
  • -msched-prefer-non-control-spec-insns — prefer non control spec insns
  • -msched-stop-bits-after-every-cycle — stop bits after every cycle, every single one 🌀
  • -msched-count-spec-in-critical-path — count spec in critical path
  • -msel-sched-dont-check-control-spec — sel sched, don't check control spec
  • -msched-fp-mem-deps-zero-cost — sched fp mem deps zero cost
  • -msched-max-memory-insns-hard-limit — max memory insns, HARD limit 🚫
  • -msched-max-memory-insns=max-insns — max memory insns = max-insns

🎀 LM32 Options 🎀

  • -mbarrel-shift-enabled — barrel shift enabled
  • -mdivide-enabled — divide enabled
  • -mmultiply-enabled — multiply enabled
  • -msign-extend-enabled — sign extend enabled
  • -muser-enabled — user enabled

🦋 LoongArch Options 🦋

  • -march=cpu-type — arch = cpu-type
  • -mtune=cpu-type — tune = cpu-type
  • -mabi=base-abi-type — abi = base-abi-type
  • -mfpu=fpu-type — fpu = fpu-type
  • -msoft-float — soft float
  • -msingle-float — single float
  • -mdouble-float — double float
  • -mbranch-cost=n — branch cost = n
  • -mcheck-zero-division — check zero division, safety first 🚦
  • -mno-check-zero-division — don't check, chaos era
  • -mcond-move-int — cond move int
  • -mno-cond-move-int — no cond move int
  • -mcond-move-float — cond move float
  • -mno-cond-move-float — no cond move float
  • -memcpy — memcpy, the icon
  • -mno-memcpy — no memcpy
  • -mstrict-align — strict align
  • -mno-strict-align — no strict align
  • -mmax-inline-memcpy-size=n — max inline memcpy size = n
  • -mcmodel=code-model — cmodel = code-model

🍓 M32R/D Options 🍓

  • -m32r2 — 32r2
  • -m32rx — 32rx
  • -m32r — 32r, the original
  • -mdebug — debug 🐞
  • -malign-loops — align loops
  • -mno-align-loops — no align loops
  • -missue-rate=number — issue rate = number
  • -mbranch-cost=number — branch cost = number
  • -mmodel=code-size-model-type — model = code-size-model-type
  • -msdata=sdata-type — sdata = sdata-type
  • -mno-flush-func — no flush func
  • -mflush-func=name — flush func = name
  • -mno-flush-trap — no flush trap
  • -mflush-trap=number — flush trap = number
  • -G num — capital G, then num

🧚 M32C Options 🧚

  • -mcpu=cpu — cpu = cpu
  • -msim — sim
  • -memregs=number — emregs = number

💅 M680x0 Options 💅

The whole 68k family reunion, bestie 😭

  • -march=arch — arch = arch
  • -mcpu=cpu — cpu = cpu
  • -mtune=tune — tune = tune
  • -m68000 — 68000
  • -m68020 — 68020
  • -m68020-40 — 68020-40
  • -m68020-60 — 68020-60
  • -m68030 — 68030
  • -m68040 — 68040
  • -m68060 — 68060
  • -mcpu32 — cpu32
  • -m5200 — 5200
  • -m5206e — 5206e
  • -m528x — 528x
  • -m5307 — 5307
  • -m5407 — 5407
  • -mcfv4e — cfv4e
  • -mbitfield — bitfield
  • -mno-bitfield — no bitfield
  • -mc68000 — c68000
  • -mc68020 — c68020
  • -mnobitfield — no bitfield, the other spelling
  • -mrtd — rtd
  • -mno-rtd — no rtd
  • -mdiv — div
  • -mno-div — no div
  • -mshort — short
  • -mno-short — no short
  • -mhard-float — hard float
  • -m68881 — 68881
  • -msoft-float — soft float
  • -mpcrel — pcrel
  • -malign-int — align int
  • -mstrict-align — strict align
  • -msep-data — sep data
  • -mno-sep-data — no sep data
  • -mshared-library-id=n — shared library id = n
  • -mid-shared-library — id shared library
  • -mno-id-shared-library — no id shared library
  • -mxgot — xgot
  • -mno-xgot — no xgot
  • -mlong-jump-table-offsets — long jump table offsets

🫶 MCore Options 🫶

  • -mhardlit — hardlit
  • -mno-hardlit — no hardlit
  • -mdiv — div
  • -mno-div — no div
  • -mrelax-immediates — relax immediates 🧘
  • -mno-relax-immediates — no relax immediates
  • -mwide-bitfields — wide bitfields
  • -mno-wide-bitfields — no wide bitfields
  • -m4byte-functions — 4byte functions
  • -mno-4byte-functions — no 4byte functions
  • -mcallgraph-data — callgraph data
  • -mno-callgraph-data — no callgraph data
  • -mslow-bytes — slow bytes 🐌
  • -mno-slow-bytes — no slow bytes
  • -mno-lsim — no lsim
  • -mlittle-endian — little endian
  • -mbig-endian — big endian
  • -m210 — 210
  • -m340 — 340
  • -mstack-increment — stack increment

🌸 MeP Options 🌸

okay bestie, MeP is serving a whole buffet of flags, and you know we're gonna list every single one 💅

  • -mabsdiff
  • -mall-opts
  • -maverage
  • -mbased=n
  • -mbitops
  • -mc=n
  • -mclip
  • -mconfig=name
  • -mcop
  • -mcop32
  • -mcop64
  • -mivc2
  • -mdc
  • -mdiv
  • -meb
  • -mel
  • -mio-volatile
  • -ml
  • -mleadz
  • -mm
  • -mminmax
  • -mmult
  • -mno-opts
  • -mrepeat
  • -ms
  • -msatur
  • -msdram
  • -msim
  • -msimnovec
  • -mtf
  • -mtiny=n

🦋 MicroBlaze Options 🦋

MicroBlaze said "let me give you options" and honestly? iconic. Here's the full set, no cap:

  • -msoft-float
  • -mhard-float
  • -msmall-divides
  • -mcpu=cpu
  • -mmemcpy
  • -mxl-soft-mul
  • -mxl-soft-div
  • -mxl-barrel-shift
  • -mxl-pattern-compare
  • -mxl-stack-check
  • -mxl-gp-opt
  • -mno-clearbss
  • -mxl-multiply-high
  • -mxl-float-convert
  • -mxl-float-sqrt
  • -mbig-endian
  • -mlittle-endian
  • -mxl-reorder
  • -mxl-mode-app-model
  • -mpic-data-is-text-relative

💜 MIPS Options 💜

MIPS has a lot to say. Like, a lot a lot. But we're gonna get through it together, bestie. Every. Single. Flag. 💖

  • -EL
  • -EB
  • -march=arch
  • -mtune=arch
  • -mips1
  • -mips2
  • -mips3
  • -mips4
  • -mips32
  • -mips32r2
  • -mips32r3
  • -mips32r5
  • -mips32r6
  • -mips64
  • -mips64r2
  • -mips64r3
  • -mips64r5
  • -mips64r6
  • -mips16
  • -mno-mips16
  • -mflip-mips16
  • -minterlink-compressed
  • -mno-interlink-compressed
  • -minterlink-mips16
  • -mno-interlink-mips16
  • -mabi=abi
  • -mabicalls
  • -mno-abicalls
  • -mshared
  • -mno-shared
  • -mplt
  • -mno-plt
  • -mxgot
  • -mno-xgot
  • -mgp32
  • -mgp64
  • -mfp32
  • -mfpxx
  • -mfp64
  • -mhard-float
  • -msoft-float
  • -mno-float
  • -msingle-float
  • -mdouble-float
  • -modd-spreg
  • -mno-odd-spreg
  • -mabs=mode
  • -mnan=encoding
  • -mdsp
  • -mno-dsp
  • -mdspr2
  • -mno-dspr2
  • -mmcu
  • -mmno-mcu
  • -meva
  • -mno-eva
  • -mvirt
  • -mno-virt
  • -mxpa
  • -mno-xpa
  • -mcrc
  • -mno-crc
  • -mginv
  • -mno-ginv
  • -mmicromips
  • -mno-micromips
  • -mmsa
  • -mno-msa
  • -mloongson-mmi
  • -mno-loongson-mmi
  • -mloongson-ext
  • -mno-loongson-ext
  • -mloongson-ext2
  • -mno-loongson-ext2
  • -mfpu=fpu-type
  • -msmartmips
  • -mno-smartmips
  • -mpaired-single
  • -mno-paired-single
  • -mdmx
  • -mno-mdmx
  • -mips3d
  • -mno-mips3d
  • -mmt
  • -mno-mt
  • -mllsc
  • -mno-llsc
  • -mlong64
  • -mlong32
  • -msym32
  • -mno-sym32
  • -Gnum
  • -mlocal-sdata
  • -mno-local-sdata
  • -mextern-sdata
  • -mno-extern-sdata
  • -mgpopt
  • -mno-gopt
  • -membedded-data
  • -mno-embedded-data
  • -muninit-const-in-rodata
  • -mno-uninit-const-in-rodata
  • -mcode-readable=setting
  • -msplit-addresses
  • -mno-split-addresses
  • -mexplicit-relocs
  • -mno-explicit-relocs
  • -mcheck-zero-division
  • -mno-check-zero-division
  • -mdivide-traps
  • -mdivide-breaks
  • -mload-store-pairs
  • -mno-load-store-pairs
  • -munaligned-access
  • -mno-unaligned-access
  • -mmemcpy
  • -mno-memcpy
  • -mlong-calls
  • -mno-long-calls
  • -mmad
  • -mno-mad
  • -mimadd
  • -mno-imadd
  • -mfused-madd
  • -mno-fused-madd
  • -nocpp
  • -mfix-24k
  • -mno-fix-24k
  • -mfix-r4000
  • -mno-fix-r4000
  • -mfix-r4400
  • -mno-fix-r4400
  • -mfix-r5900
  • -mno-fix-r5900
  • -mfix-r10000
  • -mno-fix-r10000
  • -mfix-rm7000
  • -mno-fix-rm7000
  • -mfix-vr4120
  • -mno-fix-vr4120
  • -mfix-vr4130
  • -mno-fix-vr4130
  • -mfix-sb1
  • -mno-fix-sb1
  • -mflush-func=func
  • -mno-flush-func
  • -mbranch-cost=num
  • -mbranch-likely
  • -mno-branch-likely
  • -mcompact-branches=policy
  • -mfp-exceptions
  • -mno-fp-exceptions
  • -mvr4130-align
  • -mno-vr4130-align
  • -msynci
  • -mno-synci
  • -mlxc1-sxc1
  • -mno-lxc1-sxc1
  • -mmadd4
  • -mno-madd4
  • -mrelax-pic-calls
  • -mno-relax-pic-calls
  • -mmcount-ra-address
  • -mframe-header-opt
  • -mno-frame-header-opt

🎀 MMIX Options 🎀

MMIX is giving "I have a very specific set of skills" energy. Here are the flags:

  • -mlibfuncs
  • -mno-libfuncs
  • -mepsilon
  • -mno-epsilon
  • -mabi=gnu
  • -mabi=mmixware
  • -mzero-extend
  • -mknuthdiv
  • -mtoplevel-symbols
  • -melf
  • -mbranch-predict
  • -mno-branch-predict
  • -mbase-addresses
  • -mno-base-addresses
  • -msingle-exit
  • -mno-single-exit

✨ MN10300 Options ✨

MN10300 said "let me just drop these here" and honestly? we're here for it.

  • -mmult-bug
  • -mno-mult-bug
  • -mno-am33
  • -mam33
  • -mam33-2
  • -mam34
  • -mtune=cpu-type
  • -mreturn-pointer-on-d0
  • -mno-crt0
  • -mrelax
  • -mliw
  • -msetlb

🫶 Moxie Options 🫶

Moxie is a whole vibe. Four flags. That's it. Iconic.

  • -meb
  • -mel
  • -mmul.x
  • -mno-crt0

🔥 MSP430 Options 🔥

MSP430 came to play with a whole list. Bestie, grab a snack.

  • -msim
  • -masm-hex
  • -mmcu=
  • -mcpu=
  • -mlarge
  • -msmall
  • -mrelax
  • -mwarn-mcu
  • -mcode-region=
  • -mdata-region=
  • -msilicon-errata=
  • -msilicon-errata-warn=
  • -mhwmult=
  • -minrt
  • -mtiny-printf
  • -mmax-inline-shift=

🌈 NDS32 Options 🌈

NDS32 is serving options with a side of "we have both big and little endian, we contain multitudes."

  • -mbig-endian
  • -mlittle-endian
  • -mreduced-regs
  • -mfull-regs
  • -mcmov
  • -mno-cmov
  • -mext-perf
  • -mno-ext-perf
  • -mext-perf2
  • -mno-ext-perf2
  • -mext-string
  • -mno-ext-string
  • -mv3push
  • -mno-v3push
  • -m16bit
  • -mno-16bit
  • -misr-vector-size=num
  • -mcache-block-size=num
  • -march=arch
  • -mcmodel=code-model
  • -mctor-dtor
  • -mrelax

🦄 Nios II Options 🦄

Nios II is here with a very thorough list. Some of these have =N or =name, so pay attention, bestie.

  • -G num
  • -mgpopt=option
  • -mgpopt
  • -mno-gpopt
  • -mgprel-sec=regexp
  • -mr0rel-sec=regexp
  • -mel
  • -meb
  • -mno-bypass-cache
  • -mbypass-cache
  • -mno-cache-volatile
  • -mcache-volatile
  • -mno-fast-sw-div
  • -mfast-sw-div
  • -mhw-mul
  • -mno-hw-mul
  • -mhw-mulx
  • -mno-hw-mulx
  • -mno-hw-div
  • -mhw-div
  • -mcustom-insn=N
  • -mno-custom-insn
  • -mcustom-fpu-cfg=name
  • -mhal
  • -msmallc
  • -msys-crt0=name
  • -msys-lib=name
  • -march=arch
  • -mbmx
  • -mno-bmx
  • -mcdx
  • -mno-cdx

👑 Nvidia PTX Options 👑

Nvidia PTX keeps it short and sweet. Three flags, all business.

  • -m64
  • -mmainkernel
  • -moptimize

🧚 OpenRISC Options 🧚

OpenRISC is open for business with this list. Let's go.

  • -mboard=name
  • -mnewlib
  • -mhard-mul
  • -mhard-div
  • -msoft-mul
  • -msoft-div
  • -msoft-float
  • -mhard-float
  • -mdouble-float
  • -munordered-float
  • -mcmov
  • -mror
  • -mrori
  • -msext
  • -msfimm
  • -mshftimm
  • -mcmodel=code-model

💀 PDP-11 Options 💀

PDP-11 is vintage but still serving looks. Here's the full menu.

  • -mfpu
  • -msoft-float
  • -mac0
  • -mno-ac0
  • -m40
  • -m45
  • -m10
  • -mint32
  • -mno-int16
  • -mint16
  • -mno-int32
  • -msplit
  • -munix-asm
  • -mdec-asm
  • -mgnu-asm
  • -mlra

🍓 picoChip Options 🍓

picoChip has a small but mighty list. No cap.

  • -mae=ae_type
  • -mvliw-lookahead=N
  • -msymbol-as-address
  • -mno-inefficient-warnings

⭐ PowerPC Options ⭐

bestie, just a heads up: this one says See RS/6000 and PowerPC Options. so scroll down for the real tea 💅

🙈 PRU Options 🙈

PRU is here with a handful of flags. Short and sweet.

  • -mmcu=mcu
  • -minrt
  • -mno-relax
  • -mloop
  • -mabi=variant

🌸 RISC-V Options 🌸

RISC-V is the moment. Here's the full list, and yes, we're including every single one.

  • -mbranch-cost=N-instruction
  • -mplt
  • -mno-plt
  • -mabi=ABI-string
  • -mfdiv
  • -mno-fdiv
  • -mdiv
  • -mno-div
  • -misa-spec=ISA-spec-string
  • -march=ISA-string
  • -mtune=processor-string
  • -mpreferred-stack-boundary=num
  • -msmall-data-limit=N-bytes
  • -msave-restore
  • -mno-save-restore
  • -mshorten-memrefs
  • -mno-shorten-memrefs
  • -mstrict-align
  • -mno-strict-align
  • -mcmodel=medlow
  • -mcmodel=medany
  • -mexplicit-relocs
  • -mno-explicit-relocs
  • -mrelax
  • -mno-relax
  • -mriscv-attribute
  • -mmo-riscv-attribute
  • -malign-data=type
  • -mbig-endian
  • -mlittle-endian
  • -mstack-protector-guard=guard
  • -mstack-protector-guard-reg=reg
  • -mstack-protector-guard-offset=offset

🎀 RL78 Options 🎀

RL78 has options for days. Let's get into it.

  • -msim
  • -mmul=none
  • -mmul=g13
  • -mmul=g14
  • -mallregs
  • -mcpu=g10
  • -mcpu=g13
  • -mcpu=g14
  • -mg10
  • -mg13
  • -mg14
  • -m64bit-doubles
  • -m32bit-doubles
  • -msave-mduc-in-interrupts

💜 RS/6000 and PowerPC Options 💜

Okay bestie, this is the big one. RS/6000 and PowerPC came to serve. There are so many flags here, but we're listing every single one. No skipping. 💅

  • -mcpu=cpu-type
  • -mtune=cpu-type
  • -mcmodel=code-model
  • -mpowerpc64
  • -maltivec
  • -mno-altivec
  • -mpowerpc-gpopt
  • -mno-powerpc-gpopt
  • -mpowerpc-gfxopt
  • -mno-powerpc-gfxopt
  • -mmfcrf
  • -mno-mfcrf
  • -mpopcntb
  • -mno-popcntb
  • -mpopcntd
  • -mno-popcntd
  • -mfprnd
  • -mno-fprnd
  • -mcmpb
  • -mno-cmpb
  • -mhard-dfp
  • -mno-hard-dfp
  • -mfull-toc
  • -mminimal-toc
  • -mno-fp-in-toc
  • -mno-sum-in-toc
  • -m64
  • -m32
  • -mxl-compat
  • -mno-xl-compat
  • -mpe
  • -malign-power
  • -malign-natural
  • -msoft-float
  • -mhard-float
  • -mmultiple
  • -mno-multiple
  • -mupdate
  • -mno-update
  • -mavoid-indexed-addresses
  • -mno-avoid-indexed-addresses
  • -mfused-madd
  • -mno-fused-madd
  • -mbit-align
  • -mno-bit-align
  • -mstrict-align
  • -mno-strict-align
  • -mrelocatable
  • -mno-relocatable
  • -mrelocatable-lib
  • -mno-relocatable-lib
  • -mtoc
  • -mno-toc
  • -mlittle
  • -mlittle-endian
  • -mbig
  • -mbig-endian
  • -mdynamic-no-pic
  • -mswdiv
  • -msingle-pic-base
  • -mprioritize-restricted-insns=priority
  • -msched-costly-dep=dependence_type
  • -minsert-sched-nops=scheme
  • -mcall-aixdesc
  • -mcall-eabi
  • -mcall-freebsd
  • -mcall-linux
  • -mcall-netbsd
  • -mcall-openbsd
  • -mcall-sysv
  • -mcall-sysv-eabi
  • -mcall-sysv-noeabi
  • -mtraceback=traceback_type
  • -maix-struct-return
  • -msvr4-struct-return
  • -mabi=abi-type
  • -msecure-plt
  • -mbss-plt
  • -mlongcall
  • -mno-longcall
  • -mpltseq
  • -mno-pltseq
  • -mblock-move-inline-limit=num
  • -mblock-compare-inline-limit=num
  • -mblock-compare-inline-loop-limit=num
  • -mno-block-ops-unaligned-vsx
  • -mstring-compare-inline-limit=num
  • -misel
  • -mno-isel
  • -mvrsave
  • -mno-vrsave
  • -mmulhw
  • -mno-mulhw
  • -mdlmzb
  • -mno-dlmzb
  • -mprototype
  • -mno-prototype
  • -msim
  • -mmvme
  • -mads
  • -myellowknife
  • -memb
  • -msdata
  • -msdata=opt
  • -mreadonly-in-sdata
  • -mvxworks
  • -G num
  • -mrecip
  • -mrecip=opt
  • -mno-recip
  • -mrecip-precision
  • -mno-recip-precision
  • -mveclibabi=type
  • -mfriz
  • -mno-friz
  • -mpointers-to-nested-functions
  • -mno-pointers-to-nested-functions
  • -msave-toc-indirect
  • -mno-save-toc-indirect
  • -mpower8-fusion
  • -mno-mpower8-fusion
  • -mpower8-vector
  • -mno-power8-vector
  • -mcrypto
  • -mno-crypto
  • -mhtm
  • -mno-htm
  • -mquad-memory
  • -mno-quad-memory
  • -mquad-memory-atomic
  • -mno-quad-memory-atomic
  • -mcompat-align-parm
  • -mno-compat-align-parm
  • -mfloat128
  • -mno-float128
  • -mfloat128-hardware
  • -mno-float128-hardware
  • -mgnu-attribute
  • -mno-gnu-attribute
  • -mstack-protector-guard=guard
  • -mstack-protector-guard-reg=reg
  • -mstack-protector-guard-offset=offset
  • -mprefixed
  • -mno-prefixed
  • -mpcrel
  • -mno-pcrel
  • -mmma
  • -mno-mmma
  • -mrop-protect
  • -mno-rop-protect
  • -mprivileged
  • -mno-privileged

🌟 RX Options 🌟

RX is here with a mix of old and new. Let's go.

  • -m64bit-doubles
  • -m32bit-doubles
  • -fpu
  • -nofpu
  • -mcpu=
  • -mbig-endian-data
  • -mlittle-endian-data
  • -msmall-data
  • -msim
  • -mno-sim
  • -mas100-syntax
  • -mno-as100-syntax
  • -mrelax
  • -mmax-constant-size=
  • -mint-register=
  • -mpid
  • -mallow-string-insns
  • -mno-allow-string-insns
  • -mjsr
  • -mno-warn-multiple-fast-interrupts
  • -msave-acc-in-interrupts

💎 S/390 and zSeries Options 💎

S/390 and zSeries are giving mainframe energy. Here's the full list.

  • -mtune=cpu-type
  • -march=cpu-type
  • -mhard-float
  • -msoft-float
  • -mhard-dfp
  • -mno-hard-dfp
  • -mlong-double-64
  • -mlong-double-128
  • -mbackchain
  • -mno-backchain
  • -mpacked-stack
  • -mno-packed-stack
  • -msmall-exec
  • -mno-small-exec
  • -mmvcle
  • -mno-mvcle
  • -m64
  • -m31
  • -mdebug
  • -mno-debug
  • -mesa
  • -mzarch
  • -mhtm
  • -mvx
  • -mzvector
  • -mtpf-trace
  • -mno-tpf-trace
  • -mtpf-trace-skip
  • -mno-tpf-trace-skip
  • -mfused-madd
  • -mno-fused-madd
  • -mwarn-framesize
  • -mwarn-dynamicstack
  • -mstack-size
  • -mstack-guard
  • -mhotpatch=halfwords,halfwords

🎵 Score Options 🎵

Score is keeping it short. Eight flags, all here.

  • -meb
  • -mel
  • -mnhwloop
  • -muls
  • -mmac
  • -mscore5
  • -mscore5u
  • -mscore7
  • -mscore7d

🌈 SH Options 🌈

SH has a lot going on. But we're listing every single flag because that's what besties do.

  • -m1
  • -m2
  • -m2e
  • -m2a-nofpu
  • -m2a-single-only
  • -m2a-single
  • -m2a
  • -m3
  • -m3e
  • -m4-nofpu
  • -m4-single-only
  • -m4-single
  • -m4
  • -m4a-nofpu
  • -m4a-single-only
  • -m4a-single
  • -m4a
  • -m4al
  • -mb
  • -ml
  • -mdalign
  • -mrelax
  • -mbigtable
  • -mfmovd
  • -mrenesas
  • -mno-renesas
  • -mnomacsave
  • -mieee
  • -mno-ieee
  • -mbitops
  • -misize
  • -minline-ic_invalidate
  • -mpadstruct
  • -mprefergot
  • -musermode
  • -multcost=number
  • -mdiv=strategy
  • -mdivsi3_libfunc=name
  • -mfixed-range=register-range
  • -maccumulate-outgoing-args
  • -matomic-model=atomic-model
  • -mbranch-cost=num
  • -mzdcbranch
  • -mno-zdcbranch
  • -mcbranch-force-delay-slot
  • -mfused-madd
  • -mno-fused-madd
  • -mfsca
  • -mno-fsca
  • -mfsrra
  • -mno-fsrra
  • -mpretend-cmove
  • -mtas

☀️ Solaris 2 Options ☀️

Solaris 2 is the last stop on this architecture tour. Here are the flags, bestie.

  • -mclear-hwcap
  • -mno-clear-hwcap
  • -mimpure-text
  • -mno-impure-text
  • -pthreads

ok so like — we've covered the normal human options, and now we're in the machine-dependent corner of the menu: the flags that only exist for specific chips. Heads up though, at this point in the page these are literally just names — no explanations attached to any of them — so I'm listing every single one exactly as written. No inventing, no skipping 💅

🛸 SPARC Options 🛸

SPARC besties, this is your whole flag selection. The first two take a cpu-type, one takes a code-model, one takes a mem-model, and then there's a whole pile of on/off pairs:

-mcpu=cpu-type -mtune=cpu-type -mcmodel=code-model
-mmemory-model=mem-model -m32  -m64  -mapp-regs  -mno-app-regs
-mfaster-structs  -mno-faster-structs  -mflat  -mno-flat -mfpu
-mno-fpu  -mhard-float  -msoft-float -mhard-quad-float
-msoft-quad-float -mstack-bias  -mno-stack-bias -mstd-struct-return
-mno-std-struct-return -munaligned-doubles  -mno-unaligned-doubles
-muser-mode  -mno-user-mode -mv8plus  -mno-v8plus  -mvis  -mno-vis
-mvis2  -mno-vis2  -mvis3  -mno-vis3 -mvis4  -mno-vis4  -mvis4b
-mno-vis4b -mcbcond  -mno-cbcond  -mfmaf  -mno-fmaf  -mfsmuld
-mno-fsmuld -mpopc  -mno-popc  -msubxc  -mno-subxc -mfix-at697f
-mfix-ut699  -mfix-ut700  -mfix-gr712rc -mlra  -mno-lra

the -mfix- ones lowkey look like they're fixing specific chips, and the -mno- twins are the off switch for each thing. that's all this page gives us, so that's all you get 🫶


🧾 System V Options 🧾

  • -Qy
  • -Qn
  • -YP,paths
  • -Ym,dir

four of them. two take a comma and an argument, two don't. that's the whole vibe ✨

🧩 TILE-Gx Options 🧩

-mcpu=CPU  -m32  -m64  -mbig-endian  -mlittle-endian
-mcmodel=code-model

short and sweet, one CPU placeholder in all caps for some reason, and both endianness flags are right there 😌

🧩 TILEPro Options 🧩

-mcpu=cpu  -m32

that's it. that's the list. icon behaviour honestly 💀

🌱 V850 Options 🌱

-mlong-calls  -mno-long-calls  -mep  -mno-ep
-mprolog-function  -mno-prolog-function  -mspace -mtda=n  -msda=n
-mzda=n -mapp-regs  -mno-app-regs -mdisable-callt
-mno-disable-callt -mv850e2v3  -mv850e2  -mv850e1  -mv850es -mv850e
-mv850  -mv850e3v5 -mloop -mrelax -mlong-jumps -msoft-float
-mhard-float -mgcc-abi -mrh850-abi -mbig-switch

the -m?da=n trio (-mtda=n, -msda=n, -mzda=n) all take an n, and then there's a whole little ladder of chip versions from -mv850 up through -mv850e3v5 💜

🪐 VAX Options 🪐

  • -mg
  • -mgnu
  • -munix
  • -mlra

🔭 Visium Options 🔭

-mdebug  -msim  -mfpu  -mno-fpu  -mhard-float
-msoft-float -mcpu=cpu-type  -mtune=cpu-type  -msv-mode  -muser-mode

note the cpu-type on -mcpu= and -mtune= — same placeholder name as SPARC, cute 🌸

🗄️ VMS Options 🗄️

  • -mvms-return-codes
  • -mdebug-main=prefix — takes a prefix
  • -mmalloc64
  • -mpointer-size=size — takes a size

🐚 VxWorks Options 🐚

  • -mrtp
  • -non-static
  • -Bstatic
  • -Bdynamic
  • -Xbind-lazy
  • -Xbind-now

not all of these start with -m, bestie, don't @ me, that's literally how they're written 👑


💻 x86 Options 💻

ok so. this is the list. it is enormous. it's giving pokémon dex, it's giving limited-edition sticker sheet 😭. every single one is here, in order, untouched:

-mtune=cpu-type  -march=cpu-type
-mtune-ctrl=feature-list  -mdump-tune-features  -mno-default
-mfpmath=unit -masm=dialect  -mno-fancy-math-387 -mno-fp-ret-in-387
-m80387  -mhard-float  -msoft-float -mno-wide-multiply  -mrtd
-malign-double -mpreferred-stack-boundary=num
-mincoming-stack-boundary=num -mcld  -mcx16  -msahf  -mmovbe
-mcrc32 -mmwait -mrecip  -mrecip=opt -mvzeroupper  -mprefer-avx128
-mprefer-vector-width=opt -mmove-max=bits -mstore-max=bits -mmmx
-msse  -msse2  -msse3  -mssse3  -msse4.1  -msse4.2  -msse4  -mavx
-mavx2  -mavx512f  -mavx512pf  -mavx512er  -mavx512cd  -mavx512vl
-mavx512bw  -mavx512dq  -mavx512ifma  -mavx512vbmi  -msha  -maes
-mpclmul  -mfsgsbase  -mrdrnd  -mf16c  -mfma  -mpconfig  -mwbnoinvd
-mptwrite  -mprefetchwt1  -mclflushopt  -mclwb  -mxsavec  -mxsaves
-msse4a  -m3dnow  -m3dnowa  -mpopcnt  -mabm  -mbmi  -mtbm  -mfma4
-mxop -madx  -mlzcnt  -mbmi2  -mfxsr  -mxsave  -mxsaveopt  -mrtm
-mhle  -mlwp -mmwaitx  -mclzero  -mpku  -mthreads  -mgfni  -mvaes
-mwaitpkg -mshstk -mmanual-endbr -mforce-indirect-call
-mavx512vbmi2 -mavx512bf16 -menqcmd -mvpclmulqdq  -mavx512bitalg
-mmovdiri  -mmovdir64b  -mavx512vpopcntdq -mavx5124fmaps
-mavx512vnni  -mavx5124vnniw  -mprfchw  -mrdpid -mrdseed  -msgx
-mavx512vp2intersect -mserialize -mtsxldtrk -mamx-tile  -mamx-int8
-mamx-bf16 -muintr -mhreset -mavxvnni -mavx512fp16 -mcldemote
-mms-bitfields  -mno-align-stringops  -minline-all-stringops
-minline-stringops-dynamically  -mstringop-strategy=alg -mkl
-mwidekl -mmemcpy-strategy=strategy  -mmemset-strategy=strategy
-mpush-args  -maccumulate-outgoing-args  -m128bit-long-double
-m96bit-long-double  -mlong-double-64  -mlong-double-80
-mlong-double-128 -mregparm=num  -msseregparm -mveclibabi=type
-mvect8-ret-in-mem -mpc32  -mpc64  -mpc80  -mstackrealign
-momit-leaf-frame-pointer  -mno-red-zone  -mno-tls-direct-seg-refs
-mcmodel=code-model  -mabi=name  -maddress-mode=mode -m32  -m64
-mx32  -m16  -miamcu  -mlarge-data-threshold=num -msse2avx  -mfentry
-mrecord-mcount  -mnop-mcount  -m8bit-idiv -minstrument-return=type
-mfentry-name=name -mfentry-section=name
-mavx256-split-unaligned-load  -mavx256-split-unaligned-store
-malign-data=type  -mstack-protector-guard=guard
-mstack-protector-guard-reg=reg
-mstack-protector-guard-offset=offset
-mstack-protector-guard-symbol=symbol -mgeneral-regs-only
-mcall-ms2sysv-xlogues -mrelax-cmpxchg-loop -mindirect-branch=choice
-mfunction-return=choice -mindirect-branch-register
-mharden-sls=choice -mindirect-branch-cs-prefix -mneeded
-mno-direct-extern-access

a few placeholders to keep your eyes on: cpu-type, feature-list, unit, dialect, opt, bits, alg, strategy, type, num, code-model, name, mode, guard, reg, offset, symbol, choice. if a flag has an = after it, that's what it's waiting for 🎀

and yes, -mstack-protector-guard-offset=offset is a real line all by itself. she's long. she's committed. periodt 💅

🪟 x86 Windows Options 🪟

-mconsole  -mcygwin  -mno-cygwin  -mdll
-mnop-fun-dllimport  -mthread -municode  -mwin32  -mwindows
-fno-set-stack-executable

(one imposter without the -m, we don't judge 🌈)

⚡ Xstormy16 Options ⚡

  • -msim

literally one. main character energy 👑

🧵 Xtensa Options 🧵

-mconst16  -mno-const16 -mfused-madd  -mno-fused-madd
-mforce-no-pic -mserialize-volatile  -mno-serialize-volatile
-mtext-section-literals  -mno-text-section-literals -mauto-litpools
-mno-auto-litpools -mtarget-align  -mno-target-align -mlongcalls
-mno-longcalls -mabi=abi-type

and -mabi=abi-type takes an abi-type at the end 💖

🏛️ zSeries Options 🏛️

See S/390 and zSeries Options.

they're not re-listing them here, bestie — go look at that section instead 🫶


✨ Options Controlling the Kind of Output ✨

okay, this is the big-picture section and honestly it's the one that makes everything click. real talk:

Compiling can involve up to four stages, and they always happen in this order:

  1. preprocessing
  2. compilation proper
  3. assembly
  4. linking

GCC can preprocess and compile several files at once — either into several assembler input files, or squished into a single assembler input file. Then each assembler input file produces an object file, and then linking takes all the object files (the freshly compiled ones and the ones you passed in as input) and combines them into an executable 🔥


🌸 the suffix tells it everything 🌸

For any given input file, the file name suffix decides what kind of compilation happens. here's the full decoder ring:

  • file.c — C source code that must be preprocessed.
  • file.i — C source code that should not be preprocessed.
  • file.ii — C++ source code that should not be preprocessed.
  • file.m — Objective-C source code. ⚠️ note: you must link with the libobjc library to make an Objective-C program work.
  • file.mi — Objective-C source code that should not be preprocessed.
  • file.mm, file.M — Objective-C++ source code. ⚠️ note: you must link with the libobjc library to make an Objective-C++ program work. Also note that .M means a literal capital M.
  • file.mii — Objective-C++ source code that should not be preprocessed.
  • file.h — a C, C++, Objective-C or Objective-C++ header file to be turned into a precompiled header (that's the default), or a C, C++ header file to be turned into an Ada spec (via the -fdump-ada-spec switch).
  • file.cc, file.cp, file.cxx, file.cpp, file.CPP, file.c++, file.C — C++ source code that must be preprocessed. ⚠️ careful: in .cxx, the last two letters must both be literally x. Likewise, .C means a literal capital C.
  • file.mm, file.M — Objective-C++ source code that must be preprocessed. (yep, same suffixes, this list really does say it again — i'm not merging them, that's how it's written 🙈)
  • file.mii — Objective-C++ source code that should not be preprocessed. (listed again too, and again i'm leaving it be 💀)
  • file.hh, file.H, file.hp, file.hxx, file.hpp, file.HPP, file.h++, file.tcc — C++ header file to be turned into a precompiled header or Ada spec.
  • file.f, file.for, file.ftn — fixed form Fortran source code that should not be preprocessed.
  • file.F, file.FOR, file.fpp, file.FPP, file.FTN — fixed form Fortran source code that must be preprocessed (with the traditional preprocessor).
  • file.f90, file.f95, file.f03, file.f08 — free form Fortran source code that should not be preprocessed.
  • file.F90, file.F95, file.F03, file.F08 — free form Fortran source code that must be preprocessed (with the traditional preprocessor).
  • file.go — Go source code.
  • file.d — D source code.
  • file.di — D interface file.
  • file.dd — D documentation code (Ddoc).
  • file.ads — Ada source code file containing a library unit declaration (a declaration of a package, subprogram, or generic, or a generic instantiation), or a library unit renaming declaration (a package, generic, or subprogram renaming declaration). These files are also called specs.
  • file.adb — Ada source code file containing a library unit body (a subprogram or package body). These files are also called bodies.
  • file.s — assembler code.
  • file.S, file.sx — assembler code that must be preprocessed.
  • other — an object file to be fed straight into linking. Any file name with no recognized suffix is treated this way. no suffix? object file. that's the rule 😌

🦋 saying it explicitly with -x 🦋

You can straight-up tell it what the language is instead of letting suffixes decide:

  • -x language — specify explicitly the language for the following input files (instead of letting the compiler pick a default from the file name suffix). This option applies to all following input files until the next -x option. Possible values for language are:
c  c-header  cpp-output
c++  c++-header  c++-system-header c++-user-header c++-cpp-output
objective-c  objective-c-header  objective-c-cpp-output
objective-c++ objective-c++-header objective-c++-cpp-output
assembler  assembler-with-cpp
ada
d
f77  f77-cpp-input f95  f95-cpp-input
go
  • -x none — turn off any specification of a language, so subsequent files go back to being handled by their file name suffixes (exactly like when -x hasn't been used at all). the "never mind" flag 🫶

🎯 stopping early on purpose 🎯

If you only want some of the stages, you use -x (or filename suffixes) to tell gcc where to start, and then one of -c, -S, or -E to say where gcc should stop.

⚠️ Important vibe check: some combinations (for example, -x cpp-output -E) instruct gcc to do nothing at all. literally nothing. zero. 💀
  • -c — compile or assemble the source files, but do not link. The linking stage simply is not done. The ultimate output is an object file for each source file.

By default, the object file name for a source file is made by replacing the suffix .c, .i, .s, etc., with .o.

Unrecognized input files, not requiring compilation or assembly, are ignored.

  • -S — stop after the stage of compilation proper; do not assemble. The output is an assembler code file for each non-assembler input file you specified.

By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s.

Input files that don't require compilation are ignored.

  • -E — stop after the preprocessing stage; do not run the compiler proper. The output is preprocessed source code, and it's sent to the standard output.

Input files that don't require preprocessing are ignored.

so like: -E = stop super early, -S = stop after compiling, -c = stop before linking. three little off-ramps, all iconic 🌈⭐

  • -o file — okay so this one puts the primary output in file, bestie. 💅 It applies to literally whatever sort of output you’re producing: executable file, object file, assembler file, or preprocessed C code. No cap.

If -o is not specified, the default is to put an executable file in a.out, the object file for source.suffix in source.o, its assembler file in source.s, a precompiled header file in source.suffix.gch, and all preprocessed C source on standard output. ✨

Though -o names only the primary output, it also affects the naming of auxiliary and dump outputs. See the examples below. 🫶 Unless overridden, both auxiliary outputs and dump outputs are placed in the same directory as the primary output. In auxiliary outputs, the suffix of the input file is replaced with that of the auxiliary output file type; in dump outputs, the suffix of the dump file is appended to the input file suffix. In compilation commands, the base name of both auxiliary and dump outputs is that of the primary output; in compile and link commands, the primary output name, minus the executable suffix, is combined with the input file name. If both share the same base name, disregarding the suffix, the result of the combination is that base name, otherwise, they are concatenated, separated by a dash. 🎀

gcc -c foo.c ...

will use foo.o as the primary output, and place aux outputs and dumps next to it, e.g., aux file foo.dwo for -gsplit-dwarf, and dump file foo.c.???r.final for -fdump-rtl-final. 🔥

If a non-linker output file is explicitly specified, aux and dump files by default take the same base name:

gcc -c foo.c -o dir/foobar.o ...

will name aux outputs dir/foobar.* and dump outputs dir/foobar.c.*. 🌸

A linker output will instead prefix aux and dump outputs:

gcc foo.c bar.c -o dir/foobar ...

will generally name aux outputs dir/foobar-foo.* and dir/foobar-bar.*, and dump outputs dir/foobar-foo.c.* and dir/foobar-bar.c.*. 💖

The one exception to the above is when the executable shares the base name with the single input:

gcc foo.c -o dir/foo ...

in which case aux outputs are named dir/foo.* and dump outputs named dir/foo.c.*. 🦋

The location and the names of auxiliary and dump outputs can be adjusted by the options -dumpbase, -dumpbase-ext, -dumpdir, -save-temps=cwd, and -save-temps=obj. 👑

  • -dumpbase dumpbase — this option sets the base name for auxiliary and dump output files, bestie. It does not affect the name of the primary output file. 🎀 Intermediate outputs, when preserved, are not regarded as primary outputs, but as auxiliary outputs:
gcc -save-temps -S foo.c

saves the (no longer) temporary preprocessed file in foo.i, and then compiles to the (implied) output file foo.s, whereas:

gcc -save-temps -dumpbase save-foo -c foo.c

preprocesses into save-foo.i, compiles to save-foo.s (now an intermediate, thus auxiliary output), and then assembles to the (implied) output file foo.o. 😭

Absent this option, dump and aux files take their names from the input file, or from the (non-linker) output file, if one is explicitly specified: dump output files (e.g. those requested by -fdump-* options) with the input name suffix, and aux output files (those requested by other non-dump options, e.g. -save-temps, -gsplit-dwarf, -fcallgraph-info) without it. 🧚

Similar suffix differentiation of dump and aux outputs can be attained for explicitly-given -dumpbase basename.suf by also specifying -dumpbase-ext .suf. ✨

If dumpbase is explicitly specified with any directory component, any dumppfx specification (e.g. -dumpdir or -save-temps=*) is ignored, and instead of appending to it, dumpbase fully overrides it:

gcc foo.c -c -o dir/foo.o -dumpbase alt/foo \
  -dumpdir pfx- -save-temps=cwd ...

creates auxiliary and dump outputs named alt/foo.*, disregarding dir/ in -o, the ./ prefix implied by -save-temps=cwd, and pfx- in -dumpdir. 💀

When -dumpbase is specified in a command that compiles multiple inputs, or that compiles and then links, it may be combined with dumppfx, as specified under -dumpdir. Then, each input file is compiled using the combined dumppfx, and default values for dumpbase and auxdropsuf are computed for each input file:

gcc foo.c bar.c -c -dumpbase main ...

creates foo.o and bar.o as primary outputs, and avoids overwriting the auxiliary and dump outputs by using the dumpbase as a prefix, creating auxiliary and dump outputs named main-foo.* and main-bar.*. 🔥

An empty string specified as dumpbase avoids the influence of the output basename in the naming of auxiliary and dump outputs during compilation, computing default values:

gcc -c foo.c -o dir/foobar.o -dumpbase " ...

will name aux outputs dir/foo.* and dump outputs dir/foo.c.*. Note how their basenames are taken from the input name, but the directory still defaults to that of the output. 🌈

The empty-string dumpbase does not prevent the use of the output basename for outputs during linking:

gcc foo.c bar.c -o dir/foobar -dumpbase " -flto ...

The compilation of the source files will name auxiliary outputs dir/foo.* and dir/bar.*, and dump outputs dir/foo.c.* and dir/bar.c.*. LTO recompilation during linking will use dir/foobar. as the prefix for dumps and auxiliary files. 🫶

  • -dumpbase-ext auxdropsuf — when forming the name of an auxiliary (but not a dump) output file, drop trailing auxdropsuf from dumpbase before appending any suffixes. If not specified, this option defaults to the suffix of a default dumpbase, i.e., the suffix of the input file when -dumpbase is not present in the command line, or dumpbase is combined with dumppfx. 💅
gcc foo.c -c -o dir/foo.o -dumpbase x-foo.c -dumpbase-ext .c ...

creates dir/foo.o as the main output, and generates auxiliary outputs in dir/x-foo.*, taking the location of the primary output, and dropping the .c suffix from the dumpbase. Dump outputs retain the suffix: dir/x-foo.c.*. 🎀

This option is disregarded if it does not match the suffix of a specified dumpbase, except as an alternative to the executable suffix when appending the linker output base name to dumppfx, as specified below:

gcc foo.c bar.c -o main.out -dumpbase-ext .out ...

creates main.out as the primary output, and avoids overwriting the auxiliary and dump outputs by using the executable name minus auxdropsuf as a prefix, creating auxiliary outputs named main-foo.* and main-bar.* and dump outputs named main-foo.c.* and main-bar.c.*. 💖

  • -dumpdir dumppfx — when forming the name of an auxiliary or dump output file, use dumppfx as a prefix:
gcc -dumpdir pfx- -c foo.c ...

creates foo.o as the primary output, and auxiliary outputs named pfx-foo.*, combining the given dumppfx with the default dumpbase derived from the default primary output, derived in turn from the input name. Dump outputs also take the input name suffix: pfx-foo.c.*. 🌸

If dumppfx is to be used as a directory name, it must end with a directory separator:

gcc -dumpdir dir/ -c foo.c -o obj/bar.o ...

creates obj/bar.o as the primary output, and auxiliary outputs named dir/bar.*, combining the given dumppfx with the default dumpbase derived from the primary output name. Dump outputs also take the input name suffix: dir/bar.c.*. 🦋

It defaults to the location of the output file, unless the output file is a special file like /dev/null. Options -save-temps=cwd and -save-temps=obj override this default, just like an explicit -dumpdir option. In case multiple such options are given, the last one prevails:

gcc -dumpdir pfx- -c foo.c -save-temps=obj ...

outputs foo.o, with auxiliary outputs named foo.* because -save-temps=* overrides the dumppfx given by the earlier -dumpdir option. It does not matter that =obj is the default for -save-temps, nor that the output directory is implicitly the current directory. Dump outputs are named foo.c.*. ✨

When compiling from multiple input files, if -dumpbase is specified, dumpbase, minus a auxdropsuf suffix, and a dash are appended to (or override, if containing any directory components) an explicit or defaulted dumppfx, so that each of the multiple compilations gets differently-named aux and dump outputs. 🔥

gcc foo.c bar.c -c -dumpdir dir/pfx- -dumpbase main ...

outputs auxiliary dumps to dir/pfx-main-foo.* and dir/pfx-main-bar.*, appending dumpbase- to dumppfx. Dump outputs retain the input file suffix: dir/pfx-main-foo.c.* and dir/pfx-main-bar.c.*, respectively. Contrast with the single-input compilation:

gcc foo.c -c -dumpdir dir/pfx- -dumpbase main ...

that, applying -dumpbase to a single source, does not compute and append a separate dumpbase per input file. Its auxiliary and dump outputs go in dir/pfx-main.*. 😭

When compiling and then linking from multiple input files, a defaulted or explicitly specified dumppfx also undergoes the dumpbase- transformation above (e.g. the compilation of foo.c and bar.c above, but without -c). If neither -dumpdir nor -dumpbase are given, the linker output base name, minus auxdropsuf, if specified, or the executable suffix otherwise, plus a dash is appended to the default dumppfx instead. Note, however, that unlike earlier cases of linking:

gcc foo.c bar.c -dumpdir dir/pfx- -o main ...

does not append the output name main to dumppfx, because -dumpdir is explicitly specified. The goal is that the explicitly-specified dumppfx may contain the specified output name as part of the prefix, if desired; only an explicitly-specified -dumpbase would be combined with it, in order to avoid simply discarding a meaningful option. 💀

When compiling and then linking from a single input file, the linker output base name will only be appended to the default dumppfx as above if it does not share the base name with the single input file name. This has been covered in single-input linking cases above, but not with an explicit -dumpdir that inhibits the combination, even if overridden by -save-temps=*:

gcc foo.c -dumpdir alt/pfx- -o dir/main.exe -save-temps=cwd ...

Okay so, auxiliary outputs are named foo.*, and dump outputs foo.c.* — literally in the current working directory as ultimately requested by -save-temps=cwd 💅.

Summing it all up for an intuitive though slightly imprecise data flow: the primary output name is broken into a directory part and a basename part; dumppfx is set to the former, unless overridden by -dumpdir or -save-temps=*, and dumpbase is set to the latter, unless overridden by -dumpbase. If there are multiple inputs or linking, this dumpbase may be combined with dumppfx and taken from each input file. Auxiliary output names for each input are formed by combining dumppfx, dumpbase minus suffix, and the auxiliary output suffix; dump output names are only different in that the suffix from dumpbase is retained.

When it comes to auxiliary and dump outputs created during LTO recompilation, a combination of dumppfx and dumpbase, as given or as derived from the linker output name but not from inputs — even in cases in which this combination would not otherwise be used as such — is passed down with a trailing period replacing the compiler-added dash, if any, as a -dumpdir option to lto-wrapper; being involved in linking, this program does not normally get any -dumpbase and -dumpbase-ext, and it ignores them.

When running sub-compilers, lto-wrapper appends LTO stage names to the received dumppfx, ensures it contains a directory component so that it overrides any -dumpdir, and passes that as -dumpbase to sub-compilers.

  • -v — Print (on standard error output) the commands executed to run the stages of compilation. Also print the version number of the compiler driver program and of the preprocessor and the compiler proper.
  • -### — Like -v except the commands are not executed and arguments are quoted unless they contain only alphanumeric characters or ./-_. This is useful for shell scripts to capture the driver-generated command lines.
  • --help — Print (on the standard output) a description of the command-line options understood by gcc. If the -v option is also specified then --help is also passed on to the various processes invoked by gcc, so that they can display the command-line options they accept. If the -Wextra option has also been specified (prior to the --help option), then command-line options that have no documentation associated with them are also displayed.
  • --target-help — Print (on the standard output) a description of target-specific command-line options for each tool. For some targets extra target-specific information may also be printed.
  • --help={class|[^]qualifier}[,...] — Print (on the standard output) a description of the command-line options understood by the compiler that fit into all specified classes and qualifiers.

These are the supported classes:

  • optimizers — Display all of the optimization options supported by the compiler.
  • warnings — Display all of the options controlling warning messages produced by the compiler.
  • target — Display target-specific options. Unlike the --target-help option however, target-specific options of the linker and assembler are not displayed. This is because those tools do not currently support the extended --help= syntax.
  • params — Display the values recognized by the --param option.
  • language — Display the options supported for language, where language is the name of one of the languages supported in this version of GCC. If an option is supported by all languages, one needs to select common class.
  • common — Display the options that are common to all languages.

These are the supported qualifiers:

  • undocumented — Display only those options that are undocumented.
  • joined — Display options taking an argument that appears after an equal sign in the same continuous piece of text, such as: --help=target.
  • separate — Display options taking an argument that appears as a separate word following the original option, such as: -o output-file.

Thus for example to display all the undocumented target-specific switches supported by the compiler, use:

--help=target,undocumented

The sense of a qualifier can be inverted by prefixing it with the ^ character, so for example to display all binary warning options (i.e., ones that are either on or off and that do not take an argument) that have a description, use:

--help=warnings,^joined,^undocumented
Bestie, the argument to --help= should not consist solely of inverted qualifiers.

Combining several classes is possible, although this usually restricts the output so much that there is nothing to display. One case where it does work, however, is when one of the classes is target. For example, to display all the target-specific optimization options, use:

--help=target,optimizers

The --help= option can be repeated on the command line. Each successive use displays its requested class of options, skipping those that have already been displayed. If --help is also specified anywhere on the command line then this takes precedence over any --help= option.

If the -Q option appears on the command line before the --help= option, then the descriptive text displayed by --help= is changed. Instead of describing the displayed options, an indication is given as to whether the option is enabled, disabled or set to a specific value (assuming that the compiler knows this at the point where the --help= option is used).

Here is a truncated example from the ARM port of gcc:

% gcc -Q -mabi=2 --help=target -c
The following options are target specific:
-mabi=                                2
-mabort-on-noreturn                   [disabled]
-mapcs                                [disabled]

The output is sensitive to the effects of previous command-line options, so for example it is possible to find out which optimizations are enabled at -O2 by using:

-Q -O2 --help=optimizers

Alternatively you can discover which binary optimizations are enabled by -O3 by using:

gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts
gcc -c -Q -O2 --help=optimizers > /tmp/O2-opts
diff /tmp/O2-opts /tmp/O3-opts | grep enabled
  • --version — Display the version number and copyrights of the invoked GCC.
  • -pass-exit-codes — Normally the gcc program exits with the code of 1 if any phase of the compiler returns a non-success return code. If you specify -pass-exit-codes, the gcc program instead returns with the numerically highest error produced by any phase returning an error indication. The C, C++, and Fortran front ends return 4 if an internal compiler error is encountered.
  • -pipe — Use pipes rather than temporary files for communication between the various stages of compilation. This fails to work on some systems where the assembler is unable to read from a pipe; but the GNU assembler has no trouble.
  • -specs=file — Process file after the compiler reads in the standard specs file, in order to override the defaults which the gcc driver program uses when determining what switches to pass to cc1, cc1plus, as, ld, etc. More than one -specs=file can be specified on the command line, and they are processed in order, from left to right.
  • -wrapper — Invoke all subcommands under a wrapper program. The name of the wrapper program and its parameters are passed as a comma separated list.
gcc -c t.c -wrapper gdb,--args

This invokes all subprograms of gcc under gdb --args, thus the invocation of cc1 is gdb --args cc1 ....

  • -ffile-prefix-map=old=new — When compiling files residing in directory old, record any references to them in the result of the compilation as if the files resided in directory new instead. Specifying this option is equivalent to specifying all the individual -f*-prefix-map options. This can be used to make reproducible builds that are location independent. See also -fmacro-prefix-map, -fdebug-prefix-map and -fprofile-prefix-map.
  • -fplugin=name.so — Load the plugin code in file name.so, assumed to be a shared object to be dlopen'd by the compiler. The base name of the shared object file is used to identify the plugin for the purposes of argument parsing (See -fplugin-arg-name-key=value below). Each plugin should define the callback functions specified in the Plugins API.
  • -fplugin-arg-name-key=value — Define an argument called key with a value of value for the plugin called name.
  • -fdump-ada-spec[-slim] — For C and C++ source and include files, generate corresponding Ada specs.
  • -fada-spec-parent=unit — In conjunction with -fdump-ada-spec[-slim] above, generate Ada specs as child units of parent unit.
  • -fdump-go-spec=file — For input files in any language, generate corresponding Go declarations in file. This generates Go "const", "type", "var", and "func" declarations which may be a useful way to start writing a Go interface to code written in some other language.
  • @file — Read command-line options from file. The options read are inserted in place of the original @file option. If file does not exist, or cannot be read, then the option will be treated literally, and not removed.

Options in file are separated by whitespace. A whitespace character may be included in an option by surrounding the entire option in either single or double quotes. Any character (including a backslash) may be included by prefixing the character to be included with a backslash. The file may itself contain additional @file options; any such options will be processed recursively.


🎀 Compiling C++ Programs 🎀

C++ source files conventionally use one of the suffixes .C, .cc, .cpp, .CPP, .c++, .cp, or .cxx; C++ header files often use .hh, .hpp, .H, or (for shared template code) .tcc; and preprocessed C++ files use the suffix .ii. GCC recognizes files with these names and compiles them as C++ programs even if you call the compiler the same way as for compiling C programs (usually with the name gcc).

So here’s the tea, bestie: using gcc does not add the C++ library. That’s literally not its job. g++ is the program that calls GCC and automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files unless -x is used. This program is also super useful when precompiling a C header file with a .h extension for use in C++ compilations. On many systems, g++ is also installed with the name c++. 💅

When you compile C++ programs, you may specify many of the same command-line options that you use for compiling programs in any language; or command-line options meaningful for C and related languages; or options that are meaningful only for C++ programs. No cap.

🎀 Options Controlling C Dialect 🎀

The following options control the dialect of C (or languages derived from C, such as C++, Objective-C and Objective-C++) that the compiler accepts:

  • -ansi — In C mode, this is equivalent to -std=c90. In C++ mode, it is equivalent to -std=c++98.

This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code), or of standard C++ (when compiling C++ code), such as the asm and typeof keywords, and predefined macros such as unix and vax that identify the type of system you are using. It also enables the undesirable and rarely used ISO trigraph feature. For the C compiler, it disables recognition of C++ style // comments as well as the inline keyword.

The alternate keywords __asm__, __extension__, __inline__ and __typeof__ continue to work despite -ansi. You would not want to use them in an ISO C program, of course, but it is useful to put them in header files that might be included in compilations done with -ansi. Alternate predefined macros such as __unix__ and __vax__ are also available, with or without -ansi.

The -ansi option does not cause non-ISO programs to be rejected gratuitously. For that, -Wpedantic is required in addition to -ansi. Periodt.

The macro __STRICT_ANSI__ is predefined when the -ansi option is used. Some header files may notice this macro and refrain from declaring certain functions or defining certain macros that the ISO standard doesn’t call for; this is to avoid interfering with any programs that might use these names for other things.

Functions that are normally built in but do not have semantics defined by ISO C (such as alloca and ffs) are not built-in functions when -ansi is used.

  • -std= — Determine the language standard. This option is currently only supported when compiling C or C++.

The compiler can accept several base standards, such as c90 or c++98, and GNU dialects of those standards, such as gnu90 or gnu++98. When a base standard is specified, the compiler accepts all programs following that standard plus those using GNU extensions that do not contradict it. For example, -std=c90 turns off certain features of GCC that are incompatible with ISO C90, such as the asm and typeof keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a ?: expression. On the other hand, when a GNU dialect of a standard is specified, all features supported by the compiler are enabled, even when those features change the meaning of the base standard. As a result, some strict-conforming programs may be rejected. The particular standard is used by -Wpedantic to identify which features are GNU extensions given that version of the standard. For example -std=gnu90 -Wpedantic warns about C++ style // comments, while -std=gnu99 -Wpedantic does not.

A value for this option must be provided; possible values are:

  • c90, c89, iso9899:1990 — Support all ISO C90 programs (certain GNU extensions that conflict with ISO C90 are disabled). Same as -ansi for C code.
  • iso9899:199409 — ISO C90 as modified in amendment 1.
  • c99, c9x, iso9899:1999, iso9899:199x — ISO C99. This standard is substantially completely supported, modulo bugs and floating-point issues (mainly but not entirely relating to optional C99 features from Annexes F and G). See https://gcc.gnu.org/c99status.html for more information. The names c9x and iso9899:199x are deprecated.
  • c11, c1x, iso9899:2011 — ISO C11, the 2011 revision of the ISO C standard. This standard is substantially completely supported, modulo bugs, floating-point issues (mainly but not entirely relating to optional C11 features from Annexes F and G) and the optional Annexes K (Bounds-checking interfaces) and L (Analyzability). The name c1x is deprecated.
  • c17, c18, iso9899:2017, iso9899:2018 — ISO C17, the 2017 revision of the ISO C standard (published in 2018). This standard is same as C11 except for corrections of defects (all of which are also applied with -std=c11) and a new value of __STDC_VERSION__, and so is supported to the same extent as C11.
  • c2x — The next version of the ISO C standard, still under development. The support for this version is experimental and incomplete.
  • gnu90, gnu89 — GNU dialect of ISO C90 (including some C99 features).
  • gnu99, gnu9x — GNU dialect of ISO C99. The name gnu9x is deprecated.
  • gnu11, gnu1x — GNU dialect of ISO C11. The name gnu1x is deprecated.
  • gnu17, gnu18 — GNU dialect of ISO C17. This is the default for C code.
  • gnu2x — The next version of the ISO C standard, still under development, plus GNU extensions. The support for this version is experimental and incomplete.
  • c++98, c++03 — The 1998 ISO C++ standard plus the 2003 technical corrigendum and some additional defect reports. Same as -ansi for C++ code.
  • gnu++98, gnu++03 — GNU dialect of -std=c++98.
  • c++11, c++0x — The 2011 ISO C++ standard plus amendments. The name c++0x is deprecated.
  • gnu++11, gnu++0x — GNU dialect of -std=c++11. The name gnu++0x is deprecated.
  • c++14, c++1y — The 2014 ISO C++ standard plus amendments. The name c++1y is deprecated.
  • gnu++14, gnu++1y — GNU dialect of -std=c++14. The name gnu++1y is deprecated.
  • c++17, c++1z — The 2017 ISO C++ standard plus amendments. The name c++1z is deprecated.
  • gnu++17, gnu++1z — GNU dialect of -std=c++17. This is the default for C++ code. The name gnu++1z is deprecated.
  • c++20, c++2a — The 2020 ISO C++ standard plus amendments. Support is experimental, and could change in incompatible ways in future releases. The name c++2a is deprecated.
  • gnu++20, gnu++2a — GNU dialect of -std=c++20. Support is experimental, and could change in incompatible ways in future releases. The name gnu++2a is deprecated.
  • c++2b, c++23 — The next revision of the ISO C++ standard, planned for 2023. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.
  • gnu++2b, gnu++23 — GNU dialect of -std=c++2b. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.
  • -aux-info filename — Output to the given filename prototyped declarations for all functions declared and/or defined in a translation unit, including those in header files. This option is silently ignored in any language other than C.

Besides declarations, the file indicates, in comments, the origin of each declaration (source file and line), whether the declaration was implicit, prototyped or unprototyped (I, N for new or O for old, respectively, in the first character after the line number and the colon), and whether it came from a declaration or a definition (C or F, respectively, in the following character). In the case of function definitions, a K&R-style list of arguments followed by their declarations is also provided, inside comments, after the declaration.

  • -fallow-parameterless-variadic-functions — Accept variadic functions without named parameters.

Although it is possible to define such a function, this is not very useful as it is not possible to read the arguments. This is only supported for C as this construct is allowed by C++.

  • -fno-asm — Do not recognize asm, inline or typeof as a keyword, so that code can use these words as identifiers. You can use the keywords __asm__, __inline__ and __typeof__ instead. In C, -ansi implies -fno-asm.

In C++, inline is a standard keyword and is not affected by this switch. You may want to use the -fno-gnu-keywords flag instead, which disables typeof but not asm and inline. In C99 mode (-std=c99 or -std=gnu99), this switch only affects the asm and typeof keywords, since inline is a standard keyword in ISO C99.

  • -fno-builtin, -fno-builtin-function — Don’t recognize built-in functions that do not begin with __builtin_ as prefix.

GCC normally generates special code to handle certain built-in functions more efficiently; for instance, calls to alloca may become single instructions which adjust the stack directly, and calls to memcpy may become inline copy loops. The resulting code is often both smaller and faster, but since the function calls no longer appear as such, you cannot set a breakpoint on those calls, nor can you change the behavior of the functions by linking with a different library. In addition, when a function is recognized as a built-in function, GCC may use information about that function to warn about problems with calls to that function, or to generate more efficient code, even if the resulting code still contains calls to that function. For example, warnings are given with -Wformat for bad calls to printf when printf is built in and strlen is known not to modify global memory. 💖

  • -fno-builtin-function — this one's lowkey surgical: it disables only the built-in function, not the whole squad. Two rules though, bestie: function must not start with __builtin_, and if you name something that isn't even a built-in in this version of GCC, the option just gets ignored, no drama. Also heads up — there's no matching -fbuiltin-function option. So if you wanna enable built-ins à la carte while rocking -fno-builtin or -ffreestanding, you roll your own macros, like:
#define abs(n)          __builtin_abs ((n))
#define strcpy(d, s)    __builtin_strcpy ((d), (s))
  • -fcond-mismatch — lets you have conditional expressions where the second and third args are straight-up different types 🤪. The value of such an expression is void. Not supported for C++, so don't even try it there.
  • -ffreestanding — declares "this compilation is for a freestanding environment" ✨. It implies -fno-builtin. A freestanding environment is one where the standard library might just... not exist 😭, and program startup might not even begin at main. The most obvious example? An OS kernel 👑. This is equivalent to -fno-hosted.
  • -fgimple — turns on parsing of function definitions marked with __GIMPLE. It's an experimental feature that lets you unit test GIMPLE passes 🧪.
  • -fgnu-tm — when you pass this, the compiler generates code for the Linux variant of Intel's current Transactional Memory ABI specification document (Revision 1.1, May 6 2009) 🔥. It's experimental, and its interface may change in future versions of GCC as the official spec changes — so like, don't get too attached 💀. Also please note: not all architectures are supported for this feature.

For more information on GCC's support for transactional memory,

Heads up 🫶: the transactional memory feature is not supported with non-call exceptions (-fnon-call-exceptions).
  • -fgnu89-inline — tells GCC to use the traditional GNU semantics for inline functions when you're in C99 mode. Using it is roughly equivalent to slapping the gnu_inline function attribute onto all inline functions.

The -fno-gnu89-inline option explicitly tells GCC to use the C99 semantics for inline when in C99 or gnu99 mode (i.e., it specifies the default behavior). This one is not supported in -std=c90 or -std=gnu90 mode.

And if you wanna peek at which semantics are in effect for inline functions, the preprocessor macros __GNUC_GNU_INLINE__ and __GNUC_STDC_INLINE__ are right there for you 💅.

  • -fhosted — asserts that compilation targets a hosted environment 🏠. It implies -fbuiltin. A hosted environment is one where the entire standard library is available, and where main has a return type of int. Examples: literally nearly everything except a kernel. Equivalent to -fno-freestanding.
  • -flax-vector-conversions — allows implicit conversions between vectors with differing numbers of elements and/or incompatible element types. Bestie, this option should not be used for new code 🙈. It's giving legacy vibes only.
  • -fms-extensions — accepts some non-standard constructs used in Microsoft header files 🪟.

In C++ code, this lets member names in structures be similar to previous type declarations:

typedef int UOW;
struct ABC {
  UOW UOW;
};

Some cases of unnamed fields in structures and unions are only accepted with this option.

Note that this option is off for all targets except for x86 targets using ms-abi.
  • -foffload=disable
  • -foffload=default
  • -foffload=target-list — these pick which OpenMP and OpenACC offload targets get code generated for them 🎯. The default behavior, equivalent to -foffload=default, is to generate code for all supported offload targets. The -foffload=disable form generates code only for the host fallback, while -foffload=target-list generates code only for the specified comma-separated list of offload targets.

Offload targets are specified in GCC's internal target-triplet format. You can run the compiler with -v to show the list of configured offload targets under OFFLOAD_TARGET_NAMES 👀.

  • -foffload-options=options
  • -foffload-options=target-triplet-list=options — with -foffload-options=options, GCC passes the specified options to the compilers for all enabled offloading targets 📦. You can specify options that apply only to a specific target or targets by using the -foffload-options=target-list=options form. The target-list is a comma-separated list in the same format as for the -foffload= option.

Typical command lines are

-foffload-options=-lgfortran -foffload-options=-lm
-foffload-options="-lgfortran -lm" -foffload-options=nvptx-none=-latomic
-foffload-options=amdgcn-amdhsa=-march=gfx906 -foffload-options=-lm
  • -fopenacc — enables handling of OpenACC directives #pragma acc in C/C++ and !$acc in Fortran 🌊. When -fopenacc is specified, the compiler generates accelerated code according to the OpenACC Application Programming Interface v2.6 <https://www.openacc.org>. This option implies -pthread, and thus is only supported on targets that have support for -pthread.
  • -fopenacc-dim=geom — sets default compute dimensions for parallel offload regions that don't explicitly specify them. The geom value is a triple of ':'-separated sizes, in order 'gang', 'worker' and, 'vector' 💫. A size can be omitted, to use a target-specific default value.
  • -fopenmp — enables handling of OpenMP directives #pragma omp in C/C++ and !$omp in Fortran 🔥. When -fopenmp is specified, the compiler generates parallel code according to the OpenMP Application Program Interface v4.5 <https://www.openmp.org>. This option implies -pthread, and thus is only supported on targets that have support for -pthread. Also -fopenmp implies -fopenmp-simd.
  • -fopenmp-simd — enables handling of OpenMP's SIMD directives with #pragma omp in C/C++ and !$omp in Fortran ⚡. Other OpenMP directives are ignored.
  • -fpermitted-flt-eval-methods=style — okay so ISO/IEC TS 18661-3 defines new permissible values for FLT_EVAL_METHOD that indicate operations and constants with a semantic type that is an interchange or extended format should be evaluated to the precision and range of that type 🧮. These new values are a superset of those permitted under C99/C11, which does not specify the meaning of other positive values of FLT_EVAL_METHOD. As such, code conforming to C11 may not have been written expecting the possibility of the new values.

-fpermitted-flt-eval-methods specifies whether the compiler should allow only the values of FLT_EVAL_METHOD specified in C99/C11, or the extended set of values specified in ISO/IEC TS 18661-3.

style is either c11 or ts-18661-3 as appropriate.

The default when in a standards compliant mode (-std=c11 or similar) is -fpermitted-flt-eval-methods=c11. The default when in a GNU dialect (-std=gnu11 or similar) is -fpermitted-flt-eval-methods=ts-18661-3.

  • -fplan9-extensions — accepts some non-standard constructs used in Plan 9 code 🌀.

This enables -fms-extensions, permits passing pointers to structures with anonymous fields to functions that expect pointers to elements of the type of the field, and permits referring to anonymous fields declared using a typedef. This is only supported for C, not C++.

  • -fsigned-bitfields
  • -funsigned-bitfields
  • -fno-signed-bitfields
  • -fno-unsigned-bitfields — these control whether a bit-field is signed or unsigned when the declaration doesn't use either signed or unsigned 🎚️. By default, such a bit-field is signed, because this is consistent: the basic integer types such as int are signed types. Iconic consistency behavior, honestly.
  • -fsigned-char — let the type char be signed, like signed char ✍️.

Note that this is equivalent to -fno-unsigned-char, which is the negative form of -funsigned-char. Likewise, the option -fno-signed-char is equivalent to -funsigned-char. Symmetry slay 💅.

  • -funsigned-char — let the type char be unsigned, like unsigned char 🌸.

Each kind of machine has a default for what char should be. It is either like unsigned char by default or like signed char by default.

Ideally, a portable program should always use signed char or unsigned char when it depends on the signedness of an object. But many programs have been written to use plain char and expect it to be signed, or expect it to be unsigned, depending on the machines they were written for. This option, and its inverse, let you make such a program work with the opposite default 🫶.

The type char is always a distinct type from each of signed char or unsigned char, even though its behavior is always just like one of those two. Main character with a borrowed personality, honestly.

  • -fsso-struct=endianness — sets the default scalar storage order of structures and unions to the specified endianness 🔄. The accepted values are big-endian, little-endian and native for the native endianness of the target (the default). This option is not supported for C++.
Warning 🚨: the -fsso-struct switch causes GCC to generate code that is not binary compatible with code generated without it if the specified endianness is not the native endianness of the target.

✨ Options Controlling C++ Dialect ✨

This section describes the command-line options that are only meaningful for C++ programs 💜. You can also use most of the GNU compiler options regardless of what language your program is in. For example, you might compile a file firstClass.C like this:

g++ -g -fstrict-enums -O -c firstClass.C

In this example, only -fstrict-enums is an option meant only for C++ programs; you can use the other options with any language supported by GCC.

Some options for compiling C programs, such as -std, are also relevant for C++ programs.

Here is a list of options that are only for compiling C++ programs:

  • -fabi-version=n — use version n of the C++ ABI 🏗️. The default is version 0.

Version 0 refers to the version conforming most closely to the C++ ABI specification. Therefore, the ABI obtained using version 0 will change in different versions of G++ as ABI bugs are fixed 👀.

Version 1 is the version of the C++ ABI that first appeared in G++ 3.2.

Version 2 is the version of the C++ ABI that first appeared in G++ 3.4, and was the default through G++ 4.9.

Version 3 corrects an error in mangling a constant address as a template argument ✨.

Version 4, which first appeared in G++ 4.5, implements a standard mangling for vector types. ✨

Version 5, which first appeared in G++ 4.6, corrects the mangling of attribute const/volatile on function pointer types, decltype of a plain decl, and use of a function parameter in the declaration of another parameter.

Version 6, which first appeared in G++ 4.7, corrects the promotion behavior of C++11 scoped enums and the mangling of template argument packs, const/static_cast, prefix ++ and --, and a class scope function used as a template argument.

Version 7, which first appeared in G++ 4.8, that treats nullptr_t as a builtin type and corrects the mangling of lambdas in default argument scope.

Version 8, which first appeared in G++ 4.9, corrects the substitution behavior of function types with function-cv-qualifiers.

Version 9, which first appeared in G++ 5.2, corrects the alignment of "nullptr_t".

Version 10, which first appeared in G++ 6.1, adds mangling of attributes that affect type identity, such as ia32 calling convention attributes (e.g. stdcall).

Version 11, which first appeared in G++ 7, corrects the mangling of sizeof... expressions and operator names. For multiple entities with the same name within a function, that are declared in different scopes, the mangling now changes starting with the twelfth occurrence. It also implies -fnew-inheriting-ctors.

Version 12, which first appeared in G++ 8, corrects the calling conventions for empty classes on the x86_64 target and for classes with only deleted copy/move constructors. It accidentally changes the calling convention for classes with a deleted copy constructor and a trivial move constructor. 😭 (bestie... an accident, in the ABI? iconic behaviour honestly)

Version 13, which first appeared in G++ 8.2, fixes the accidental change in version 12. 🫶

Version 14, which first appeared in G++ 10, corrects the mangling of the nullptr expression.

Version 15, which first appeared in G++ 11, changes the mangling of "__alignof__" to be distinct from that of "alignof", and dependent operator names.

See also -Wabi.

  • -fabi-compat-version=n — on targets that support strong aliases, G++ works around mangling changes by creating an alias with the correct mangled name when defining a symbol with an incorrect mangled name. This switch specifies which ABI version to use for the alias. 💅

With -fabi-version=0 (the default), this defaults to 11 (GCC 7 compatibility). If another ABI version is explicitly selected, this defaults to 0. For compatibility with GCC versions 3.2 through 4.9, use -fabi-compat-version=2.

If this option is not provided but -Wabi=n is, that version is used for compatibility aliases. If this option is provided along with -Wabi (without the version), the version from this option is used for the warning.

  • -fno-access-control — turn off all access checking. This switch is mainly useful for working around bugs in the access control code. 🙈 (yes it's a "get out of jail free" card, no we don't make a habit of it)
  • -faligned-new — enable support for C++17 "new" of types that require more alignment than "void* ::operator new(std::size_t)" provides. A numeric argument such as -faligned-new=32 can be used to specify how much alignment (in bytes) is provided by that function, but few users will need to override the default of alignof(std::max_align_t).

This flag is enabled by default for -std=c++17. 🎀

  • -fchar8_t
  • -fno-char8_t — enable support for "char8_t" as adopted for C++20. This includes the addition of a new "char8_t" fundamental type, changes to the types of UTF-8 string and character literals, new signatures for user-defined literals, associated standard library updates, and new "__cpp_char8_t" and "__cpp_lib_char8_t" feature test macros. ✨

This option enables functions to be overloaded for ordinary and UTF-8 strings:

int f(const char *);    // #1
int f(const char8_t *); // #2
int v1 = f("text");     // Calls #1
int v2 = f(u8"text");   // Calls #2

and introduces new signatures for user-defined literals:

int operator""_udl1(char8_t);
int v3 = u8'x'_udl1;
int operator""_udl2(const char8_t*, std::size_t);
int v4 = u8"text"_udl2;
template<typename T, T...> int operator""_udl3();
int v5 = u8"text"_udl3;

The change to the types of UTF-8 string and character literals introduces incompatibilities with ISO C++11 and later standards. 😭 For example, the following code is well-formed under ISO C++11, but is ill-formed when -fchar8_t is specified.

char ca[] = u8"xx";     // error: char-array initialized from wide
                        //        string
const char *cp = u8"xx";// error: invalid conversion from
                        //        `const char8_t*' to `const char*'
int f(const char*);
auto v = f(u8"xx");     // error: invalid conversion from
                        //        `const char8_t*' to `const char*'
std::string s{u8"xx"};  // error: no matching function for call to
                        //        `std::basic_string<char>::basic_string()'
using namespace std::literals;
s = u8"xx"s;            // error: conversion from
                        //        `basic_string<char8_t>' to non-scalar
                        //        type `basic_string<char>' requested
  • -fcheck-new — check that the pointer returned by "operator new" is non-null before attempting to modify the storage allocated. This check is normally unnecessary because the C++ standard specifies that "operator new" only returns 0 if it is declared throw(), in which case the compiler always checks the return value even without this option. In all other cases, when "operator new" has a non-empty exception specification, memory exhaustion is signalled by throwing "std::bad_alloc". See also new (nothrow).
  • -fconcepts
  • -fconcepts-ts — below -std=c++20, -fconcepts enables support for the C++ Extensions for Concepts Technical Specification, ISO 19217 (2015). 🌸

With -std=c++20 and above, Concepts are part of the language standard, so -fconcepts defaults to on. But the standard specification of Concepts differs significantly from the TS, so some constructs that were allowed in the TS but didn't make it into the standard can still be enabled by -fconcepts-ts.

  • -fconstexpr-depth=n — set the maximum nested evaluation depth for C++11 constexpr functions to n. A limit is needed to detect endless recursion during constant expression evaluation. The minimum specified by the standard is 512. 🔥
  • -fconstexpr-cache-depth=n — set the maximum level of nested evaluation depth for C++11 constexpr functions that will be cached to n. This is a heuristic that trades off compilation speed (when the cache avoids repeated calculations) against memory consumption (when the cache grows very large from highly recursive evaluations). The default is 8. Very few users are likely to want to adjust it, but if your code does heavy constexpr calculations you might want to experiment to find which value works best for you. 🧚
  • -fconstexpr-fp-except — Annex F of the C standard specifies that IEC559 floating point exceptions encountered at compile time should not stop compilation. C++ compilers have historically not followed this guidance, instead treating floating point division by zero as non-constant even though it has a well defined value. This flag tells the compiler to give Annex F priority over other rules saying that a particular operation is undefined. ✨
constexpr float inf = 1./0.; // OK with -fconstexpr-fp-except
  • -fconstexpr-loop-limit=n — set the maximum number of iterations for a loop in C++14 constexpr functions to n. A limit is needed to detect infinite loops during constant expression evaluation. The default is 262144 (1<<18).
  • -fconstexpr-ops-limit=n — set the maximum number of operations during a single constexpr evaluation. Even when number of iterations of a single loop is limited with the above limit, if there are several nested loops and each of them has many iterations but still smaller than the above limit, or if in a body of some loop or even outside of a loop too many expressions need to be evaluated, the resulting constexpr evaluation might take too long. The default is 33554432 (1<<25). ⭐
  • -fcoroutines — enable support for the C++ coroutines extension (experimental). 👀 (experimental!! we love a beta babe)
  • -fno-elide-constructors — the C++ standard allows an implementation to omit creating a temporary that is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases. This option also causes G++ to call trivial member functions which otherwise would be expanded inline.

In C++17, the compiler is required to omit these temporaries, but this option still affects trivial member functions.

  • -fno-enforce-eh-specs — don't generate code to check for violation of exception specifications at run time. This option violates the C++ standard, but may be useful for reducing code size in production builds, much like defining "NDEBUG". This does not give user code permission to throw exceptions in violation of the exception specifications; the compiler still optimizes based on the specifications, so throwing an unexpected exception results in undefined behavior at run time. 💀
bestie fr fr: that last one is undefined behavior territory — "may be useful for reducing code size" is not the same as "go off, it's fine". Respect the specs. 🫶
  • -fextern-tls-init, -fno-extern-tls-init — okay so bestie, here's the tea ☕: C++11 and OpenMP standards literally let thread_local and threadprivate variables have dynamic (runtime!) initialization. To make that work, every use of such a variable goes through a lil wrapper function that does the init. When the use AND the definition are in the same translation unit, that overhead gets optimized away — slay. But when the use is in a different translation unit? Significant overhead, even if the variable doesn't actually need dynamic initialization 😭. So if you (the programmer) can be sure no use of the variable in a non-defining TU needs to trigger dynamic initialization — either because the variable is statically initialized, or because a use in the defining TU runs before any uses in another TU — then you can skip that overhead with -fno-extern-tls-init.

On targets that support symbol aliases, the default is -fextern-tls-init. On targets that don't support symbol aliases, the default is -fno-extern-tls-init. 🎀

  • -ffold-simple-inlines, -fno-fold-simple-inlines — lets the C++ frontend fold calls to std::move, std::forward, std::addressof and std::as_const. And unlike inlining, this means no debug information gets generated for those calls. Which is fine honestly, because who's out here debugging std::move? 💅 It's enabled by default unless -fno-inline is active.
  • -fno-gnu-keywords — do NOT recognize typeof as a keyword, so your code can use that word as an identifier. You can use the keyword __typeof__ instead. This option is implied by the strict ISO C++ dialects: -ansi, -std=c++98, -std=c++11, etc. ✨
  • -fimplicit-constexpr — makes inline functions implicitly constexpr if they satisfy the requirements for a constexpr function. Works in C++14 mode or later. Result? Initialization can flip from dynamic to static, plus other optimizations. Iconic behavior honestly 🔥
  • -fno-implicit-templates — never emit code for non-inline templates that are instantiated implicitly (i.e. by use); only emit code for explicit instantiations. Heads up though: if you use this, you MUST structure your code to include all the necessary explicit instantiations, otherwise you're gonna get undefined symbols at link time. No cap, that's on you 🫶
  • -fno-implicit-inline-templates — don't emit code for implicit instantiations of inline templates either. The default handles inlines differently so that compiles with and without optimization need the same set of explicit instantiations.
  • -fno-implement-inlines — to save space, don't emit out-of-line copies of inline functions controlled by #pragma implementation. This causes linker errors if those functions aren't inlined everywhere they're called. So like… careful 💀
  • -fmodules-ts, -fno-modules-ts — enable support for C++20 modules. The -fno-modules-ts is usually not needed, since that's the default. And even though this is a C++20 feature, it is not currently implicitly enabled by selecting that standard version. Rude but okay 🌸
  • -fmodule-header, -fmodule-header=user, -fmodule-header=system — compile a header file to create an importable header unit. 🦋
  • -fmodule-implicit-inline — member functions defined in their class definitions are not implicitly inline for modular code. That's different from traditional C++ behavior, for good reasons. But it may cause some difficulty during code porting 😭. This option makes such function definitions implicitly inline. It does, however, generate an ABI incompatibility, so you must use it everywhere or nowhere. (Such definitions outside of a named module remain implicitly inline, regardless.) ⭐
  • -fno-module-lazy — disable lazy module importing and module mapper creation.
  • -fmodule-mapper=[hostname]:port[?ident], -fmodule-mapper=|program[?ident] args..., -fmodule-mapper==socket[?ident], -fmodule-mapper=<>[inout][?ident], -fmodule-mapper=<in>out[?ident], -fmodule-mapper=file[?ident] — an oracle to query for module name to filename mappings 👑. If unspecified, the CXX_MODULE_MAPPER environment variable is used, and if that's unset, an in-process default is provided.
  • -fmodule-only — only emit the Compiled Module Interface, inhibiting any object file. Just the CMI, nothing else, periodt 💅
  • -fms-extensions — disable Wpedantic warnings about constructs used in MFC, such as implicit int and getting a pointer to member function via non-standard syntax. 🧚
  • -fnew-inheriting-ctors — enable the P0136 adjustment to the semantics of C++11 constructor inheritance. This is part of C++17 but also considered a Defect Report against C++11 and C++14. Enabled by default unless -fabi-version=10 or lower is specified.
  • -fnew-ttp-matching — enable the P0522 resolution to Core issue 150, template template parameters and default arguments: this allows a template with default template arguments as an argument for a template template parameter with fewer template parameters. Enabled by default for -std=c++17. ✨
  • -fno-nonansi-builtins — disable built-in declarations of functions that aren't mandated by ANSI/ISO C. These include ffs, alloca, _exit, index, bzero, conjf, and other related functions. 🍓
  • -fnothrow-opt — treat a throw() exception specification as if it were a noexcept specification, to reduce or eliminate the text size overhead compared to a function with no exception specification. And plot twist: if the function has local variables of types with non-trivial destructors, the exception specification actually makes the function smaller, because the EH cleanups for those variables can be optimized away 🔥. The semantic effect is that an exception thrown out of a function with such an exception specification results in a call to terminate rather than unexpected.
  • -fno-operator-names — do NOT treat the operator name keywords and, bitand, bitor, compl, not, or and xor as synonyms as keywords. 💜
  • -fno-optional-diags — disable diagnostics that the standard says a compiler does not need to issue. Currently, the only such diagnostic issued by G++ is the one for a name having multiple meanings within a class.
  • -fpermissive — downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive allows some nonconforming code to compile. Living dangerously, love that for you 🙈
  • -fno-pretty-templates — so when an error message refers to a specialization of a function template, the compiler normally prints the signature of the template followed by the template arguments and any typedefs or typenames in the signature (e.g. void f(T) [with T = int] rather than void f(int)) so it's clear which template is involved. And when an error message refers to a specialization of a class template, the compiler omits any template arguments that match the default template arguments for that template. If either of these behaviors makes it harder to understand the error message rather than easier, you can use -fno-pretty-templates to disable them. 🎀
  • -fno-rtti — disable generation of information about every class with virtual functions for use by the C++ run-time type identification features (dynamic_cast and typeid). If you don't use those parts of the language, you can save some space with this flag 💅. Note that exception handling uses the same info, but G++ generates it as needed. The dynamic_cast operator can still be used for casts that don't require run-time type information, i.e. casts to void * or to unambiguous base classes.
⚠️ Mixing code compiled with -frtti with that compiled with -fno-rtti may not work. For example, programs may fail to link if a class compiled with -fno-rtti is used as a base for a class compiled with -frtti. Not the vibe, be careful 😭
  • -fsized-deallocation — enable the built-in global declarations
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;

as introduced in C++14. Useful for user-defined replacement deallocation functions that, for example, use the size of the object to make deallocation faster. Enabled by default under -std=c++14 and above. The flag -Wsized-deallocation warns about places that might want to add a definition. 👑

  • -fstrict-enums — allow the compiler to optimize using the assumption that a value of enumerated type can only be one of the values of the enumeration (as defined in the C++ standard; basically, a value that can be represented in the minimum number of bits needed to represent all the enumerators). This assumption may not be valid if the program uses a cast to convert an arbitrary integer value to the enumerated type. 💀
  • -fstrong-eval-order — evaluate member access, array subscripting, and shift expressions in left-to-right order, and evaluate assignment in right-to-left order, as adopted for C++17. Enabled by default with -std=c++17. -fstrong-eval-order=some enables just the ordering of member access and shift expressions, and is the default without -std=c++17. 🌈
  • *-ftemplate-backtrace-limit=n* — set the maximum number of template instantiation notes for a single warning or error to n. The default value is 10.
  • *-ftemplate-depth=n* — set the maximum instantiation depth for template classes to n. A limit on the template instantiation depth is needed to detect endless recursions during template class instantiation. ANSI/ISO C++ conforming programs must not rely on a maximum depth greater than 17 (changed to 1024 in C++11). The default value is 900, because the compiler can run out of stack space before hitting 1024 in some situations. 😮‍💨
  • -fno-threadsafe-statics — do NOT emit the extra code to use the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this option to reduce code size slightly in code that doesn't need to be thread-safe. 🧚
  • -fuse-cxa-atexit — register destructors for objects with static storage duration with the __cxa_atexit function rather than the atexit function. This option is required for fully standards-compliant handling of static destructors, but it only works if your C library supports __cxa_atexit. ✨
  • -fno-use-cxa-get-exception-ptr — bestie, this says don't use the __cxa_get_exception_ptr runtime routine. 😭 That makes std::uncaught_exception incorrect, but it's necessary if the runtime routine isn't available. No cap.
  • -fvisibility-inlines-hidden — this switch declares that the user does not attempt to compare pointers to inline functions or methods where the addresses of the two functions are taken in different shared objects. 💅

The effect is that GCC may effectively mark inline methods with __attribute__ ((visibility ("hidden"))) so they don't appear in the export table of a DSO and don't require a PLT indirection when used within the DSO. Enabling this option can have a dramatic effect on load and link times of a DSO as it massively reduces the size of the dynamic export table when the library makes heavy use of templates. ✨

The behavior of this switch is not quite the same as marking the methods as hidden directly, because it does not affect static variables local to the function or cause the compiler to deduce that the function is defined in only one shared object. 🫶

You may mark a method as having a visibility explicitly to negate the effect of the switch for that method. For example, if you do want to compare pointers to a particular inline method, you might mark it as having default visibility. Marking the enclosing class with explicit visibility has no effect. 👑

Explicitly instantiated inline methods are unaffected by this option as their linkage might otherwise cross a shared library boundary. 🌈

  • -fvisibility-ms-compat — this flag attempts to use visibility settings to make GCC's C++ linkage model compatible with that of Microsoft Visual Studio. 😮‍💨

The flag makes these changes to GCC's linkage model:

  1. It sets the default visibility to hidden, like -fvisibility=hidden.
  2. Types, but not their members, are not hidden by default.
  3. The One Definition Rule is relaxed for types without explicit visibility specifications that are defined in more than one shared object: those declarations are permitted if they are permitted when this option is not used.

In new code it is better to use -fvisibility=hidden and export those classes that are intended to be externally visible. Unfortunately it is possible for code to rely, perhaps accidentally, on the Visual Studio behavior. 🙈

Among the consequences of these changes are that static data members of the same type with the same name but defined in different shared objects are different, so changing one does not change the other; and that pointers to function members defined in different shared objects may not compare equal. When this flag is given, it is a violation of the ODR to define types with the same name differently. 💀

  • -fno-weak — do not use weak symbol support, even if it is provided by the linker. By default, G++ uses weak symbols if they are available. This option exists only for testing, and should not be used by end-users; it results in inferior code and has no benefits. This option may be removed in a future release of G++. 🚨
  • -fext-numeric-literals (C++ and Objective-C++ only) — accept imaginary, fixed-point, or machine-defined literal number suffixes as GNU extensions. When this option is turned off these suffixes are treated as C++11 user-defined literal numeric suffixes. This is on by default for all pre-C++11 dialects and all GNU dialects: -std=c++98, -std=gnu++98, -std=gnu++11, -std=gnu++14. This option is off by default for ISO C++11 onwards (-std=c++11, ...). 🔥
  • -nostdinc++ — do not search for header files in the standard directories specific to C++, but do still search the other standard directories. (This option is used when building the C++ library.) 🛠️
  • -flang-info-include-translate, -flang-info-include-translate-not, -flang-info-include-translate=header — inform of include translation events. The first will note accepted include translations, the second will note declined include translations. The header form will inform of include translations relating to that specific header. If header is of the form "user" or "<system>" it will be resolved to a specific user or system header using the include path. 🧚
  • -flang-info-module-cmi, -flang-info-module-cmi=module — inform of Compiled Module Interface pathnames. The first will note all read CMI pathnames. The module form will not reading a specific module's CMI. module may be a named module or a header-unit (the latter indicated by either being a pathname containing directory separators or enclosed in <> or ""). 🎀
  • -stdlib=libstdc++,libc++ — when G++ is configured to support this option, it allows specification of alternate C++ runtime libraries. Two options are available: libstdc++ (the default, native C++ runtime for G++) and libc++ which is the C++ runtime installed on some operating systems (e.g. Darwin versions from Darwin11 onwards). The option switches G++ to use the headers from the specified library and to emit -lstdc++ or -lc++ respectively, when a C++ runtime is required for linking. 🌸

In addition, these warning options have meanings only for C++ programs:

  • -Wabi-tag (C++ and Objective-C++ only) — warn when a type with an ABI tag is used in a context that does not have that ABI tag. See C++ Attributes for more information about ABI tags. 💜
  • -Wcomma-subscript (C++ and Objective-C++ only) — warn about uses of a comma expression within a subscripting expression. This usage was deprecated in C++20 and is going to be removed in C++23. However, a comma expression wrapped in ( ) is not deprecated. Example:
void f(int *a, int b, int c) {
    a[b,c];     // deprecated in C++20, invalid in C++23
    a[(b,c)];   // OK
}

In C++23 it is valid to have comma separated expressions in a subscript when an overloaded subscript operator is found and supports the right number and types of arguments. G++ will accept the formerly valid syntax for code that is not valid in C++23 but used to be valid but deprecated in C++20 with a pedantic warning that can be disabled with -Wno-comma-subscript. ⭐

Enabled by default with -std=c++20 unless -Wno-deprecated, and with -std=c++23 regardless of -Wno-deprecated. 👑

  • -Wctad-maybe-unsupported (C++ and Objective-C++ only) — warn when performing class template argument deduction (CTAD) on a type with no explicitly written deduction guides. This warning will point out cases where CTAD succeeded only because the compiler synthesized the implicit deduction guides, which might not be what the programmer intended. Certain style guides allow CTAD only on types that specifically "opt-in"; i.e., on types that are designed to support CTAD. This warning can be suppressed with the following pattern:
struct allow_ctad_t; // any name works
template <typename T> struct S {
  S(T) { }
};
S(allow_ctad_t) -> S<void>; // guide with incomplete parameter type will never be considered
  • -Wctor-dtor-privacy (C++ and Objective-C++ only) — warn when a class seems unusable because all the constructors or destructors in that class are private, and it has neither friends nor public static member functions. Also warn if there are no non-private methods, and there's at least one private member function that isn't a constructor or destructor. 🫶
  • -Wdelete-non-virtual-dtor (C++ and Objective-C++ only) — warn when delete is used to destroy an instance of a class that has virtual functions and non-virtual destructor. It is unsafe to delete an instance of a derived class through a pointer to a base class if the base class does not have a virtual destructor. This warning is enabled by -Wall. 💀
  • -Wdeprecated-copy (C++ and Objective-C++ only) — warn that the implicit declaration of a copy constructor or copy assignment operator is deprecated if the class has a user-provided copy constructor or copy assignment operator, in C++11 and up. This warning is enabled by -Wextra. With -Wdeprecated-copy-dtor, also deprecate if the class has a user-provided destructor. 🌈
  • -Wno-deprecated-enum-enum-conversion (C++ and Objective-C++ only) — disable the warning about the case when the usual arithmetic conversions are applied on operands where one is of enumeration type and the other is of a different enumeration type. This conversion was deprecated in C++20. For example:
enum E1 { e };
enum E2 { f };
int k = f - e;

-Wdeprecated-enum-enum-conversion is enabled by default with -std=c++20. In pre-C++20 dialects, this warning can be enabled by -Wenum-conversion. ✨

  • -Wno-deprecated-enum-float-conversion (C++ and Objective-C++ only) — disable the warning about the case when the usual arithmetic conversions are applied on operands where one is of enumeration type and the other is of a floating-point type. This conversion was deprecated in C++20. For example:
enum E1 { e };
enum E2 { f };
bool b = e <= 3.7;

-Wdeprecated-enum-float-conversion is enabled by default with -std=c++20. In pre-C++20 dialects, this warning can be enabled by -Wenum-conversion. 🦋

  • -Wno-init-list-lifetime (C++ and Objective-C++ only) — do not warn about uses of std::initializer_list that are likely to result in dangling pointers. Since the underlying array for an initializer_list is handled like a normal C++ temporary object, it is easy to inadvertently keep a pointer to the array past the end of the array's lifetime. For example:
    • If a function returns a temporary initializer_list, or a local initializer_list variable, the array's lifetime ends at the end of the return statement, so the value returned has a dangling pointer.
    • If a new-expression creates an initializer_list, the array only lives until the end of the enclosing full-expression, so the initializer_list in the heap has a dangling pointer. 💅
  • 🫶 so like, when you assign an initializer_list variable from a brace-enclosed initializer list, the temporary array made for the right side of the assignment only lives until the end of the full-expression — which means at the very next statement, that initializer_list variable is holding a dangling pointer. yikes.
// li's initial underlying array lives as long as li
std::initializer_list<int> li = { 1,2,3 };
// assignment changes li to point to a temporary array
li = { 4, 5 };
// now the temporary is gone and li has a dangling pointer
int i = li.begin()[0] // undefined behavior
  • and when a list constructor stores the begin pointer from the initializer_list argument, that does not extend the lifetime of the array 😭 so if a class variable gets constructed from a temporary initializer_list, that pointer is left dangling by the end of the variable declaration statement. no cap, it's just gone.

  • -Winvalid-imported-macros — verifies that all imported macro definitions are valid at the end of compilation ✨ this one is not enabled by default, because it needs extra processing to figure out. lowkey it's a good idea when you're prepping sets of header-units and you wanna make sure the macros stay consistent 🎀
  • -Wno-literal-suffix (C++ and Objective-C++ only) — this one like, stops the warning when a string or character literal is followed by a ud-suffix that doesn't start with an underscore. as a conforming extension, GCC treats those suffixes as separate preprocessing tokens so old code using formatting macros from <inttypes.h> keeps working. for example:
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>

int main() {
  int64_t i64 = 123;
  printf("My int64: %" PRId64"\n", i64);
}

in this case, PRId64 is treated as a separate preprocessing token 💅

this option also controls the warnings when a user-defined literal operator is declared with a literal suffix identifier that doesn't begin with an underscore — and those suffixes are reserved for future standardization, so like, don't 🔥

these warnings are enabled by default.

  • -Wno-narrowing (C++ and Objective-C++ only) — for C++11 and later standards, narrowing conversions are diagnosed by default, as the standard requires 👑 a narrowing conversion from a constant produces an error, and from a non-constant produces a warning, but -Wno-narrowing suppresses the diagnostic. note that this does not affect the meaning of well-formed code — narrowing conversions are still considered ill-formed in SFINAE contexts 🦋

with -Wnarrowing in C++98, you get a warning when a narrowing conversion prohibited by C++11 happens inside { }, like:

int i = { 2.2 }; // error: narrowing from double to int

this flag is included in -Wall and -Wc++11-compat ⭐

  • -Wnoexcept (C++ and Objective-C++ only) — warns when a noexcept-expression evaluates to false because of a call to a function that doesn't have a non-throwing exception specification (i.e. throw() or noexcept) but that the compiler knows will never throw an exception 🙈
  • -Wnoexcept-type (C++ and Objective-C++ only) — warns if the C++17 feature that makes noexcept part of a function type changes the mangled name of a symbol compared to C++14. enabled by -Wabi and -Wc++17-compat 🎀

example time:

template <class T> void f(T t) { t(); };
void g() noexcept;
void h() { f(g); }

in C++14, f calls f<void(*)()>, but in C++17 it calls f<void(*)()noexcept> 💀

  • -Wclass-memaccess (C++ and Objective-C++ only) — warns when the destination of a call to a raw memory function like memset or memcpy is an object of class type, and when writing into that object might bypass the class's non-trivial or deleted constructor or copy assignment, violate const-correctness or encapsulation, or corrupt virtual table pointers 😭 modifying the representation of those objects may violate invariants that member functions of the class maintain. for example, the memset call below is undefined because it modifies a non-trivial class object, so it gets diagnosed. the safe way to initialize or clear the storage of such types is using the appropriate constructor or assignment operator, if one exists:
std::string str = "abc";
memset (&str, 0, sizeof str);

-Wclass-memaccess is enabled by -Wall ✨ and explicitly casting the pointer to the class object to void * or to a type the raw memory function can safely access suppresses the warning 🫶

  • -Wnon-virtual-dtor (C++ and Objective-C++ only) — warns when a class has virtual functions and an accessible non-virtual destructor, either itself or in an accessible polymorphic base class — in which case deleting an instance of a derived class through a pointer to the class itself or base class is possible but unsafe 💀 this warning is automatically enabled if -Weffc++ is specified.
  • -Wregister (C++ and Objective-C++ only) — warns on uses of the register storage class specifier, except when it's part of the GNU Explicit Register Variables extension. using register as a storage class specifier has been deprecated in C++11 and removed in C++17 😭 enabled by default with -std=c++17 🔥
  • -Wreorder (C++ and Objective-C++ only) — warns when the order of member initializers in your code doesn't match the order they actually get executed in. for instance:
struct A {
  int i;
  int j;
  A(): j (0), i (1) { }
};

the compiler rearranges the member initializers for i and j to match the declaration order of the members, and throws a warning to that effect 💅 this warning is enabled by -Wall.

  • -Wno-pessimizing-move (C++ and Objective-C++ only) — warns when a call to std::move prevents copy elision 😭 a typical scenario where copy elision can occur is returning in a function with a class return type, when the expression being returned is the name of a non-volatile automatic object, isn't a function parameter, and has the same type as the function return type:
struct T {
...
};
T fn()
{
  T t;
  ...
  return std::move (t);
}

but in this example, that std::move call prevents copy elision 🫠 this warning is enabled by -Wall.

  • -Wno-redundant-move (C++ and Objective-C++ only) — warns about redundant calls to std::move — like, when a move operation would've happened even without the std::move call 🙈 this happens because the compiler is forced to treat the object as if it were an rvalue in certain situations, like returning a local variable, where copy elision isn't applicable. consider:
struct T {
...
};
T fn(T t)
{
  ...
  return std::move (t);
}

here, the std::move call is redundant. because G++ implements Core Issue 1579, another example is:

struct T { // convertible to U
...
};
struct U {
...
};
U fn()
{
  T t;
  ...
  return std::move (t);
}

in this example, copy elision isn't applicable because the type of the expression being returned and the function return type differ — yet G++ treats the return value as if it were designated by an rvalue ✨ this warning is enabled by -Wextra.

  • -Wrange-loop-construct (C++ and Objective-C++ only) — warns when a C++ range-based for-loop is making an unnecessary copy 🎀 this can happen when the range declaration isn't a reference but probably should be. for example:
struct S { char arr[128]; };
void fn () {
  S arr[5];
  for (const auto x : arr) { ... }
}

it does not warn when the type being copied is a trivially-copyable type whose size is less than 64 bytes 💅

it also warns when a loop variable in a range-based for-loop is initialized with a value of a different type, resulting in a copy. like:

void fn() {
  int arr[10];
  for (const double &x : arr) { ... }
}

in the example above, every iteration of the loop creates and destroys a temporary value of type double, and the reference const double & is bound to it 😭 this warning is enabled by -Wall.

  • -Wredundant-tags (C++ and Objective-C++ only) — warns about redundant class-key and enum-key in references to class types and enumerated types in contexts where the key can be dropped without causing ambiguity. for example:
struct foo;
struct foo *p;   // warn that keyword struct can be eliminated

on the other hand, in this example there's no warning:

struct foo;
void foo ();   // "hides" struct foo
void bar (struct foo&);  // no warning, keyword struct is necessary
  • -Wno-subobject-linkage (C++ and Objective-C++ only) — don't warn if a class type has a base or a field whose type uses the anonymous namespace or depends on a type with no linkage 🦋 if a type A depends on a type B with no or internal linkage, defining A in multiple translation units would be an ODR violation, because the meaning of B is different in each translation unit. if A only appears in one translation unit, the best way to silence the warning is to give it internal linkage by putting it in an anonymous namespace too 💜 the compiler doesn't give this warning for types defined in the main .C file, since those are unlikely to have multiple definitions. -Wsubobject-linkage is enabled by default.
  • -Weffc++ (C++ and Objective-C++ only) — warns about violations of these style guidelines from Scott Meyers' Effective C++ series of books 👑 …
  • Define a copy constructor and an assignment operator for classes that have dynamically-allocated memory. Like, if your class owns memory, it needs to know how to copy itself properly, bestie 💖
  • Prefer initialization to assignment in constructors. Initializer lists are the moment, it's giving main character energy ✨
  • Have operator= return a reference to *this — chainable assignment or bust 👑
  • Don't try to return a reference when you must return an object — return by value when you gotta, no cap
  • Distinguish between prefix and postfix forms of increment and decrement operators
  • Never overload &&, ||, or , — just don't, the short-circuit vibes are sacred 🚫

So this option also turns on -Wnon-virtual-dtor, which is also one of the effective C++ recommendations. But bestie, the check gets extended — it also warns you when an accessible non-polymorphic base class is missing a virtual destructor 🫶

Heads up: when you select this option, be aware that the standard library headers do not obey all of these guidelines. Use grep -v to filter out those warnings, iykyk 🌸

-Wno-exceptions (C++ and Objective-C++ only)

Turns off the warning for when an exception handler is shadowed by another handler. Lowkey this one is useful because it points out a wrong ordering of exception handlers — like, the order matters, bestie 😭

-Wstrict-null-sentinel (C++ and Objective-C++ only)

Warns about using an uncasted NULL as a sentinel. When you're compiling only with GCC this is a valid sentinel, since NULL is defined to __null. And even though it's a null pointer constant rather than a null pointer, it's guaranteed to be the same size as a pointer. But ngl this use is not portable across different compilers — so like, don't ship it everywhere 💀

-Wno-non-template-friend (C++ and Objective-C++ only)

Disables the warning for when non-template friend functions are declared inside a template. Okay so history lesson: in very old versions of GCC that predate implementation of the ISO standard, declarations like friend int foo(int) — where the name of the friend is an unqualified-id — could be interpreted as a particular specialization of a template function. The warning exists to diagnose these compatibility problems, and it's enabled by default 🦋

-Wold-style-cast (C++ and Objective-C++ only)

Warns if you use an old-style (C-style) cast to a non-void type inside a C++ program. The new-style casts (dynamic_cast, static_cast, reinterpret_cast, and const_cast) are less vulnerable to unintended effects and wayyy easier to search for. Glow up your casts, bestie 💅

-Woverloaded-virtual (C++ and Objective-C++ only)

Warns when a function declaration hides virtual functions from a base class. Example time — say you've got:

struct A {
  virtual void f();
};

struct B: public A {
  void f(int);
};

The A class version of f is hidden in B, and then code like this:

B* b;
b->f();

fails to compile. Oops 🙈

-Wno-pmf-conversions (C++ and Objective-C++ only)

Disables the diagnostic for converting a bound pointer to member function into a plain pointer.

-Wsign-promo (C++ and Objective-C++ only)

Warns when overload resolution picks a promotion from unsigned or enumerated type to a signed type, over a conversion to an unsigned type of the same size. Previous versions of G++ tried to preserve unsignedness, but the standard mandates the current behavior. Not us making the rules, we just follow them 🤷

-Wtemplates (C++ and Objective-C++ only)

Warns when a primary template declaration is encountered. Some coding rules disallow templates, and this can be used to enforce that rule. The warning is inactive inside a system header file — like the STL — so you can still use the STL, don't worry 🎀 You may also instantiate or specialize templates.

-Wmismatched-new-delete (C++ and Objective-C++ only)

Warns for mismatches between calls to operator new or operator delete and the corresponding call to the allocation or deallocation function. This includes invocations of C++ operator delete with pointers returned from either mismatched forms of operator new, or from other functions that allocate objects for which the operator delete isn't a suitable deallocator. Also covers calls to other deallocation functions with pointers returned from operator new for which the deallocation function isn't suitable 🔥

For example, the delete expression in the function below is diagnosed because it doesn't match the array form of the new expression the pointer argument was returned from. Similarly, the call to free is also diagnosed:

void f ()
{
  int *a = new int[n];
  delete a;   // warning: mismatch in array forms of expressions

  char *p = new char[n];
  free (p);   // warning: mismatch between new and free
}

The related option -Wmismatched-dealloc diagnoses mismatches involving allocation and deallocation functions other than operator new and operator delete.

-Wmismatched-new-delete is included in -Wall ⭐

-Wmismatched-tags (C++ and Objective-C++ only)

Warns for declarations of structs, classes, and class templates and their specializations with a class-key that doesn't match either the definition or the first declaration if no definition is provided.

Okay for example, the declaration of struct Object in the argument list of draw triggers the warning. To avoid it, either remove the redundant class-key struct or replace it with class to match its definition:

class Object {
public:
  virtual ~Object () = 0;
};
void draw (struct Object*);

It is not wrong to declare a class with the class-key struct — the example above shows that. The -Wmismatched-tags option is meant to help you get a consistent style of class declarations. And in code that's intended to be portable to Windows-based compilers, the warning helps prevent unresolved references caused by the difference in the mangling of symbols declared with different class-keys. You can use the option on its own or together with -Wredundant-tags 🧚

-Wmultiple-inheritance (C++ and Objective-C++ only)

Warns when a class is defined with multiple direct base classes. Some coding rules disallow multiple inheritance, and this may be used to enforce that rule. The warning is inactive inside a system header file — like the STL — so you can still use the STL 💜 You may also define classes that indirectly use multiple inheritance.

-Wvirtual-inheritance

Warns when a class is defined with a virtual direct base class. Some coding rules disallow multiple inheritance, and this may be used to enforce that rule. The warning is inactive inside a system header file — such as the STL — so you can still use the STL 🌈 You may also define classes that indirectly use virtual inheritance.

-Wno-virtual-move-assign

Suppresses warnings about inheriting from a virtual base with a non-trivial C++11 move assignment operator. And okay, this one is genuinely dangerous — because if the virtual base is reachable along more than one path, it gets moved multiple times, which can mean both objects end up in the moved-from state 😭 If the move assignment operator is written to avoid moving from a moved-from object, then you can disable this warning. But like, be careful, fr fr.

-Wnamespaces

Warns when a namespace definition is opened. Some coding rules disallow namespaces, and this may be used to enforce that rule. The warning is inactive inside a system header file — like the STL — so you can still use the STL 🍓 You may also use using directives and qualified names.

-Wno-terminate (C++ and Objective-C++ only)

Disables the warning about a throw-expression that will immediately result in a call to terminate. Like, it was never gonna make it bestie 💀

-Wno-vexing-parse (C++ and Objective-C++ only)

Warns about the most vexing parse syntactic ambiguity. This warns about the cases where a declaration looks like a variable definition, but the C++ language requires it to be interpreted as a function declaration. For instance:

void f(double a) {
  int i();        // extern int i (void);
  int n(int(a));  // extern int n (int);
}

Another example:

struct S { S(int); };
void f(double a) {
  S x(int(a));   // extern struct S x (int);
  S y(int());    // extern struct S y (int (*) (void));
  S z();         // extern struct S z (void);
}

The warning will suggest options for how to deal with such an ambiguity — e.g., it can suggest removing the parentheses or using braces instead. Iconic behaviour honestly 👑

This warning is enabled by default.

-Wno-class-conversion (C++ and Objective-C++ only)

Do not warn when a conversion function converts an object to the same type, to a base class of that type, or to void. Such a conversion function will never be called, so like... why 😭

-Wvolatile (C++ and Objective-C++ only)

Warns about deprecated uses of the volatile qualifier. This includes:

  • postfix and prefix ++ and -- expressions of volatile-qualified types
  • using simple assignments where the left operand is a volatile-qualified non-class type for their value
  • compound assignments where the left operand is a volatile-qualified non-class type
  • volatile-qualified function return type
  • volatile-qualified parameter type
  • structured bindings of a volatile-qualified type

This usage was deprecated in C++20, so it's giving "old code era" 🕰️

Enabled by default with -std=c++20.

-Wzero-as-null-pointer-constant (C++ and Objective-C++ only)

Warns when a literal 0 is used as a null pointer constant. This can be useful to help with the conversion to nullptr in C++11. Say it with me: nullptr is the moment ✨

-Waligned-new

Warns about a new-expression of a type that requires greater alignment than alignof(std::max_align_t) but uses an allocation function without an explicit alignment parameter. This option is enabled by -Wall.

Normally this only warns about global allocation functions, but -Waligned-new=all also warns about class member allocation functions. Extra thorough, love that for us 💅

-Wno-placement-new / -Wplacement-new=n

Warns about placement new expressions with undefined behavior — like constructing an object in a buffer that's smaller than the type of the object. For example, the placement new expression below is diagnosed because it attempts to construct an array of 64 integers in a buffer only 64 bytes large:

char buf [64];
new (buf) int[64];

That's a no from me, chief 🙈

This warning is enabled by default.

  • -Wplacement-new=1 — this is the default warning level for -Wplacement-new, bestie. At this level the warning is not issued for some strictly undefined constructs that GCC allows as extensions so it stays compatible with legacy code. Like, for example, this new expression is not diagnosed at this level even though it has undefined behavior according to the C++ standard, because it writes past the end of the one-element array:
struct S { int n, a[1]; };
S *s = (S *)malloc (sizeof *s + 31 * sizeof s->a[0]);
new (s->a)int [32]();
  • -Wplacement-new=2 — at this level, on top of diagnosing all the same constructs as at level 1, a diagnostic is also issued for placement new expressions that construct an object in the last member of a structure whose type is an array of a single element and whose size is less than the size of the object being constructed. So the previous example would get diagnosed, but the following construct uses the flexible member array extension to dodge the warning at level 2:
struct S { int n, a[]; };
S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]);
new (s->a)int [32]();

  • -Wcatch-value / -Wcatch-value=n (C++ and Objective-C++ only) — warns you about catch handlers that don't catch via reference. With -Wcatch-value=1 (or just -Wcatch-value for short) it warns about polymorphic class types that are caught by value. With -Wcatch-value=2 it warns about all class types that are caught by value. With -Wcatch-value=3 it warns about all types that are not caught by reference. And btw, -Wcatch-value is enabled by -Wall. 🫶
  • -Wconditionally-supported (C++ and Objective-C++ only) — warns for conditionally-supported (C++11 [intro.defs]) constructs. iykyk.
  • -Wno-delete-incomplete (C++ and Objective-C++ only) — do not warn when deleting a pointer to an incomplete type, which may cause undefined behavior at runtime. This warning is enabled by default (yes, that's why you're here turning it off).
  • -Wextra-semi (C++, Objective-C++ only) — warns about redundant semicolons after in-class function definitions. the way those stray ; pile up... 💀
  • -Wno-inaccessible-base (C++, Objective-C++ only) — this option controls warnings for when a base class is inaccessible in a class derived from it due to ambiguity. The warning is enabled by default. Note that the warning for ambiguous virtual bases is enabled by the -Wextra option.
struct A { int a; };

struct B : A { };

struct C : B, A { };
  • -Wno-inherited-variadic-ctor — suppresses warnings about use of C++11 inheriting constructors when the base class inherited from has a C variadic constructor. The warning is on by default because the ellipsis is not inherited. 🙈
  • -Wno-invalid-offsetof (C++ and Objective-C++ only) — suppresses warnings from applying the offsetof macro to a non-POD type. According to the 2014 ISO C++ standard, applying offsetof to a non-standard-layout type is undefined. In existing C++ implementations, however, offsetof typically gives meaningful results. This flag is for users who are fully aware that they are writing nonportable code and who have deliberately chosen to ignore the warning about it. Also, heads up: the restrictions on offsetof may be relaxed in a future version of the C++ standard. 👑
  • -Wsized-deallocation (C++ and Objective-C++ only) — warns about a definition of an unsized deallocation function
void operator delete (void *) noexcept;
void operator delete[] (void *) noexcept;

without a definition of the corresponding sized deallocation function

void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;

or vice versa. Enabled by -Wextra along with -fsized-deallocation.

  • -Wsuggest-final-types — warns about types with virtual methods where code quality would be improved if the type were declared with the C++11 final specifier, or, if possible, declared in an anonymous namespace. This allows GCC to more aggressively devirtualize the polymorphic calls. This warning is more effective with link-time optimization, where the information about the class hierarchy graph is more complete. ✨
  • -Wsuggest-final-methods — warns about virtual methods where code quality would be improved if the method were declared with the C++11 final specifier, or, if possible, its type were declared in an anonymous namespace or with the final specifier. This warning is more effective with link-time optimization, where the information about the class hierarchy graph is more complete. Recommendation from the manpage itself: first consider suggestions of -Wsuggest-final-types and then rebuild with new annotations. 🌸
  • -Wsuggest-override — warns about overriding virtual functions that are not marked with the override keyword. literally just add the keyword, bestie.
  • -Wuse-after-free / -Wuse-after-free=n — warns about uses of pointers to dynamically allocated objects that have been rendered indeterminate by a call to a deallocation function. The warning is enabled at all optimization levels but may yield different results with optimization than without. 👀
    • -Wuse-after-free=1 — at level 1 the warning attempts to diagnose only unconditional uses of pointers made indeterminate by a deallocation call or a successful call to realloc, regardless of whether or not the call resulted in an actual reallocation of memory. This includes double-free calls as well as uses in arithmetic and relational expressions. Although undefined, uses of indeterminate pointers in equality (or inequality) expressions are not diagnosed at this level.
    • -Wuse-after-free=2 — at level 2, in addition to unconditional uses, the warning also diagnoses conditional uses of pointers made indeterminate by a deallocation call. As at level 2, uses in equality (or inequality) expressions are not diagnosed. For example, the second call to free in the following function is diagnosed at this level:
struct A { int refcount; void *data; };

void release (struct A *p)
{
  int refcount = --p->refcount;
  free (p);
  if (refcount == 0)
    free (p->data);   // warning: p may be used after free
}
  • -Wuse-after-free=3 — at level 3, the warning also diagnoses uses of indeterminate pointers in equality expressions. All uses of indeterminate pointers are undefined, but equality tests sometimes appear after calls to realloc as an attempt to determine whether the call resulted in relocating the object to a different address. They are diagnosed at a separate level to aid legacy code in gradually transitioning to safe alternatives. For example, the equality test in the function below is diagnosed at this level:
void adjust_pointers (int**, int);

void grow (int **p, int n)
{
  int **q = (int**)realloc (p, n *= 2);
  if (q == p)
    return;
  adjust_pointers ((int**)q, n);
}

To avoid the warning at this level, store offsets into allocated memory instead of pointers. This approach obviates needing to adjust the stored pointers after reallocation. 🧚

-Wuse-after-free=2 is included in -Wall.
  • -Wuseless-cast (C++ and Objective-C++ only) — warns when an expression is casted to its own type. like... why would you even.
  • -Wno-conversion-null (C++ and Objective-C++ only) — do not warn for conversions between NULL and non-pointer types. And -Wconversion-null is enabled by default. 💅

💜 Options Controlling Objective-C and Objective-C++ Dialects 💜

NOTE: This manual does not describe the Objective-C and Objective-C++ languages themselves.

This section describes the command-line options that are only meaningful for Objective-C and Objective-C++ programs. You can also use most of the language-independent GNU compiler options. For example, you might compile a file some_class.m like this:

gcc -g -fgnu-runtime -O -c some_class.m

In this example, -fgnu-runtime is an option meant only for Objective-C and Objective-C++ programs; you can use the other options with any language supported by GCC.

Also note that since Objective-C is an extension of the C language, Objective-C compilations may also use options specific to the C front-end (e.g., -Wtraditional). Similarly, Objective-C++ compilations may use C++-specific options (e.g., -Wabi).

Here is a list of options that are only for compiling Objective-C and Objective-C++ programs:

  • -fconstant-string-class=class-name — use class-name as the name of the class to instantiate for each literal string specified with the syntax @"...". The default class name is NXConstantString if the GNU runtime is being used, and NSConstantString if the NeXT runtime is being used (see below). The -fconstant-cfstrings option, if also present, overrides the -fconstant-string-class setting and causes @"..." literals to be laid out as constant CoreFoundation strings. 🎀
  • -fgnu-runtime — generate object code compatible with the standard GNU Objective-C runtime. This is the default for most types of systems.
  • -fnext-runtime — generate output compatible with the NeXT runtime. This is the default for NeXT-based systems, including Darwin and Mac OS X. The macro __NEXT_RUNTIME__ is predefined if (and only if) this option is used.
  • -fno-nil-receivers — assume that all Objective-C message dispatches ([receiver message:arg]) in this translation unit ensure that the receiver is not nil. This allows for more efficient entry points in the runtime to be used. This option is only available in conjunction with the NeXT runtime and ABI version 0 or 1. 🌈
  • -fobjc-abi-version=n — okay so this one says use version n of the Objective-C ABI for the runtime you selected, bestie. Right now it’s only supported for the NeXT runtime. In that case, Version 0 is the traditional (32-bit) ABI without support for properties and other Objective-C 2.0 additions. Version 1 is the traditional (32-bit) ABI with support for properties and other Objective-C 2.0 additions. Version 2 is the modern (64-bit) ABI. If nothing is specified, the default is Version 0 on 32-bit target machines, and Version 2 on 64-bit target machines.
  • -fobjc-call-cxx-cdtors — this is the C++ constructor/destructor girlie for Objective-C classes. For each Objective-C class, check if any of its instance variables is a C++ object with a non-trivial default constructor. If so, synthesize a special - (id) .cxx_construct instance method which runs non-trivial default constructors on any such instance variables, in order, and then return self. Similarly, check if any instance variable is a C++ object with a non-trivial destructor, and if so, synthesize a special - (void) .cxx_destruct method which runs all such default destructors, in reverse order.

The - (id) .cxx_construct and - (void) .cxx_destruct methods thusly generated only operate on instance variables declared in the current Objective-C class, and not those inherited from superclasses. It is the responsibility of the Objective-C runtime to invoke all such methods in an object's inheritance hierarchy. The - (id) .cxx_construct methods are invoked by the runtime immediately after a new object instance is allocated; the - (void) .cxx_destruct methods are invoked immediately before the runtime deallocates an object instance.

As of this writing, only the NeXT runtime on Mac OS X 10.4 and later has support for invoking the - (id) .cxx_construct and - (void) .cxx_destruct methods.

  • -fobjc-direct-dispatch — allow fast jumps to the message dispatcher. On Darwin this is accomplished via the comm page. speedy message tea 🫶
  • -fobjc-exceptions — enable syntactic support for structured exception handling in Objective-C, similar to what is offered by C++. This option is required to use the Objective-C keywords @try, @throw, @catch, @finally and @synchronized. This option is available with both the GNU runtime and the NeXT runtime (but not available in conjunction with the NeXT runtime on Mac OS X 10.2 and earlier).
  • -fobjc-gc — enable garbage collection (GC) in Objective-C and Objective-C++ programs. This option is only available with the NeXT runtime; the GNU runtime has a different garbage collection implementation that does not require special compiler flags. no extra flags needed over there, iykyk 💅
  • -fobjc-nilcheck — for the NeXT runtime with version 2 of the ABI, check for a nil receiver in method invocations before doing the actual method call. This is the default and can be disabled using -fno-objc-nilcheck. Class methods and super calls are never checked for nil in this way no matter what this flag is set to. Currently this flag does nothing when the GNU runtime, or an older version of the NeXT runtime ABI, is used.
  • -fobjc-std=objc1 — conform to the language syntax of Objective-C 1.0, the language recognized by GCC 4.0. This only affects the Objective-C additions to the C/C++ language; it does not affect conformance to C/C++ standards, which is controlled by the separate C/C++ dialect option flags. When this option is used with the Objective-C or Objective-C++ compiler, any Objective-C syntax that is not recognized by GCC 4.0 is rejected. This is useful if you need to make sure that your Objective-C code can be compiled with older versions of GCC.
  • -freplace-objc-classes — emit a special marker instructing ld(1) not to statically link in the resulting object file, and allow dyld(1) to load it in at run time instead. This is used in conjunction with the Fix-and-Continue debugging mode, where the object file in question may be recompiled and dynamically reloaded in the course of program execution, without the need to restart the program itself. Currently, Fix-and-Continue functionality is only available in conjunction with the NeXT runtime on Mac OS X 10.3 and later.
  • -fzero-link — when compiling for the NeXT runtime, the compiler ordinarily replaces calls to objc_getClass("...") (when the name of the class is known at compile time) with static class references that get initialized at load time, which improves run-time performance. Specifying the -fzero-link flag suppresses this behavior and causes calls to objc_getClass("...") to be retained. This is useful in Zero-Link debugging mode, since it allows for individual class implementations to be modified during program execution. The GNU runtime currently always retains calls to objc_get_class("...") regardless of command-line options.
  • -fno-local-ivars — by default instance variables in Objective-C can be accessed as if they were local variables from within the methods of the class they're declared in. This can lead to shadowing between instance variables and other variables declared either locally inside a class method or globally with the same name. Specifying the -fno-local-ivars flag disables this behavior thus avoiding variable shadowing issues.
  • -fivar-visibility=[public|protected|private|package] — set the default instance variable visibility to the specified option so that instance variables declared outside the scope of any access modifier directives default to the specified visibility. visibility check, but make it default ✨
  • -gen-decls — dump interface declarations for all classes seen in the source file to a file named sourcename.decl. Literally all the class interface tea, in one file.
  • -Wassign-intercept (Objective-C and Objective-C++ only) — warn whenever an Objective-C assignment is being intercepted by the garbage collector.
  • -Wno-property-assign-default (Objective-C and Objective-C++ only) — do not warn if a property for an Objective-C object has no assign semantics specified.
  • -Wno-protocol (Objective-C and Objective-C++ only) — if a class is declared to implement a protocol, a warning is issued for every method in the protocol that is not implemented by the class. The default behavior is to issue a warning for every method not explicitly implemented in the class, even if a method implementation is inherited from the superclass. If you use the -Wno-protocol option, then methods inherited from the superclass are considered to be implemented, and no warning is issued for them.
  • -Wobjc-root-class (Objective-C and Objective-C++ only) — warn if a class interface lacks a superclass. Most classes will inherit from NSObject (or Object) for example. When declaring classes intended to be root classes, the warning can be suppressed by marking their interfaces with __attribute__((objc_root_class)).
  • -Wselector (Objective-C and Objective-C++ only) — warn if multiple methods of different types for the same selector are found during compilation. The check is performed on the list of methods in the final stage of compilation. Additionally, a check is performed for each selector appearing in a @selector(...) expression, and a corresponding method for that selector has been found during compilation. Because these checks scan the method table only at the end of compilation, these warnings are not produced if the final stage of compilation is not reached, for example because an error is found during compilation, or because the -fsyntax-only option is being used. end-of-compilation vibes only ⭐
  • -Wstrict-selector-match (Objective-C and Objective-C++ only) — warn if multiple methods with differing argument and/or return types are found for a given selector when attempting to send a message using this selector to a receiver of type id or Class. When this flag is off (which is the default behavior), the compiler omits such warnings if any differences found are confined to types that share the same size and alignment.
  • -Wundeclared-selector (Objective-C and Objective-C++ only) — warn if a @selector(...) expression referring to an undeclared selector is found. A selector is considered undeclared if no method with that name has been declared before the @selector(...) expression, either explicitly in an @interface or @protocol declaration, or implicitly in an @implementation section. This option always performs its checks as soon as a @selector(...) expression is found, while -Wselector only performs its checks in the final stage of compilation. This also enforces the coding style convention that methods and selectors must be declared before being used.
  • -print-objc-runtime-info — generate C header describing the largest structure that is passed by value, if any.

✨ Options to Control Diagnostic Messages Formatting ✨

Traditionally, diagnostic messages have been formatted irrespective of the output device's aspect (e.g. its width, ...). You can use the options described below to control the formatting algorithm for diagnostic messages, e.g. how many characters per line, how often source location information should be reported. Note that some language front ends may not honor these options. respect the formatting options, bestie 🫶

  • -fmessage-length=n — try to format error messages so that they fit on lines of about n characters. If n is zero, then no line-wrapping is done; each error message appears on a single line. This is the default for all front ends.

Note - this option also affects the display of the #error and #warning pre-processor directives, and the deprecated function/type/variable attribute. It does not however affect the pragma GCC warning and pragma GCC error pragmas.

  • -fdiagnostics-plain-output — this option requests that diagnostic output look as plain as possible, which may be useful when running dejagnu or other utilities that need to parse diagnostics output and prefer that it remain more stable over time. -fdiagnostics-plain-output is currently equivalent to the following options: -fno-diagnostics-show-caret -fno-diagnostics-show-line-numbers -fdiagnostics-color=never -fdiagnostics-urls=never -fdiagnostics-path-format=separate-events In the future, if GCC changes the default appearance of its diagnostics, the corresponding option to disable the new behavior will be added to this list.
  • -fdiagnostics-show-location=once — bestie this one is literally only a thing in line-wrapping mode, okay? It tells the diagnostic reporter to drop the source location info, like, once — so if a message is too long to fit on one physical line and has to wrap, you won't get the source location repeated as a prefix over and over on every single continuation line. This is the default behavior, so yeah, it's already doing this unless you go messing with it 💅
  • -fdiagnostics-show-location=every-line — again, only meaningful in line-wrapping mode, no cap. This one makes the reporter emit that same source location info (as a prefix) on every physical line that comes out of breaking a too-long message. So if you love seeing the same file:line:col scroll past you ten times, this is your moment, go off 🎀

🌈 the color situation 🌈

  • -fdiagnostics-color[=WHEN], -fno-diagnostics-color — do we want color in our diagnostics or not, that's the whole vibe check. WHEN is never, always, or auto. The default depends on how the compiler was configured, so it can be any of those WHEN values — or also never if the GCC_COLORS environment variable isn't present in the environment, and auto otherwise. auto makes GCC use color only when standard error is a terminal, and when it's not running inside an emacs shell 🦋

Also: -fdiagnostics-color and -fno-diagnostics-color are literally just aliases for -fdiagnostics-color=always and -fdiagnostics-color=never, respectively. Slay, convenience.

The colors themselves are defined by the environment variable GCC_COLORS. Its value is a colon-separated list of capabilities and Select Graphic Rendition (SGR) substrings. SGR commands get interpreted by your terminal or terminal emulator. (Go look at the section in your text terminal's documentation for the permitted values and what they mean as character attributes — that's a you-and-your-terminal thing.) These substring values are integers in decimal representation and can be concatenated with semicolons ✨

Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. Icons only 🔥

The default GCC_COLORS is:

        error=01;31:warning=01;35:note=01;36:range1=32:range2=34:locus=01:\
        quote=01:path=01;36:fixit-insert=32:fixit-delete=31:\
        diff-filename=01:diff-hunk=32:diff-delete=31:diff-insert=32:\
        type-diff=01;32

where 01;31 is bold red, 01;35 is bold magenta, 01;36 is bold cyan, 32 is green, 34 is blue, 01 is bold, and 31 is red. Setting GCC_COLORS to the empty string disables colors — ghost mode 👻

Supported capabilities are as follows, bestie, take notes:

  • "error=" — SGR substring for error: markers.
  • "warning=" — SGR substring for warning: markers.
  • "note=" — SGR substring for note: markers.
  • "path=" — SGR substring for colorizing paths of control-flow events as printed via -fdiagnostics-path-format=, such as the identifiers of individual events and lines indicating interprocedural calls and returns.
  • "range1=" — SGR substring for first additional range.
  • "range2=" — SGR substring for second additional range.
  • "locus=" — SGR substring for location information, file:line or file:line:column etc.
  • "quote=" — SGR substring for information printed within quotes.
  • "fixit-insert=" — SGR substring for fix-it hints suggesting text to be inserted or replaced.
  • "fixit-delete=" — SGR substring for fix-it hints suggesting text to be deleted.
  • "diff-filename=" — SGR substring for filename headers within generated patches.
  • "diff-hunk=" — SGR substring for the starts of hunks within generated patches.
  • "diff-delete=" — SGR substring for deleted lines within generated patches.
  • "diff-insert=" — SGR substring for inserted lines within generated patches.
  • "type-diff=" — SGR substring for highlighting mismatching types within template arguments in the C++ frontend.

  • -fdiagnostics-urls[=WHEN] — this one is giving "make diagnostics clickable" energy ✨ It uses escape sequences to embed URLs in diagnostics. For example, when -fdiagnostics-show-option emits text showing the command-line option that controls a diagnostic, it embeds a URL for the documentation of that option. Obsessed with the cross-referencing, honestly.

WHEN is never, always, or auto. auto makes GCC use URL escape sequences only when standard error is a terminal, and when it's not running inside an emacs shell or any graphical terminal which is known to be incompatible with this feature — see below, there's a whole list 🙈

The default depends on how the compiler has been configured. It can be any of the above WHEN options.

GCC can also be configured (via the --with-diagnostics-urls=auto-if-env configure-time option) so that the default is affected by environment variables. Under such a configuration, GCC defaults to using auto if either GCC_URLS or TERM_URLS environment variables are present and non-empty in the environment of the compiler, or never if neither are.

But wait — even with -fdiagnostics-urls=always the behavior is dependent on those environment variables:

  • If GCC_URLS is set to empty or no, do not embed URLs in diagnostics.
  • If set to st, URLs use ST escape sequences.
  • If set to bel, the default, URLs use BEL escape sequences.
  • Any other non-empty value enables the feature.
  • If GCC_URLS is not set, use TERM_URLS as a fallback.
Fun fact bestie: ST is an ANSI escape sequence, string terminator ESC \. BEL is an ASCII character, CTRL-G, that usually sounds like a beep 💀 so yes, your terminal may literally go beep.

At this time GCC tries to detect also a few terminals that are known to not implement the URL feature, and have bugs or at least had bugs in some versions that are still in use, where the URL escapes are likely to misbehave, i.e. print garbage on the screen 😭 That list is currently xfce4-terminal, certain known to be buggy gnome-terminal versions, the linux console, and mingw. This check can be skipped with -fdiagnostics-urls=always — your screen, your choice, main character energy.


  • -fno-diagnostics-show-option — by default, each diagnostic emitted includes text indicating the command-line option that directly controls that diagnostic (if such an option is known to the diagnostic machinery, that is). Specifying the -fno-diagnostics-show-option flag suppresses that behavior. Like, quiet down about which flag did it, I guess 🫶
  • -fno-diagnostics-show-caret — by default, each diagnostic emitted includes the original source line and a caret ^ indicating the column. This option suppresses that info entirely. Note: the source line gets truncated to n characters if the -fmessage-length=n option is given. And when the output is done to the terminal, the width is limited to the width given by the COLUMNS environment variable or, if that's not set, to the terminal width. Respect the layout, periodt.
  • -fno-diagnostics-show-labels — by default, when printing source code (via -fdiagnostics-show-caret), diagnostics can label ranges of source code with pertinent information, such as the types of expressions, and it looks like this:
            printf ("foo %s bar", long_i + long_j);
                         ~^       ~~~~~~~~~~~~~~~
                          |              |
                          char *         long int

This option suppresses the printing of these labels — so in the example above, the vertical bars and the "char *" and "long int" text just dip 🦋

  • -fno-diagnostics-show-cwe — diagnostic messages can optionally have an associated CWE identifier (that's https://cwe.mitre.org/index.html if you wanna go read up, iykyk). GCC itself only provides such metadata for some of the -fanalyzer diagnostics. GCC plugins may also provide diagnostics with such metadata. By default, if this information is present, it will be printed with the diagnostic. This option suppresses the printing of this metadata. Sometimes you just don't need the lore, you know? 💅
  • -fno-diagnostics-show-line-numbers — by default, when printing source code (via -fdiagnostics-show-caret), a left margin is printed showing line numbers. This option suppresses that left margin. Clean, minimal, no gutter 💜
  • -fdiagnostics-minimum-margin-width=width — controls the minimum width of the left margin printed by -fdiagnostics-show-line-numbers. It defaults to 6. Six. That's the number. Iconic.

  • -fdiagnostics-parseable-fixits — okay this one is for the IDE girlies 💖 It emits fix-it hints in a machine-parseable format, suitable for consumption by IDEs. For each fix-it, a line gets printed after the relevant diagnostic, starting with the string "fix-it:". Like so:
        fix-it:"test.c":{45:3-45:21}:"gtk_widget_show_all"

The location is expressed as a half-open range, expressed as a count of bytes, starting at byte 1 for the initial column. In the above example, bytes 3 through 20 of line 45 of "test.c" are to be replaced with the given string:

        00000000011111111112222222222
        12345678901234567890123456789
          gtk_widget_showall (dlg);
          ^^^^^^^^^^^^^^^^^^
          gtk_widget_show_all

The filename and replacement string escape backslash as "\\", tab as "\t", newline as "\n", double quotes as "\"", non-printable characters as octal (e.g. vertical tab as "\013"). Get those escapes right, no cap.

An empty replacement string indicates that the given range is to be removed. An empty range (e.g. "45:3-45:3") indicates that the string is to be inserted at the given position. Insert vs. replace vs. yeet — all covered 🎀

  • -fdiagnostics-generate-patch — prints fix-it hints to stderr in unified diff format, after any diagnostics are printed. Look at her:
        --- test.c
        +++ test.c
        @ -42,5 +42,5 @

         void show_cb(GtkDialog *dlg)
         {
        -  gtk_widget_showall(dlg);
        +  gtk_widget_show_all(dlg);
         }

The diff may or may not be colorized, following the same rules as for diagnostics (see -fdiagnostics-color). Ate, honestly 🍓

  • -fdiagnostics-show-template-tree — in the C++ frontend, when printing diagnostics showing mismatching template types, such as:
          could not convert 'std::map<int, std::vector<double> >()'
            from 'map<[...],vector<double>>' to 'map<[...],vector<float>>

the -fdiagnostics-show-template-tree flag enables printing a tree-like structure showing the common and differing parts of the types, like this:

          map<
            [...],
            vector<
              [double != float]>>

Literally so much more readable, I'm obsessed. Tree structure slay 🌸

The parts that differ are highlighted with color (double and float in this case) — so cute, honestly, the diff basically glows at you ✨

  • -fno-elide-type — okay so bestie, by default when the C++ frontend prints diagnostics showing mismatching template types, the common parts of the types get printed as [...] to simplify the error message. Like, for example:
          could not convert 'std::map<int, std::vector<double> >()'
            from 'map<[...],vector<double>>' to 'map<[...],vector<float>>

Specifying the -fno-elide-type flag suppresses that behavior. No more hiding the boring repeated bits — you get the whole type, periodt. This flag also affects the output of the -fdiagnostics-show-template-tree flag. 🫶

  • -fdiagnostics-path-format=KIND — this one specifies how to print paths of control-flow events for diagnostics that have such a path associated with them. Vibe check on KIND: it's none, separate-events, or inline-events, the default.

none means to not print diagnostic paths at all. Nothing to see here, moving on.

separate-events means to print a separate "note" diagnostic for each event within the diagnostic. For example:

        test.c:29:5: error: passing NULL as argument 1 to 'PyList_Append' which requires a non-NULL parameter
        test.c:25:10: note: (1) when 'PyList_New' fails, returning NULL
        test.c:27:3: note: (2) when 'i < count'
        test.c:29:5: note: (3) when calling 'PyList_Append', passing NULL from (1) as argument 1

inline-events means to print the events "inline" within the source code. This view attempts to consolidate the events into runs of sufficiently-close events, printing them as labelled ranges within the source. It's giving annotated glow-up of your source. 🌸

For example, the same events as above might be printed as:

          'test': events 1-3
            |
            |   25 |   list = PyList_New(0);
            |      |          ^~~~~~~~~~~~~
            |      |          |
            |      |          (1) when 'PyList_New' fails, returning NULL
            |   26 |
            |   27 |   for (i = 0; i < count; i++) {
            |      |   ~~~
            |      |   |
            |      |   (2) when 'i < count'
            |   28 |     item = PyLong_FromLong(random());
            |   29 |     PyList_Append(list, item);
            |      |     ~~~~~~~~~~~~~~~~~~~~~~~~~
            |      |     |
            |      |     (3) when calling 'PyList_Append', passing NULL from (1) as argument 1
            |

Interprocedural control flow is shown by grouping the events by stack frame, and using indentation to show how stack frames are nested, pushed, and popped. Ngl this is art. 🎀

For example:

          'test': events 1-2
            |
            |  133 | {
            |      | ^
            |      | |
            |      | (1) entering 'test'
            |  134 |   boxed_int *obj = make_boxed_int (i);
            |      |                    ~~~~~~~~~~~~~~~~~~
            |      |                    |
            |      |                    (2) calling 'make_boxed_int'
            |
            +--> 'make_boxed_int': events 3-4
                   |
                   |  120 | {
                   |      | ^
                   |      | |
                   |      | (3) entering 'make_boxed_int'
                   |  121 |   boxed_int *result = (boxed_int *)wrapped_malloc (sizeof (boxed_int));
                   |      |                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                   |      |                                    |
                   |      |                                    (4) calling 'wrapped_malloc'
                   |
                   +--> 'wrapped_malloc': events 5-6
                          |
                          |    7 | {
                          |      | ^
                          |      | |
                          |      | (5) entering 'wrapped_malloc'
                          |    8 |   return malloc (size);
                          |      |          ~~~~~~~~~~~~~
                          |      |          |
                          |      |          (6) calling 'malloc'
                          |
            <-------------+
            |
         'test': event 7
            |
            |  138 |   free_boxed_int (obj);
            |      |   ^~~~~~~~~~~~~~~~~~~~
            |      |   |
            |      |   (7) calling 'free_boxed_int'
            |
        (etc)
  • -fdiagnostics-show-path-depths — this option provides additional information when printing control-flow paths associated with a diagnostic. If this is option is provided then the stack depth will be printed for each run of events within -fdiagnostics-path-format=separate-events. Depth reveal, slay.

This is intended for use by GCC developers and plugin developers when debugging diagnostics that report interprocedural control flow. iykyk 💅

  • -fno-show-column — do not print column numbers in diagnostics. This may be necessary if diagnostics are being scanned by a program that does not understand the column numbers, such as dejagnu. Feeding your output to a tool that's a little clueless? This is for you. 🦋
  • -fdiagnostics-column-unit=UNIT — select the units for the column number. This affects traditional diagnostics (in the absence of -fno-show-column), as well as JSON format diagnostics if requested.

The default UNIT, display, considers the number of display columns occupied by each character. This may be larger than the number of bytes required to encode the character, in the case of tab characters, or it may be smaller, in the case of multibyte characters. For example, the character "GREEK SMALL LETTER PI (U+03C0)" occupies one display column, and its UTF-8 encoding requires two bytes; the character "SLIGHTLY SMILING FACE (U+1F642)" occupies two display columns, and its UTF-8 encoding requires four bytes. Bestie the smiley is literally wider than pi, I can't 😭

Setting UNIT to byte changes the column number to the raw byte count in all cases, as was traditionally output by GCC prior to version 11.1.0. Retro byte-count era ✨

  • -fdiagnostics-column-origin=ORIGIN — select the origin for column numbers, i.e. the column number assigned to the first column. The default value of 1 corresponds to traditional GCC behavior and to the GNU style guide. Some utilities may perform better with an origin of 0; any non-negative value may be specified. Zero-indexed girlies, this one's for you 🫶
  • -fdiagnostics-escape-format=FORMAT — when GCC prints pertinent source lines for a diagnostic it normally attempts to print the source bytes directly. However, some diagnostics relate to encoding issues in the source file, such as malformed UTF-8, or issues with Unicode normalization. These diagnostics are flagged so that GCC will escape bytes that are not printable ASCII when printing their pertinent source lines. Encoding drama detected → escape mode engaged. 💅

This option controls how such bytes should be escaped.

The default FORMAT, unicode, displays Unicode characters that are not printable ASCII in the form <U+XXXX>, and bytes that do not correspond to a Unicode character validly-encoded in UTF-8-encoded will be displayed as hexadecimal in the form <XX>. Fancy hex-y hex-y.

For example, a source line containing the string before followed by the Unicode character U+03C0 ("GREEK SMALL LETTER PI", with UTF-8 encoding 0xCF 0x80) followed by the byte 0xBF (a stray UTF-8 trailing byte), followed by the string after will be printed for such a diagnostic as:

          before<U+03C0><BF>after

Setting FORMAT to bytes will display all non-printable-ASCII bytes in the form <XX>, thus showing the underlying encoding of non-ASCII Unicode characters. For the example above, the following will be printed:

          before<CF><80><BF>after
  • -fdiagnostics-format=FORMAT — select a different format for printing diagnostics. FORMAT is text or json. The default is text. JSON besties rise 🧚

The json format consists of a top-level JSON array containing JSON objects representing the diagnostics.

The JSON is emitted as one line, without formatting; the examples below have been formatted for clarity. Not me reformatting it all pretty for you, bestie 😭

Diagnostics can have child diagnostics. For example, this error and note:

        misleading-indentation.c:15:3: warning: this 'if' clause does not
          guard... [-Wmisleading-indentation]
           15 |   if (flag)
              |   ^~
        misleading-indentation.c:17:5: note: ...this statement, but the latter
          is misleadingly indented as if it were guarded by the 'if'
           17 |     y = 2;
              |     ^

might be printed in JSON form (after formatting) like this:

…where the "note" is a child of the "warning" — like the warning is the main character and the note is its ride-or-die little sibling tagging along 🫶

A diagnostic has a "kind". If that's "warning", then there's an "option" key describing the command-line option controlling the warning. slay, self-documenting 💅

A diagnostic can contain zero or more locations. Each location has an optional "label" string and up to three positions within it: a "caret" position and optional "start" and "finish" positions. A position is described by a "file" name, a "line" number, and three numbers indicating a column position:

  • "display-column" — counts display columns, accounting for tabs and multibyte characters ✨
  • "byte-column" — counts raw bytes 🧮
  • "column" — is equal to one of the previous two, as dictated by the -fdiagnostics-column-unit option 👑

All three columns are relative to the origin specified by -fdiagnostics-column-origin, which is typically equal to 1 but may be set, for instance, to 0 for compatibility with other utilities that number columns from 0. The column origin is recorded in the JSON output in the "column-origin" tag. In the remaining examples below, the extra column number outputs have been omitted for brevity. (ngl, thank u for that 🙏)

For example, this error:

bad-binary-ops.c:64:23: error: invalid operands to binary + (have 'S' {aka
   'struct s'} and 'T' {aka 'struct t'})
   64 |   return callee_4a () + callee_4b ();
      |          ~~~~~~~~~~~~ ^ ~~~~~~~~~~~~
      |          |              |
      |          |              T {aka struct t}
      |          S {aka struct s}

has three locations. Its primary location is at the + token at column 23. It has two secondary locations, describing the left and right-hand sides of the expression, which have labels. It might be printed in JSON form as:

{
    "children": [],
    "kind": "error",
    "locations": [
        {
            "caret": {
                "column": 23, "file": "bad-binary-ops.c", "line": 64
            }
        },
        {
            "caret": {
                "column": 10, "file": "bad-binary-ops.c", "line": 64
            },
            "finish": {
                "column": 21, "file": "bad-binary-ops.c", "line": 64
            },
            "label": "S {aka struct s}"
        },
        {
            "caret": {
                "column": 25, "file": "bad-binary-ops.c", "line": 64
            },
            "finish": {
                "column": 36, "file": "bad-binary-ops.c", "line": 64
            },
            "label": "T {aka struct t}"
        }
    ],
    "escape-source": false,
    "message": "invalid operands to binary + ..."
}

If a diagnostic contains fix-it hints, it has a "fixits" array, consisting of half-open intervals, similar to the output of -fdiagnostics-parseable-fixits. For example, this diagnostic with a replacement fix-it hint:

demo.c:8:15: error: 'struct s' has no member named 'colour'; did you
  mean 'color'?
    8 |   return ptr->colour;
      |               ^~~~~~
      |               color

might be printed in JSON form as:

{
    "children": [],
    "fixits": [
        {
            "next": {
                "column": 21,
                "file": "demo.c",
                "line": 8
            },
            "start": {
                "column": 15,
                "file": "demo.c",
                "line": 8
            },
            "string": "color"
        }
    ],
    "kind": "error",
    "locations": [
        {
            "caret": {
                "column": 15,
                "file": "demo.c",
                "line": 8
            },
            "finish": {
                "column": 20,
                "file": "demo.c",
                "line": 8
            }
        }
    ],
    "escape-source": false,
    "message": "\u2018struct s\u2019 has no member named ..."
}

where the fix-it hint suggests replacing the text from "start" up to but not including "next" with "string"'s value. Deletions are expressed via an empty value for "string", insertions by having "start" equal "next". bestie that's the whole trick, so clean 😭

If the diagnostic has a path of control-flow events associated with it, it has a "path" array of objects representing the events. Each event object has a "description" string, a "location" object, along with a "function" string and a "depth" number for representing interprocedural paths. The "function" represents the current function at that event, and the "depth" represents the stack depth relative to some baseline: the higher, the more frames are within the stack. 📚

For example, the intraprocedural example shown for -fdiagnostics-path-format= might have this JSON for its path:

"path": [
    {
        "depth": 0,
        "description": "when 'PyList_New' fails, returning NULL",
        "function": "test",
        "location": {
            "column": 10,
            "file": "test.c",
            "line": 25
        }
    },
    {
        "depth": 0,
        "description": "when 'i < count'",
        "function": "test",
        "location": {
            "column": 3,
            "file": "test.c",
            "line": 27
        }
    },
    {
        "depth": 0,
        "description": "when calling 'PyList_Append', passing NULL from (1) as argument 1",
        "function": "test",
        "location": {
            "column": 5,
            "file": "test.c",
            "line": 29
        }
    }
]

Diagnostics have a boolean attribute "escape-source", hinting whether non-ASCII bytes should be escaped when printing the pertinent lines of source code ("true" for diagnostics involving source encoding issues). 🦋


✨ Options to Request or Suppress Warnings ✨

Warnings are diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error. no cap, they're the "hey bestie… u sure?" of the compiler 💅

The following language-independent options do not enable specific warnings but control the kinds of diagnostics produced by GCC:

  • -fsyntax-only — Check the code for syntax errors, but don't do anything beyond that. Just the vibe check, nothing more 🎀
  • -fmax-errors=_n_ — Limits the maximum number of error messages to n, at which point GCC bails out rather than attempting to continue processing the source code. If n is 0 (the default), there is **no limit on the number of error messages produced. If -Wfatal-errors is also specified, then -Wfatal-errors takes precedence over this option. 😤
  • -w — Inhibit all warning messages. like… all of them. silence, iconic, maybe concerning 😶
  • -Werror — Make all warnings into errors. glow-up of the century, everything is fatal now 🔥
bestie pls be careful with -Werror on a big project, it does exactly what it says and it does not care about your feelings 💀
  • -Werror= — this is the glow-up machine: it takes whatever warning you name and makes it a full-on error. You append the specifier, so like -Werror=switch turns the warnings controlled by -Wswitch into errors. It's got a negative form too, and that one's for un-erroring specific warnings without touching the rest — -Wno-error=switch makes -Wswitch warnings stop being errors, even when -Werror is out here being extra in the background. 💅

Bestie, every controllable warning prints the option that controls it right in the message. So you can just steal that option name and feed it to -Werror= or -Wno-error= like the original text said. (Wanna hide that option from the message? -fno-diagnostics-show-option does the trick. 🎀)

Heads up: -Werror=foo automatically implies -Wfoo, no cap. But -Wno-error=foo? That one implies nothing. Zero. Zilch. 🙈
  • -Wfatal-errors — the "I've seen enough" button. The compiler aborts compilation on the very first error instead of trying to keep going and printing further error messages. Like, it stops doom-scrolling the source file at the first red flag. 💀

So, requesting warnings: you can ask for a whole bunch of specific warnings with options that start with -W, for example -Wimplicit to request warnings on implicit declarations. And every one of these specific warning options also has a negative form beginning -Wno-, which turns the warnings off — -Wno-implicit, for example. This manual only lists one of the two forms, whichever one isn't the default. For more language-specific options you also wanna check C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. And you can get even more warnings by enabling the static analyzer. ✨

Now here's the lore on priority, because it's giving ✨layers✨: some options, like -Wall and -Wextra, turn on other options, like -Wunused, which may turn on further options, like -Wunused-value. The combined effect of positive and negative forms is that more specific options have priority over less specific ones — and that's true independently of their position in the command line. For options of the same specificity, the last one takes effect. And options enabled or disabled via pragmas take effect as if they appeared at the end of the command-line. Periodt. 👑

When an unrecognized warning option is requested (e.g. -Wunknown-warning), GCC emits a diagnostic stating that the option is not recognized. But the -Wno- form is lowkey built different: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are being produced. That's on purpose — it lets you use new -Wno- options with old compilers. But if something goes wrong, the compiler warns that an unrecognized option is present. 🫶

And ngl, the effectiveness of some warnings depends on optimizations also being enabled. For example -Wsuggest-final-types is more effective with link-time optimization, and some instances of other warnings may not be issued at all unless optimization is enabled. While optimization in general improves the efficacy of control and data flow sensitive warnings, in some cases it may also cause false positives. It's giving "he's a little confused but he's got the spirit." 😭

  • -Wpedantic, -pedantic — the strict ISO C and ISO C++ enforcer 🧚. It issues all the warnings demanded by strict ISO C and ISO C++; it rejects all programs that use forbidden extensions, and some other programs that do not follow ISO C and ISO C++. For ISO C, it follows the version of the ISO C standard specified by any -std option used.

Valid ISO C and ISO C++ programs should compile properly with or without this option (though a rare few require -ansi or a -std option specifying the required version of ISO C). However, without this option, certain GNU extensions and traditional C and C++ features are supported as well. With this option, they are rejected. Like, they're not invited to the party anymore. 🚫

Okay, loopholes. -Wpedantic does not cause warning messages for use of the alternate keywords whose names begin and end with __. This alternate format can also be used to disable warnings for non-ISO __intN types, i.e. __intN__. Pedantic warnings are also disabled in the expression that follows "__extension__". BUT — and this is the important part — only system header files should use these escape routes; application programs should avoid them. 🫣

Some users try to use -Wpedantic to check programs for strict ISO C conformance. They soon find that it does not do quite what they want: it finds some non-ISO practices, but not all — only those for which ISO C requires a diagnostic, and some others for which diagnostics have been added. It's giving "expected a full audit, got a vibe check." 🙈

A feature to report any failure to conform to ISO C might be useful in some instances, but would require considerable additional work and would be quite different from -Wpedantic. We don't have plans to support such a feature in the near future. (Don't hold your breath bestie.) 😌

And where the standard specified with -std represents a GNU extended dialect of C, such as gnu90 or gnu99, there's a corresponding base standard — the version of ISO C on which the GNU extended dialect is based. Warnings from -Wpedantic are given where they are required by the base standard. (It does not make sense for such warnings to be given only for features not in the specified GNU C dialect, since by definition the GNU dialects of C include all features the compiler supports with the given option, and there would be nothing to warn about.) 💖

  • -pedantic-errors — same energy but turned all the way up 🔥: it gives an error whenever the base standard (see -Wpedantic) requires a diagnostic, in some cases where there is undefined behavior at compile-time and in some other cases that do not prevent compilation of programs that are valid according to the standard. And no, this is not equivalent to -Werror=pedantic, since there are errors enabled by this option and not enabled by the latter and vice versa. They're siblings, not twins. 💅
  • -Wall — the iconic one, the main character 🌈. This enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros. This also enables some language-specific warnings described in C++ Dialect Options and Objective-C and Objective-C++ Dialect Options.

-Wall turns on the following warning flags — and yes, I'm listing every single one, because we don't do skipping here bestie:

-Waddress -Warray-bounds=1 (only with -O2) -Warray-compare
-Warray-parameter=2 (C and Objective-C only) -Wbool-compare
-Wbool-operation -Wc++11-compat  -Wc++14-compat -Wcatch-value (C++
and Objective-C++ only) -Wchar-subscripts -Wcomment
-Wdangling-pointer=2 -Wduplicate-decl-specifier (C and Objective-C
only) -Wenum-compare (in C/ObjC; this is on by default in C++)
-Wformat -Wformat-overflow -Wformat-truncation -Wint-in-bool-context
-Wimplicit (C and Objective-C only) -Wimplicit-int (C and
Objective-C only) -Wimplicit-function-declaration (C and Objective-C
only) -Winit-self (only for C++) -Wlogical-not-parentheses -Wmain
(only for C/ObjC and unless -ffreestanding) -Wmaybe-uninitialized
-Wmemset-elt-size -Wmemset-transposed-args -Wmisleading-indentation
(only for C/C++) -Wmismatched-dealloc -Wmismatched-new-delete (only
for C/C++) -Wmissing-attributes -Wmissing-braces (only for C/ObjC)
-Wmultistatement-macros -Wnarrowing (only for C++) -Wnonnull
-Wnonnull-compare -Wopenmp-simd -Wparentheses -Wpessimizing-move
(only for C++) -Wpointer-sign -Wrange-loop-construct (only for C++)
-Wreorder -Wrestrict -Wreturn-type -Wsequence-point -Wsign-compare
(only in C++) -Wsizeof-array-div -Wsizeof-pointer-div
-Wsizeof-pointer-memaccess -Wstrict-aliasing -Wstrict-overflow=1
-Wswitch -Wtautological-compare -Wtrigraphs -Wuninitialized
-Wunknown-pragmas -Wunused-function -Wunused-label -Wunused-value
-Wunused-variable -Wuse-after-free=3 -Wvla-parameter (C and
Objective-C only) -Wvolatile-register-var -Wzero-length-bounds

Note that some warning flags are not implied by -Wall. Some of them warn about constructions that users generally do not consider questionable, but which occasionally you might wish to check for; others warn about constructions that are necessary or hard to avoid in some cases, and there's no simple way to modify the code to suppress the warning. Some of them are enabled by -Wextra but many of them must be enabled individually. FOMO warning: -Wall is not "all", it's "all the reasonable ones." 🫠

  • -Wextra — the plus-one, the bonus round ⭐. This enables some extra warning flags that are not enabled by -Wall. (This option used to be called -W. The older name is still supported, but the newer name is more descriptive. Glow-up complete. 💅)
-Wclobbered -Wcast-function-type -Wdeprecated-copy (C++ only)
-Wempty-body -Wenum-conversion (C only) -Wignored-qualifiers
-Wimplicit-fallthrough=3 -Wmissing-field-initializers
-Wmissing-parameter-type (C only) -Wold-style-declaration (C only)
-Woverride-init -Wsign-compare (C only) -Wstring-compare
-Wredundant-move (only for C++) -Wtype-limits -Wuninitialized
-Wshift-negative-value (in C++11 to C++17 and in C99 and newer)
-Wunused-parameter (only with -Wunused or -Wall)
-Wunused-but-set-parameter (only with -Wunused or -Wall)

The option -Wextra also prints warning messages for the following cases:

  • A pointer is compared against integer zero with "<", "<=", ">", or ">=".
  • (C++ only) An enumerator and a non-enumerator both appear in a conditional expression.
  • (C++ only) Ambiguous virtual bases.
  • (C++ only) Subscripting an array that has been declared "register".
  • (C++ only) Taking the address of a variable that has been declared "register".
  • (C++ only) A base class is not initialized in the copy constructor of a derived class.
  • -Wabi (C, Objective-C, C++ and Objective-C++ only) — warns about code affected by ABI changes 🦋. This includes code that may not be compatible with the vendor-neutral C++ ABI as well as the psABI for the particular target.

Since G++ now defaults to updating the ABI with each major release, normally -Wabi warns only about C++ ABI compatibility problems if there's a check added later in a release series for an ABI issue discovered since the initial release. -Wabi warns about more things if an older ABI version is selected (with -fabi-version=n).

-Wabi can also be used with an explicit version number to warn about C++ ABI compatibility with a particular -fabi-version level, e.g. -Wabi=2 to warn about changes relative to -fabi-version=2.

If an explicit version number is provided and -fabi-compat-version is not specified, the version number from this option is used for compatibility aliases. If no explicit version number is provided with this option, but -fabi-compat-version is specified, that version number is used for C++ ABI warnings. iykyk 🧚

okay so real talk, bestie: GCC tries to put you on notice for all of these cases, but like… it’s not psychic 💀 There are probably some cases that don’t get warned about, even though G++ is out here generating incompatible code. And yeah, there may also be cases where warnings pop off even though the code that gets generated is compatible.

You should rewrite your code to avoid these warnings if you’re concerned about the fact that code generated by G++ may not be binary compatible with code generated by other compilers. no cap.

Known incompatibilities in -fabi-version=2 (which was the default from GCC 3.4 to 4.9) include:

  • A template with a non-type template parameter of reference type was mangled incorrectly:
extern int N;
template <int &> struct S {};
void n (S<N>) {2}

This was fixed in -fabi-version=3.

  • SIMD vector types declared using "__attribute ((vector_size))" were mangled in a non-standard way that does not allow for overloading of functions taking vectors of different sizes.

The mangling was changed in -fabi-version=4.

  • "__attribute ((const))" and "noreturn" were mangled as type qualifiers, and "decltype" of a plain declaration was folded away.

These mangling issues were fixed in -fabi-version=5.

  • Scoped enumerators passed as arguments to a variadic function are promoted like unscoped enumerators, causing "va_arg" to complain. On most targets this does not actually affect the parameter passing ABI, as there is no way to pass an argument smaller than "int".

Also, the ABI changed the mangling of template argument packs, "const_cast", "static_cast", prefix increment/decrement, and a class scope function used as a template argument.

These issues were corrected in -fabi-version=6.

  • Lambdas in default argument scope were mangled incorrectly, and the ABI changed the mangling of "nullptr_t".

These issues were corrected in -fabi-version=7.

  • When mangling a function type with function-cv-qualifiers, the un-qualified function type was incorrectly treated as a substitution candidate.

This was fixed in -fabi-version=8, the default for GCC 5.1.

  • decltype(nullptr) incorrectly had an alignment of 1, leading to unaligned accesses. Note that this did not affect the ABI of a function with a "nullptr_t" parameter, as parameters have a minimum alignment.

This was fixed in -fabi-version=9, the default for GCC 5.2.

  • Target-specific attributes that affect the identity of a type, such as ia32 calling conventions on a function type (stdcall, regparm, etc.), did not affect the mangled name, leading to name collisions when function pointers were used as template arguments.

This was fixed in -fabi-version=10, the default for GCC 6.1.

This option also enables warnings about psABI-related changes. The known psABI changes at this point include:

  • For SysV/x86-64, unions with "long double" members are passed in memory as specified in psABI. Prior to GCC 4.4, this was not the case. For example:
union U {
  long double ld;
  int i;
};

"union U" is now always passed in memory.


  • -Wchar-subscripts — Warn if an array subscript has type "char". This is a common cause of error, as programmers often forget that this type is signed on some machines. This warning is enabled by -Wall. 💅
  • -Wno-coverage-mismatch — Warn if feedback profiles do not match when using the -fprofile-use option. If a source file is changed between compiling with -fprofile-generate and with -fprofile-use, the files with the profile feedback can fail to match the source file and GCC cannot use the profile feedback information. By default, this warning is enabled and is treated as an error. -Wno-coverage-mismatch can be used to disable the warning or -Wno-error=coverage-mismatch can be used to disable the error. Disabling the error for this warning can result in poorly optimized code and is useful only in the case of very minor changes such as bug fixes to an existing code-base. Completely disabling the warning is not recommended. 🫶
  • -Wno-coverage-invalid-line-number — Warn in case a function ends earlier than it begins due to an invalid linenum macros. The warning is emitted only with --coverage enabled.

By default, this warning is enabled and is treated as an error. -Wno-coverage-invalid-line-number can be used to disable the warning or -Wno-error=coverage-invalid-line-number can be used to disable the error. 😭

  • -Wno-cpp (C, Objective-C, C++, Objective-C++ and Fortran only) — Suppress warning messages emitted by "#warning" directives. 🤫
  • -Wdouble-promotion (C, C++, Objective-C and Objective-C++ only) — Give a warning when a value of type "float" is implicitly promoted to "double". CPUs with a 32-bit "single-precision" floating-point unit implement "float" in hardware, but emulate "double" in software. On such a machine, doing computations using "double" values is much more expensive because of the overhead required for software emulation. 💸

It is easy to accidentally do computations with "double" because floating-point literals are implicitly of type "double". For example, in:

float area(float radius)
{
   return 3.14159 * radius * radius;
}

the compiler performs the entire computation with "double" because the floating-point literal is a "double". caught in 4k 🔍

  • -Wduplicate-decl-specifier (C and Objective-C only) — Warn if a declaration has duplicate "const", "volatile", "restrict" or "_Atomic" specifier. This warning is enabled by -Wall. 🎀
  • -Wformat
  • -Wformat=n — Check calls to "printf" and "scanf", etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense. This includes standard functions, and others specified by format attributes, in the "printf", "scanf", "strftime" and "strfmon" (an X/Open extension, not in the C standard) families (or other target-specific families). Which functions are checked without format attributes having been specified depends on the standard version selected, and such checks of functions without the attribute specified are disabled by -ffreestanding or -fno-builtin. 👑

The formats are checked against the format features supported by GNU libc version 2.2. These include all ISO C90 and C99 features, as well as features from the Single Unix Specification and some BSD and GNU extensions. Other library implementations may not support all these features; GCC does not support warning about features that go beyond a particular library’s limitations. However, if -Wpedantic is used with -Wformat, warnings are given about format features not in the selected standard version (but not for "strfmon" formats, since those are not in any version of the C standard). 🌈

  • -Wformat=1, -Wformat — Option -Wformat is equivalent to -Wformat=1, and -Wno-format is equivalent to -Wformat=0. Since -Wformat also checks for null format arguments for several functions, -Wformat also implies -Wnonnull. Some aspects of this level of format checking can be disabled by the options: -Wno-format-contains-nul, -Wno-format-extra-args, and -Wno-format-zero-length. -Wformat is enabled by -Wall. ✨
  • -Wformat=2 — Enable -Wformat plus additional format checks. Currently equivalent to -Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k. 🔥
  • -Wno-format-contains-nul — If -Wformat is specified, do not warn about format strings that contain NUL bytes. 🫧
  • -Wno-format-extra-args — If -Wformat is specified, do not warn about excess arguments to a "printf" or "scanf" format function. The C standard specifies that such arguments are ignored.

Where the unused arguments lie between used arguments that are specified with $ operand number specifications, normally warnings are still given, since the implementation could not know what type to pass to "va_arg" to skip the unused arguments. However, in the case of "scanf" formats, this option suppresses the warning if the unused arguments are all pointers, since the Single Unix Specification says that such unused arguments are allowed. iykyk 🧚

  • -Wformat-overflow
  • -Wformat-overflow=level — Warn about calls to formatted input/output functions such as "sprintf" and "vsprintf" that might overflow the destination buffer. When the exact number of bytes written by a format directive cannot be determined at compile-time it is estimated based on heuristics that depend on the level argument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives. 💀
    • -Wformat-overflow, -Wformat-overflow=1 — Level 1 of -Wformat-overflow enabled by -Wformat employs a conservative approach that warns only about calls that most likely overflow the buffer. At this level, numeric arguments to format directives with unknown values are assumed to have the value of one, and strings of unknown length to be empty. Numeric arguments that are known to be bounded to a subrange of their type, or string arguments whose output is bounded either by their directive’s precision or by a finite set of string literals, are assumed to take on the value within the range that results in the most bytes on output. For example, the call to "sprintf" below is diagnosed because even with both a and b equal to zero, the terminating NUL character ('\0') appended by the function to the destination buffer will be written past its end. Increasing the size of the buffer by a single byte is sufficient to avoid the warning, though it may not be sufficient to avoid the overflow. 🚨
void f (int a, int b)
{
  char buf [13];
  sprintf (buf, "a = %i, b = %i\n", a, b);
}

and yes bestie, there’s literally more right behind this — this was just the format-checking corner of the group chat 💬💖

  • -Wformat-overflow=2 — level 2 is the extra level, bestie 💅 it also drags calls that might overflow the destination buffer given an argument of sufficient length or magnitude. At level 2, unknown numeric arguments are assumed to have the minimum representable value for signed types with a precision greater than 1, and the maximum representable value otherwise. And unknown string arguments whose length cannot be assumed to be bounded — either by the directive's precision, or by a finite set of string literals they may evaluate to, or the character array they may point to — are assumed to be 1 character long. no cap.

At level 2, the call in the example above is again diagnosed, but this time because with a equal to a 32-bit INT_MIN the first %i directive will write some of its digits beyond the end of the destination buffer. so 😭 the drama. To make the call safe regardless of the values of the two variables, the size of the destination buffer must be increased to at least 34 bytes. GCC includes the minimum size of the buffer in an informational note following the warning — it's literally being helpful.

An alternative to increasing the size of the destination buffer is to constrain the range of formatted values. The maximum length of string arguments can be bounded by specifying the precision in the format directive. When numeric arguments of format directives can be assumed to be bounded by less than the precision of their type, choosing an appropriate length modifier to the format specifier will reduce the required buffer size. For example, if a and b in the example above can be assumed to be within the precision of the short int type then using either the %hi format directive or casting the argument to short reduces the maximum required size of the buffer to 24 bytes.

void f (int a, int b)
{
  char buf [23];
  sprintf (buf, "a = %hi, b = %i\n", a, (short)b);
}
  • -Wno-format-zero-length — if -Wformat is specified, do not warn about zero-length formats. The C standard specifies that zero-length formats are allowed. so like... it's legal, bestie, chill 🫶
  • -Wformat-nonliteral — if -Wformat is specified, also warn if the format string is not a string literal and so cannot be checked, unless the format function takes its format arguments as a va_list. 🧚
  • -Wformat-security — if -Wformat is specified, also warn about uses of format functions that represent possible security problems. At present, this warns about calls to printf and scanf functions where the format string is not a string literal and there are no format arguments, as in printf (foo);. This may be a security hole if the format string came from untrusted input and contains %n. 🚨 (This is currently a subset of what -Wformat-nonliteral warns about, but in future warnings may be added to -Wformat-security that are not included in -Wformat-nonliteral.) iykyk, the overlap is real but don't count on it forever.
  • -Wformat-signedness — if -Wformat is specified, also warn if the format string requires an unsigned argument and the argument is signed and vice versa. mismatched vibes, caught 💀
  • -Wformat-truncation, *-Wformat-truncation=level* — warn about calls to formatted input/output functions such as snprintf and vsnprintf that might result in output truncation. When the exact number of bytes written by a format directive cannot be determined at compile-time it is estimated based on heuristics that depend on the level argument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives. 😭 Except as noted otherwise, the option uses the same logic -Wformat-overflow.
    • -Wformat-truncation, -Wformat-truncation=1 — level 1 of -Wformat-truncation enabled by -Wformat employs a conservative approach that warns only about calls to bounded functions whose return value is unused and that will most likely result in output truncation. playing it safe, honestly iconic.
    • -Wformat-truncation=2 — level 2 warns also about calls to bounded functions whose return value is used and that might result in truncation given an argument of sufficient length or magnitude. level 2 said "and what if" 💅
  • -Wformat-y2k — if -Wformat is specified, also warn about strftime formats that may yield only a two-digit year. the millennium bug said hi 🎀
  • -Wnonnull — warn about passing a null pointer for arguments marked as requiring a non-null value by the nonnull function attribute.

-Wnonnull is included in -Wall and -Wformat. It can be disabled with the -Wno-nonnull option.

  • -Wnonnull-compare — warn when comparing an argument marked with the nonnull function attribute against null inside the function. like bestie, you already said it's not null, why are we checking 😭

-Wnonnull-compare is included in -Wall. It can be disabled with the -Wno-nonnull-compare option.

  • -Wnull-dereference — warn if the compiler detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer. 💀 This option is only active when -fdelete-null-pointer-checks is active, which is enabled by optimizations in most targets. The precision of the warnings depends on the optimization options used. so like, it's giving "results may vary".
  • -Winfinite-recursion — warn about infinitely recursive calls. 🔁 The warning is effective at all optimization levels but requires optimization in order to detect infinite recursion in calls between two or more functions. -Winfinite-recursion is included in -Wall. not me going in circles fr fr.
  • -Winit-self (C, C++, Objective-C and Objective-C++ only) — warn about uninitialized variables that are initialized with themselves. Note this option can only be used with the -Wuninitialized option. the girl is her own origin story 🙈

For example, GCC warns about i being uninitialized in the following snippet only when -Winit-self has been specified:

int f()
{
  int i = i;
  return i;
}

This warning is enabled by -Wall in C++.

  • -Wno-implicit-int (C and Objective-C only) — this option controls warnings when a declaration does not specify a type. This warning is enabled by default in C99 and later dialects of C, and also by -Wall.
  • -Wno-implicit-function-declaration (C and Objective-C only) — this option controls warnings when a function is used before being declared. This warning is enabled by default in C99 and later dialects of C, and also by -Wall. The warning is made into an error by -pedantic-errors. 😳 it gets promoted.
  • -Wimplicit (C and Objective-C only) — same as -Wimplicit-int and -Wimplicit-function-declaration. This warning is enabled by -Wall. the two-for-one combo meal 🍓
  • -Wimplicit-fallthrough — -Wimplicit-fallthrough is the same as -Wimplicit-fallthrough=3 and -Wno-implicit-fallthrough is the same as -Wimplicit-fallthrough=0.
  • *-Wimplicit-fallthrough=n* — warn when a switch case falls through. like:
switch (cond)
  {
  case 1:
    a = 1;
    break;
  case 2:
    a = 2;
  case 3:
    a = 3;
    break;
  }

This warning does not warn when the last statement of a case cannot fall through, e.g. when there is a return statement or a call to function declared with the noreturn attribute. -Wimplicit-fallthrough= also takes into account control flow statements, such as ifs, and only warns when appropriate. E.g.

switch (cond)
  {
  case 1:
    if (i > 3) {
      bar (5);
      break;
    } else if (i < 1) {
      bar (0);
    } else
      return;
  default:
    ...
  }

Since there are occasions where a switch case fall through is desirable, GCC provides an attribute, __attribute__ ((fallthrough)), that is to be used along with a null statement to suppress this warning that would normally occur:

switch (cond)
  {
  case 1:
    bar (0);
    __attribute__ ((fallthrough));
  default:
    ...
  }

C++17 provides a standard way to suppress the -Wimplicit-fallthrough warning using [[fallthrough]]; instead of the GNU attribute. In C++11 or C++14 users can use [[gnu::fallthrough]];, which is a GNU extension. Instead of these attributes, it is also possible to add a fallthrough comment to silence the warning. The whole body of the C or C++ style comment should match the given regular expressions listed below. The option argument n specifies what kind of comments are accepted:

  • -Wimplicit-fallthrough=0 disables the warning altogether. 🙅
  • -Wimplicit-fallthrough=1 matches .* regular expression, any comment is used as fallthrough comment.
  • -Wimplicit-fallthrough=2 case insensitively matches .*falls?[ \t-]*thr(ough|u).* regular expression.
  • -Wimplicit-fallthrough=3 case sensitively matches one of the following regular expressions:
    • "-fallthrough"
    • "@fallthrough@"
    • "lint -fallthrough[ \t]*"
    • "[ \t.!]*(ELSE,? |INTENTIONAL(LY)? )?FALL(S | |-)?THR(OUGH|U)[ \t.!]*(-[^\n\r]*)?"
    • "[ \t.!]*(Else,? |Intentional(ly)? )?Fall((s | |-)[Tt]|t)hr(ough|u)[ \t.!]*(-[^\n\r]*)?"
    • "[ \t.!]*([Ee]lse,? |[Ii]ntentional(ly)? )?fall(s | |-)?thr(ough|u)[ \t.!]*(-[^\n\r]*)?"
  • -Wimplicit-fallthrough=4 case sensitively matches one of the following regular expressions:
    • "-fallthrough"
    • "@fallthrough@"
    • "lint -fallthrough[ \t]*"
    • "[ \t]*FALLTHR(OUGH|U)[ \t]*"
  • -Wimplicit-fallthrough=5 doesn't recognize any comments as fallthrough comments, only attributes disable the warning.

The comment needs to be followed after optional whitespace and other comments by case or default keywords or by a user label that precedes some case or default label.

switch (cond)
  {
  case 1:
    bar (0);
    /* FALLTHRU */
  default:
    ...
  }

Also lowkey: the -Wimplicit-fallthrough=3 warning is enabled by -Wextra. ✨

  • -Wno-if-not-aligned (C, C++, Objective-C and Objective-C++ only) — controls whether warnings triggered by the warn_if_not_aligned attribute get issued. These warnings are enabled by default. 🎀
  • -Wignored-qualifiers (C and C++ only) — warns if the return type of a function has a type qualifier such as const. For ISO C, that kind of type qualifier has no effect, because the value returned by a function is not an lvalue. For C++, the warning is only emitted for scalar types or void. ISO C prohibits qualified void return types on function definitions, so those return types always get a warning even without this option. This warning is also enabled by -Wextra. 💅
  • -Wno-ignored-attributes (C and C++ only) — this one controls warnings when an attribute is ignored. It’s different from -Wattributes because it warns whenever the compiler decides to drop an attribute, not because the attribute is unknown or used in the wrong place, etc. This warning is enabled by default. 🦋
  • -Wmain — warns if the type of main is suspicious. main should be a function with external linkage, returning int, taking either zero arguments, two, or three arguments of appropriate types. This warning is enabled by default in C++ and is enabled by either -Wall or -Wpedantic. 👑
  • -Wmisleading-indentation (C and C++ only) — warns when the indentation of the code does not reflect the block structure. Specifically, a warning is issued for if, else, while, and for clauses with a guarded statement that does not use braces, followed by an unguarded statement with the same indentation.

In the following example, the call to bar is misleadingly indented as if it were guarded by the if conditional. 😭

if (some_condition ())
  foo ();
  bar ();  /* Gotcha: this is not guarded by the "if".  */

In the case of mixed tabs and spaces, the warning uses the -ftabstop= option to determine if the statements line up (defaulting to 8). The warning is not issued for code involving multiline preprocessor logic such as the following example.

if (flagA)
  foo (0);
#if SOME_CONDITION_THAT_DOES_NOT_HOLD
  if (flagB)
#endif
  foo (1);

The warning is not issued after a #line directive, since this typically indicates autogenerated code, and no assumptions can be made about the layout of the file that the directive references. This warning is enabled by -Wall in C and C++. 🌸

  • -Wmissing-attributes — warns when a declaration of a function is missing one or more attributes that a related function is declared with and whose absence may adversely affect the correctness or efficiency of generated code. For example, the warning is issued for declarations of aliases that use attributes to specify less restrictive requirements than those of their targets. This typically represents a potential optimization opportunity. By contrast, the -Wattribute-alias=2 option controls warnings issued when the alias is more restrictive than the target, which could lead to incorrect code generation. Attributes considered include alloc_align, alloc_size, cold, const, hot, leaf, malloc, nonnull, noreturn, nothrow, pure, returns_nonnull, and returns_twice.

In C++, the warning is issued when an explicit specialization of a primary template declared with attribute alloc_align, alloc_size, assume_aligned, format, format_arg, malloc, or nonnull is declared without it. Attributes deprecated, error, and warning suppress the warning.

You can use the copy attribute to apply the same set of attributes to a declaration as that on another declaration without explicitly enumerating the attributes. This attribute can be applied to declarations of functions, variables, or types. -Wmissing-attributes is enabled by -Wall.

For example, since the declaration of the primary function template below makes use of both attribute malloc and alloc_size, the declaration of the explicit specialization of the template is diagnosed because it is missing one of the attributes. 🔥

template <class T>
T* __attribute__ ((malloc, alloc_size (1)))
allocate (size_t);

template <>
void* __attribute__ ((malloc))   // missing alloc_size
allocate<void> (size_t);
  • -Wmissing-braces — warns if an aggregate or union initializer is not fully bracketed. In the following example, the initializer for a is not fully bracketed, but the one for b is fully bracketed. 🎀
int a[2][2] = { 0, 1, 2, 3 };
int b[2][2] = { { 0, 1 }, { 2, 3 } };

This warning is enabled by -Wall.

  • -Wmissing-include-dirs (C, C++, Objective-C, Objective-C++ and Fortran only) — warns if a user-supplied include directory does not exist. This opions is disabled by default for C, C++, Objective-C and Objective-C++. For Fortran, it is partially enabled by default by warning for -I and -J, only. 🫶
  • -Wno-missing-profile — this option controls warnings if feedback profiles are missing when using the -fprofile-use option. It diagnoses those cases where a new function or a new file is added between compiling with -fprofile-generate and with -fprofile-use, without regenerating the profiles. In these cases, the profile feedback data files do not contain any profile feedback information for the newly added function or file respectively. Also, in the case when profile count data (.gcda) files are removed, GCC cannot use any profile feedback information. In all these cases, warnings are issued to inform you that a profile generation step is due. Ignoring the warning can result in poorly optimized code. -Wno-missing-profile can be used to disable the warning, but this is not recommended and should be done only when non-existent profile data is justified. 💀
  • -Wmismatched-dealloc — warns for calls to deallocation functions with pointer arguments returned from allocation functions for which the former isn’t a suitable deallocator. A pair of functions can be associated as matching allocators and deallocators by use of attribute malloc. Unless disabled by the -fno-builtin option, the standard functions calloc, malloc, realloc, and free, as well as the corresponding forms of C++ operator new and operator delete, are implicitly associated as matching allocators and deallocators. In the following example, mydealloc is the deallocator for pointers returned from myalloc.
void mydealloc (void*);

__attribute__ ((malloc (mydealloc, 1))) void*
myalloc (size_t);

void f (void)
{
  void *p = myalloc (32);
  // ...use p...
  free (p);   // warning: not a matching deallocator for myalloc
  mydealloc (p);   // ok
}

In C++, the related option -Wmismatched-new-delete diagnoses mismatches involving either operator new or operator delete. Option -Wmismatched-dealloc is included in -Wall. 🌈

  • -Wmultistatement-macros — warns about unsafe multiple statement macros that appear to be guarded by a clause such as if, else, for, switch, or while, in which only the first statement is actually guarded after the macro is expanded. For example:
#define DOIT x++; y++
if (c)
  DOIT;

will increment y unconditionally, not just when c holds. This can usually be fixed by wrapping the macro in a do-while loop:

#define DOIT do { x++; y++; } while (0)
if (c)
  DOIT;

This warning is enabled by -Wall in C and C++. ⭐

  • -Wparentheses — warns if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about. Also warns if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1 : 0) <= z, which is a different interpretation from that of ordinary mathematical notation. Also warns for dangerous uses of the GNU extension to ?: with omitted middle operand. When the condition in the ?: operator is a boolean expression, the omitted value is always 1. Often programmers expect it to be a value computed inside the conditional expression instead.

For C++, this also warns for some cases of unnecessary parentheses in declarations, which can indicate an attempt at a function call instead of a declaration:

{
  // Declares a local variable called mymutex.
  std::unique_lock<std::mutex> (mymutex);
  // User meant std::unique_lock<std::mutex> lock (mymutex);
}

This warning is enabled by -Wall. 💖

  • -Wsequence-point — warns about code that may have undefined semantics because of violations of sequence point rules in the C and C++ standards.

The C and C++ standards define the order in which expressions in a C/C++ program are evaluated in terms of sequence points, which represent a partial ordering between the execution of parts of the program: those executed before the sequence point, and those executed after it. These occur after the evaluation of a full expression (one which is not part of a larger expression), after the evaluation of the first operand of a &&, ||, ? : or , (comma) operator, before a function is called (but after the evaluation of its arguments and the expression denoting the called function), and in certain other places. Other than as expressed by the sequence point rules, the order of evaluation of subexpressions of an expression is not specified. All these rules describe only a partial order rather than a total order, since, for example, if two functions are called within one expression with no sequence point between them, the order in which the functions are called is not specified. However, the standards committee have ruled that function calls do not overlap. 🧚

It's literally not specified when between sequence points the modifications to object values actually take effect, bestie 😭. Programs that depend on that have undefined behavior — the C and C++ standards are like, "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored." If a program breaks those rules, the results on any particular implementation are entirely unpredictable. Zero cap. 💀

Examples of code with undefined behavior are a = a++;, a[n] = b[n++] and a[i++] = i;. Some more complicated cases are not diagnosed by this option, and it may give an occasional false positive result, but in general it has been found fairly effective at detecting this sort of problem in programs. Slay, honestly. ✨

The C++17 standard will define the order of evaluation of operands in more cases: in particular it requires that the right-hand side of an assignment be evaluated before the left-hand side, so the above examples are no longer undefined. But this option will still warn about them, to help people avoid writing code that is undefined in C and earlier revisions of C++. It's giving protective bestie energy 🫶.

The standard is worded confusingly, therefore there is some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem, including proposed formal definitions, may be found on the GCC readings page, at <https://gcc.gnu.org/readings.html>.

This warning is enabled by -Wall for C and C++.

  • -Wno-return-local-addr — do not warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns. Like, 🚩🚩🚩 bestie that's a dangling pointer but ok, your call.
  • -Wreturn-type — warn whenever a function is defined with a return type that defaults to int. Also warn about any return statement with no return value in a function whose return type is not void (falling off the end of the function body is considered returning without a value).

For C only, warn about a return statement with an expression in a function whose return type is void, unless the expression type is also void. As a GNU extension, the latter case is accepted without a warning unless -Wpedantic is used. Attempting to use the return value of a non-void function other than main that flows off the end by reaching the closing curly brace that terminates the function is undefined.

Unlike in C, in C++, flowing off the end of a non-void function other than main results in undefined behavior even when the value of the function is not used. 🫠

This warning is enabled by default in C++ and by -Wall otherwise.

  • -Wno-shift-count-negative — controls warnings if a shift count is negative. This warning is enabled by default.
  • -Wno-shift-count-overflow — controls warnings if a shift count is greater than or equal to the bit width of the type. This warning is enabled by default.
  • -Wshift-negative-value — warn if left shifting a negative value. This warning is enabled by -Wextra in C99 (and newer) and C++11 to C++17 modes.
  • -Wno-shift-overflow, -Wshift-overflow=n — these options control warnings about left shift overflows. 👀
    • -Wshift-overflow=1 — this is the warning level of -Wshift-overflow and is enabled by default in C99 and C++11 modes (and newer). This warning level does not warn about left-shifting 1 into the sign bit. (However, in C, such an overflow is still rejected in contexts where an integer constant expression is required.) No warning is emitted in C++20 mode (and newer), as signed left shifts always wrap. It's giving "wrap it up" 💅
    • -Wshift-overflow=2 — this warning level also warns about left-shifting 1 into the sign bit, unless C++14 mode (or newer) is active.
  • -Wswitch — warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. (The presence of a default label prevents this warning.) case labels outside the enumeration range also provoke warnings when this option is used (even if there is a default label). This warning is enabled by -Wall.
  • -Wswitch-default — warn whenever a switch statement does not have a default case. bestie where's your safety net 😭
  • -Wswitch-enum — warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. case labels outside the enumeration range also provoke warnings when this option is used. The only difference between -Wswitch and this option is that this option gives a warning about an omitted enumeration code even if there is a default label. Strict mode activated 🔥
  • -Wno-switch-bool — do not warn when a switch statement has an index of boolean type and the case values are outside the range of a boolean type. It is possible to suppress this warning by casting the controlling expression to a type other than bool. For example:
        switch ((int) (a == 4))
          {
          ...
          }

This warning is enabled by default for C and C++ programs.

  • -Wno-switch-outside-range — this option controls warnings when a switch case has a value that is outside of its respective type range. This warning is enabled by default for C and C++ programs.
  • -Wno-switch-unreachable — do not warn when a switch statement contains statements between the controlling expression and the first case label, which will never be executed. For example:
        switch (cond)
          {
           i = 15;
          ...
           case 5:
          ...
          }

-Wswitch-unreachable does not warn if the statement between the controlling expression and the first case label is just a declaration:

        switch (cond)
          {
           int i;
          ...
           case 5:
           i = 5;
          ...
          }

This warning is enabled by default for C and C++ programs.

  • -Wsync-nand (C and C++ only) — warn when __sync_fetch_and_nand and __sync_nand_and_fetch built-in functions are used. These functions changed semantics in GCC 4.4. glow-up but make it breaking change 😬
  • -Wtrivial-auto-var-init — warn when -ftrivial-auto-var-init cannot initialize the automatic variable. A common situation is an automatic variable that is declared between the controlling expression and the first case label of a switch statement.
  • -Wunused-but-set-parameter — warn whenever a function parameter is assigned to, but otherwise unused (aside from its declaration). To suppress this warning use the unused attribute. This warning is also enabled by -Wunused together with -Wextra.
  • -Wunused-but-set-variable — warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). This warning is enabled by -Wall. To suppress this warning use the unused attribute. This warning is also enabled by -Wunused, which is enabled by -Wall.
  • -Wunused-function — warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by -Wall.
  • -Wunused-label — warn whenever a label is declared but not used. This warning is enabled by -Wall. To suppress this warning use the unused attribute.
  • -Wunused-local-typedefs (C, Objective-C, C++ and Objective-C++ only) — warn when a typedef locally defined in a function is not used. This warning is enabled by -Wall.
  • -Wunused-parameter — warn whenever a function parameter is unused aside from its declaration. To suppress this warning use the unused attribute.
  • -Wno-unused-result — do not warn if a caller of a function marked with attribute warn_unused_result does not use its return value. The default is -Wunused-result. Not me ignoring the return value 🙈
  • -Wunused-variable — warn whenever a local or static variable is unused aside from its declaration. This option implies -Wunused-const-variable=1 for C, but not for C++. This warning is enabled by -Wall. To suppress this warning use the unused attribute.
  • -Wunused-const-variable, -Wunused-const-variable=n — warn whenever a constant static variable is unused aside from its declaration. -Wunused-const-variable=1 is enabled by -Wunused-variable for C, but not for C++. In C this declares variable storage, but in C++ this is not an error since const variables take the place of #defines. To suppress this warning use the unused attribute.
    • -Wunused-const-variable=1 — this is the warning level that is enabled by -Wunused-variable for C. It warns only about unused static const variables defined in the main compilation unit, but not about static const variables declared in any header included.
    • -Wunused-const-variable=2 — this warning level also warns for unused constant static variables in headers (excluding system headers). This is the warning level of -Wunused-const-variable and must be explicitly requested since in C++ this isn't an error and in C it might be harder to clean up all headers included. highkey a whole cleanup project 🌸
  • -Wunused-value — warn whenever a statement computes a result that is explicitly not used. To suppress this warning cast the unused expression to void. This includes an expression-statement or the left-hand side of a comma expression that contains no side effects. For example, an expression such as x[i,j] causes a warning, while x[(void)i,j] does not. This warning is enabled by -Wall.
  • -Wunused — all the above -Wunused options combined. 🎀 In order to get a warning about an unused function parameter, you must either specify -Wextra -Wunused (note that -Wall implies -Wunused), or separately specify -Wunused-parameter.
  • -Wuninitialized — warn if an object with automatic or allocated storage duration is used without having been initialized. In C++, also warn if a non-static reference or non-static const member appears in a class without constructors. uninitialized variables are not the vibe, bestie 💀

Okay bestie, back to warning flags—the plot thickens ✨

Also, ngl, if you pass a pointer (or in C++, a reference) to an uninitialized object into a const-qualified argument of a built-in function that we know reads that object, this warning will catch it too. Lowkey useful. (-Wmaybe-uninitialized is the one that fires for ordinary functions, just so you know the difference 🫶)

If you specifically want to be warned about code that uses a variable's uninitialized value in its own initializer, like the chaos of int x = x;, then go turn on -Winit-self.

These warnings fire for individual uninitialized elements of struct, union, or array variables, as well as for whole variables that are just uninitialized entirely. They do not fire for variables or elements declared volatile. And because these warnings depend on optimization, which exact variables or elements get flagged depends on the precise optimization options and which version of GCC you're running. So like, it's a vibe, not a guarantee 😭

Also heads up: you might straight up get no warning about a variable that's only used to compute a value that itself is never used—because data flow analysis might just delete those computations before the warnings even get printed. Gone. Poof. 💨

In C++, this warning also warns about using uninitialized objects in member-initializer-lists. For example, GCC warns about b being uninitialized in this iconic little snippet:

struct A {
  int a;
  int b;
  A() : a(b) { }
};

  • -Wno-invalid-memory-model — this option controls warnings for invocations of __atomic Builtins, __sync Builtins, and the C11 atomic generic functions when the memory consistency argument is either invalid for the operation or outside the range of values of the memory_order enumeration. For example, since the __atomic_store and __atomic_store_n built-ins are only defined for the relaxed, release, and sequentially consistent memory orders, the following code gets diagnosed:
void store (int *i)
{
  __atomic_store_n (i, 0, memory_order_consume);
}

-Winvalid-memory-model is enabled by default. Slay for sensible defaults 💅


  • -Wmaybe-uninitialized — okay so for an object with automatic or allocated storage duration: if there exists a path from the function entry to a use of the object that is initialized, but there exist some other paths where the object is not initialized, the compiler emits a warning if it can't prove the uninitialized paths are never executed at run time. It's giving "I can't be sure this is safe so I'm telling on you" energy.

In addition, passing a pointer (or in C++, a reference) to an uninitialized object into a const-qualified function argument is also diagnosed by this warning. (-Wuninitialized is the one issued for built-in functions known to read the object.) And bestie, annotating the function with attribute access (none) tells the compiler the argument isn't used to access the object, and avoids the warning. Iconic workaround ✨

These warnings are only possible in optimizing compilation, because otherwise GCC simply doesn't keep track of the state of variables. No optimization, no tracking, no warning. Periodt.

These warnings are made optional because GCC may not be able to determine when the code is actually correct even though it looks like it has an error. Here's one example of how this can happen:

{
  int x;
  switch (y)
    {
    case 1: x = 1;
      break;
    case 2: x = 4;
      break;
    case 3: x = 5;
    }
  foo (x);
}

If the value of y is always 1, 2 or 3, then x is always initialized, but GCC doesn't know that. To suppress the warning, you need to provide a default case with assert(0) or similar code. Give the compiler the closure it needs 🫶

This option also warns when a non-volatile automatic variable might be changed by a call to longjmp. The compiler only sees the calls to setjmp. It cannot know where longjmp will be called—and honestly, a signal handler could call it at any point in the code, so like... it's a whole thing. As a result, you may get a warning even when there's actually no problem, because longjmp cannot in fact be called at the place that would cause a problem. False positive realness 😭

Some spurious warnings can be avoided if you declare all the functions you use that never return as noreturn. Little tip from me to you 💖

This warning is enabled by -Wall or -Wextra.


  • -Wunknown-pragmas — warns when a #pragma directive is encountered that GCC doesn't understand. If this command-line option is used, warnings are even issued for unknown pragmas in system header files. This is not the case if the warnings are only enabled by the -Wall command-line option. So like, -Wunknown-pragmas is the extra-thorough one 👑

  • -Wno-pragmas — do not warn about misuses of pragmas, like incorrect parameters, invalid syntax, or conflicts between pragmas. See also -Wunknown-pragmas. Let the pragmas live, honestly.

  • -Wno-prio-ctor-dtor — do not warn if a priority from 0 to 100 is used for a constructor or destructor. The use of constructor and destructor attributes lets you assign a priority to the constructor/destructor to control its order of execution before main is called or after it returns. The priority values must be greater than 100, because the compiler reserves priority values between 0–100 for the implementation. Respect the reserved range bestie 🚫

  • -Wstrict-aliasing — this option is only active when -fstrict-aliasing is active. It warns about code that might break the strict aliasing rules that the compiler is using for optimization. The warning doesn't catch all cases, but it does attempt to catch the more common pitfalls. It is included in -Wall. It is equivalent to -Wstrict-aliasing=3.

  • -Wstrict-aliasing=n — same deal, only active when -fstrict-aliasing is active. It warns about code that might break the strict aliasing rules the compiler is using for optimization. Higher levels correspond to higher accuracy (fewer false positives). Higher levels also correspond to more effort, similar to the way -O works. -Wstrict-aliasing is equivalent to -Wstrict-aliasing=3.

Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels don't warn but -fstrict-aliasing still breaks the code, since it has very few false negatives. However, it has many false positives. Warns for all pointer conversions between possibly incompatible types, even if never dereferenced. Runs in the front end only.

Level 2: Aggressive, quick, not too precise. May still have many false positives (not as many as level 1 though), and few false negatives (but possibly more than level 1). Unlike level 1, it only warns when an address is taken. Warns about incomplete types. Runs in the front end only.

Level 3 (default for -Wstrict-aliasing): Should have very few false positives and few false negatives. Slightly slower than levels 1 or 2 when optimization is enabled. Takes care of the common pun+dereference pattern in the front end: *(int*)&some_float. If optimization is enabled, it also runs in the back end, where it deals with multiple statement cases using flow-sensitive points-to information. Only warns when the converted pointer is dereferenced. Does not warn about incomplete types. The whole package, honestly 💅


  • -Wstrict-overflow
  • -Wstrict-overflow=n — this option is only active when signed overflow is undefined. It warns about cases where the compiler optimizes based on the assumption that signed overflow does not occur. Note that it does not warn about all cases where the code might overflow: it only warns about cases where the compiler actually implements some optimization. So this warning depends on the optimization level, iykyk.

An optimization that assumes signed overflow does not occur is perfectly safe if the values of the variables involved are such that overflow never actually happens. So this warning can easily give a false positive—a warning about code that is not actually a problem. To help focus on important issues, several warning levels are defined. And get this: no warnings are issued for the use of undefined signed overflow when estimating how many iterations a loop requires, in particular when determining whether a loop will be executed at all. That check is off the table.

  • -Wstrict-overflow=1 — warn about cases that are both questionable and easy to avoid. For example, the compiler simplifies x + 1 > x to 1. This level of -Wstrict-overflow is enabled by -Wall; higher levels are not, and must be explicitly requested.
  • -Wstrict-overflow=2 — also warn about other cases where a comparison is simplified to a constant. For example: abs (x) >= 0. This can only be simplified when signed integer overflow is undefined, because abs (INT_MIN) overflows to INT_MIN, which is less than zero. -Wstrict-overflow (with no level) is the same as -Wstrict-overflow=2.
  • -Wstrict-overflow=3 — also warn about other cases where a comparison is simplified. For example: x + 1 > 1 is simplified to x > 0.
  • -Wstrict-overflow=4 — also warn about other simplifications not covered by the above cases. For example: (x * 10) / 5 is simplified to x * 2.
  • -Wstrict-overflow=5 — also warn about cases where the compiler reduces the magnitude of a constant involved in a comparison. For example: x + 2 > y is simplified to x + 1 >= y. This is reported only at the highest warning level because this simplification applies to many comparisons, so this warning level gives a very large number of false positives. You've been warned, bestie 💀

  • -Wstring-compare — warns for calls to strcmp and strncmp whose result is determined to be either zero or non-zero in tests for such equality, owing to the length of one argument being greater than the size of the array the other argument is stored in (or the bound in the case of strncmp). Such calls could be mistakes. For example, the call to strcmp below is diagnosed because its result is necessarily non-zero irrespective of the contents of the array a. It's giving "this comparison can literally never be true" energy:
extern char a[4];
void f (char *d)
{
  strcpy (d, "string");
  ...
  if (0 == strcmp (a, d))   // cannot be true
    puts ("a and d are the same");
}

-Wstring-compare is enabled by -Wextra.

  • -Wno-stringop-overflow, -Wstringop-overflow, -Wstringop-overflow=type — bestie, this one yells at you when you call string-wrangling functions like memcpy and strcpy and GCC is like "girl that is definitely overflowing the destination buffer." 💀 The optional argument is one greater than the type of Object Size Checking used to figure out the size of the destination. Real talk though: that argument only means anything for functions that work on character arrays — it does nothing for raw memory functions like memcpy, which always use Object Size type-0, periodt. The option also warns about calls that specify a size bigger than the largest possible object or at most SIZE_MAX / 2 bytes. It gives its best results with optimization enabled, but ngl it can still catch a small subset of simple buffer overflows even without optimization, in calls to the GCC built-in functions like __builtin_memcpy that correspond to the standard functions. In any case (iykyk), the option only warns about a subset of the buffer overflows detected by the corresponding overflow checking built-ins. Like, for example, it issues a warning for the strcpy call below because it copies at least 5 characters (the string "blue" including the terminating NUL) into the buffer of size 4 🫶
enum Color { blue, purple, yellow };
const char* f (enum Color clr)
{
  static char buf [4];
  const char *str;
  switch (clr)
    {
      case blue: str = "blue"; break;
      case purple: str = "purple"; break;
      case yellow: str = "yellow"; break;
    }

  return strcpy (buf, str);   // warning here
}

Option -Wstringop-overflow=2 is enabled by default. ✨

  • -Wstringop-overflow, -Wstringop-overflow=1 — this setting uses type-zero Object Size Checking to figure out the sizes of destination objects. At this level the option does not warn for writes past the end of subobjects of larger objects accessed by pointers, unless the size of the largest surrounding object is known. When the destination might be one of several objects, it assumes it's the largest one of them. On Linux systems, when optimization is enabled at this setting, the option warns for the same code as when the _FORTIFY_SOURCE macro is defined to a non-zero value. slay 💅
  • -Wstringop-overflow=2 — this setting uses type-one Object Size Checking to figure out the sizes of destination objects. At this setting the option warns about overflows when writing to members of the largest complete objects whose exact size is known. However, it does not warn for excessive writes to the same members of unknown objects referenced by pointers, since they may point to arrays containing unknown numbers of elements. This is the default setting of the option 👑
  • -Wstringop-overflow=3 — this setting uses type-two Object Size Checking to figure out the sizes of destination objects. At this setting the option warns about overflowing the smallest object or data member. Heads up: this is the most restrictive setting of the option, and it may result in warnings for safe code 😭
  • -Wstringop-overflow=4 — this setting uses type-three Object Size Checking to figure out the sizes of destination objects. At this setting the option warns about overflowing any data members, and when the destination is one of several objects it uses the size of the largest of them to decide whether to issue a warning. Similarly to -Wstringop-overflow=3, this setting of the option may result in warnings for benign code 🙈

  • -Wno-stringop-overread — warns for calls to string manipulation functions such as memchr, or strcpy, that are determined to read past the end of the source sequence. Reading too far is giving chaotic energy and we do not stan 🚫

Option -Wstringop-overread is enabled by default. ✨

  • -Wno-stringop-truncation — do not warn for calls to bounded string manipulation functions such as strncat, strncpy, and stpncpy that may either truncate the copied string or leave the destination unchanged. (So this is the "okay bestie, I trust you" flag for those specific warnings.)

In the following example, the call to strncat specifies a bound that is less than the length of the source string. As a result, the copy of the source will be truncated and so the call is diagnosed 😬 To avoid the warning use bufsize - strlen (buf) - 1) as the bound.

void append (char *buf, size_t bufsize)
{
  strncat (buf, ".txt", 3);
}

As another example, the following call to strncpy results in copying to d just the characters preceding the terminating NUL, without appending the NUL to the end. Assuming the result of strncpy is necessarily a NUL-terminated string is a common mistake — like, everyone does it — and so the call is diagnosed. To avoid the warning when the result is not expected to be NUL-terminated, call memcpy instead 🫶

void copy (char *d, const char *s)
{
  strncpy (d, s, strlen (s));
}

In the following example, the call to strncpy specifies the size of the destination buffer as the bound. If the length of the source string is equal to or greater than this size the result of the copy will not be NUL-terminated. Therefore, the call is also diagnosed. To avoid the warning, specify sizeof buf - 1 as the bound and set the last element of the buffer to NUL.

void copy (const char *s)
{
  char buf[80];
  strncpy (buf, s, sizeof buf);
  ...
}

In situations where a character array is intended to store a sequence of bytes with no terminating NUL, such an array may be annotated with attribute nonstring to avoid this warning. Such arrays, however, are not suitable arguments to functions that expect NUL-terminated strings — that's a whole vibe killer. To help detect accidental misuses of such arrays GCC issues warnings unless it can prove that the use is safe. 🧚

  • -Wsuggest-attribute=[pure|const|noreturn|format|cold|malloc] — warns for cases where adding an attribute may be beneficial. The attributes currently supported are listed below, bestie, come get your faves:
    • -Wsuggest-attribute=pure, -Wsuggest-attribute=const, -Wsuggest-attribute=noreturn, -Wmissing-noreturn, -Wsuggest-attribute=malloc — warns about functions that might be candidates for attributes pure, const or noreturn or malloc. The compiler only warns for functions visible in other compilation units or (in the case of pure and const) if it cannot prove that the function returns normally. A function returns normally if it doesn't contain an infinite loop or return abnormally by throwing, calling abort or trapping. This analysis requires option -fipa-pure-const, which is enabled by default at -O and higher. Higher optimization levels improve the accuracy of the analysis — like, the vibe check gets more accurate 🔥
    • -Wsuggest-attribute=format, -Wmissing-format-attribute — warns about function pointers that might be candidates for format attributes. Note these are only possible candidates, not absolute ones — no cap. GCC guesses that function pointers with format attributes that are used in assignment, initialization, parameter passing or return statements should have a corresponding format attribute in the resulting type. I.e. the left-hand side of the assignment or initialization, the type of the parameter variable, or the return type of the containing function respectively should also have a format attribute to avoid the warning ✨

GCC also warns about function definitions that might be candidates for format attributes. Again, these are only possible candidates. GCC guesses that format attributes might be appropriate for any function that calls a function like vprintf or vscanf, but this might not always be the case, and some functions for which format attributes are appropriate may not be detected. It's giving "we tried our best" 💀

  • -Wsuggest-attribute=cold — warns about functions that might be candidates for cold attribute. This is based on static detection and generally only warns about functions which always leads to a call to another cold function such as wrappers of C++ throw or fatal error reporting functions leading to abort. 💀❄️
  • -Walloc-zero — warns about calls to allocation functions decorated with attribute alloc_size that specify zero bytes, including those to the built-in forms of the functions aligned_alloc, alloca, calloc, malloc, and realloc. Because the behavior of these functions when called with a zero size differs among implementations (and in the case of realloc has been deprecated), relying on it may result in subtle portability bugs and should be avoided. Fr fr, don't do it 🚫
  • -Walloc-size-larger-than=byte-size — warns about calls to functions decorated with attribute alloc_size that attempt to allocate objects larger than the specified number of bytes, or where the result of the size computation in an integer type with infinite precision would exceed the value of PTRDIFF_MAX on the target. -Walloc-size-larger-than=PTRDIFF_MAX is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of SIZE_MAX or more or by -Wno-alloc-size-larger-than 👑
  • -Wno-alloc-size-larger-than — disable -Walloc-size-larger-than= warnings. The option is equivalent to -Walloc-size-larger-than=SIZE_MAX or larger. Easy 💅
  • -Walloca — this option warns on all uses of alloca in the source. Every single one. No exceptions. Iconic, honestly.
  • -Walloca-larger-than=byte-size — this option warns on calls to alloca with an integer argument whose value is either zero, or that is not bounded by a controlling predicate that limits its value to at most byte-size. It also warns for calls to alloca where the bound value is unknown (rude). Arguments of non-integer types are considered unbounded even if they appear to be constrained to the expected range 🫠

For example, a bounded case of alloca could be:

void func (size_t n)
{
  void *p;
  if (n <= 1000)
    p = alloca (n);
  else
    p = malloc (n);
  f (p);
}

okay so in this example, passing -Walloca-larger-than=1000 would not warn you, because the call to alloca is provably at most 1000 bytes ✨. But the second you pass -Walloca-larger-than=500? boom, the compiler emits a warning 💀.

Unbounded uses, on the other hand, are uses of alloca with no controlling predicate constraining its integer argument. Like this little gremlin:

void func ()
{
  void *p = alloca (n);
  f (p);
}

If -Walloca-larger-than=500 were passed, the above would trigger a warning — but this time because of the lack of bounds checking 🙈.

And bestie, heads up: even seemingly correct code involving signed integers could cause a warning 😭:

void func (signed int n)
{
  if (n < 500)
    {
      p = alloca (n);
      f (p);
    }
}

In the above example, n could be negative, which means a larger-than-expected argument gets implicitly cast into the alloca call. like, sneaky 💅.

This option also warns when alloca is used in a loop 👀.

-Walloca-larger-than=PTRDIFF_MAX is enabled by default but is usually only effective when -ftree-vrp is active (default for -O2 and above).

See also -Wvla-larger-than=byte-size.

  • -Wno-alloca-larger-than — Disable -Walloca-larger-than= warnings. The option is equivalent to -Walloca-larger-than=SIZE_MAX or larger. 🫶
  • -Warith-conversion — Do warn about implicit conversions from arithmetic operations even when conversion of the operands to the same type cannot change their values. This affects warnings from -Wconversion, -Wfloat-conversion, and -Wsign-conversion.
void f (char c, int i)
{
  c = c + i; // warns with B<-Wconversion>
  c = c + 1; // only warns with B<-Warith-conversion>
}
  • -Warray-bounds, -Warray-bounds=n — Warn about out of bounds subscripts or offsets into arrays. This warning is enabled by -Wall. It is more effective when -ftree-vrp is active (the default for -O2 and above) but a subset of instances are issued even without optimization ✨.
    • -Warray-bounds=1 — This is the default warning level of -Warray-bounds and is enabled by -Wall; higher levels are not, and must be explicitly requested 👑.
    • -Warray-bounds=2 — This warning level also warns about out of bounds accesses to trailing struct members of one-element array types and about the intermediate results of pointer arithmetic that may yield out of bounds values. This warning level may give a larger number of false positives 🙈 and is deactivated by default.
  • -Warray-compare — Warn about equality and relational comparisons between two operands of array type. This comparison was deprecated in C++20. For example:
int arr1[5];
int arr2[5];
bool same = arr1 == arr2;

-Warray-compare is enabled by -Wall.

  • -Warray-parameter, -Warray-parameter=n — Warn about redeclarations of functions involving arguments of array or pointer types of inconsistent kinds or forms, and enable the detection of out-of-bounds accesses to such parameters by warnings such as -Warray-bounds.

If the first function declaration uses the array form, the bound specified in the array is assumed to be the minimum number of elements expected to be provided in calls to the function and the maximum number of elements accessed by it. Failing to provide arguments of sufficient size or accessing more than the maximum number of elements may be diagnosed by warnings such as -Warray-bounds. At level 1 the warning diagnoses inconsistencies involving array parameters declared using the T[static N] form 💅.

For example, the warning triggers for the following redeclarations because the first one allows an array of any size to be passed to f while the second one with the keyword static specifies that the array argument must have at least four elements:

void f (int[static 4]);
void f (int[]);           // warning (inconsistent array form)

void g (void)
{
  int *p = (int *)malloc (4);
  f (p);                  // warning (array too small)
  ...
}

At level 2 the warning also triggers for redeclarations involving any other inconsistency in array or pointer argument forms denoting array sizes. Pointers and arrays of unspecified bound are considered equivalent and do not trigger a warning 👀.

void g (int*);
void g (int[]);     // no warning
void g (int[8]);    // warning (inconsistent array bound)

-Warray-parameter=2 is included in -Wall. The -Wvla-parameter option triggers warnings for similar inconsistencies involving Variable Length Array arguments 🦋.

  • -Wattribute-alias=n, -Wno-attribute-alias — Warn about declarations using the alias and similar attributes whose target is incompatible with the type of the alias.
    • -Wattribute-alias=1 — The default warning level of the -Wattribute-alias option diagnoses incompatibilities between the type of the alias declaration and that of its target. Such incompatibilities are typically indicative of bugs 💀.
    • -Wattribute-alias=2 — At this level -Wattribute-alias also diagnoses cases where the attributes of the alias declaration are more restrictive than the attributes applied to its target. These mismatches can potentially result in incorrect code generation 😭. In other cases they may be benign and could be resolved simply by adding the missing attribute to the target. For comparison, see the -Wmissing-attributes option, which controls diagnostics when the alias declaration is less restrictive than the target, rather than more restrictive.

Attributes considered include alloc_align, alloc_size, cold, const, hot, leaf, malloc, nonnull, noreturn, nothrow, pure, returns_nonnull, and returns_twice ✨.

-Wattribute-alias is equivalent to -Wattribute-alias=1. This is the default. You can disable these warnings with either -Wno-attribute-alias or -Wattribute-alias=0.

  • -Wbidi-chars=[none|unpaired|any|ucn] — Warn about possibly misleading UTF-8 bidirectional control characters in comments, string literals, character constants, and identifiers 👀. Such characters can change left-to-right writing direction into right-to-left (and vice versa), which can cause confusion between the logical order and visual order. This may be dangerous 🔥 — for instance, it may seem that a piece of code is not commented out, whereas it in fact is. yikes.

There are three levels of warning supported by GCC. The default is -Wbidi-chars=unpaired, which warns about improperly terminated bidi contexts. -Wbidi-chars=none turns the warning off. -Wbidi-chars=any warns about any use of bidirectional control characters.

By default, this warning does not warn about UCNs. It is, however, possible to turn on such checking by using -Wbidi-chars=unpaired,ucn or -Wbidi-chars=any,ucn. Using -Wbidi-chars=ucn is valid, and is equivalent to -Wbidi-chars=unpaired,ucn, if no previous -Wbidi-chars=any was specified 💅.

  • -Wbool-compare — Warn about boolean expression compared with an integer value different from true/false. For instance, the following comparison is always false:
int n = 5;
...
if ((n > 1) == 2) { ... }

This warning is enabled by -Wall.

  • -Wbool-operation — Warn about suspicious operations on expressions of a boolean type. For instance, bitwise negation of a boolean is very likely a bug in the program 😭. For C, this warning also warns about incrementing or decrementing a boolean, which rarely makes sense. (In C++, decrementing a boolean is always invalid. Incrementing a boolean is invalid in C++17, and deprecated otherwise.)

This warning is enabled by -Wall.

  • -Wduplicated-branches — Warn when an if-else has identical branches. This warning detects cases like:
if (p != NULL)
  return 0;
else
  return 0;

It doesn't warn when both branches contain just a null statement. This warning also warns for conditional operators:

int i = x ? *p : *p;
  • -Wduplicated-cond — Warn about duplicated conditions in an if-else-if chain. For instance, warn for the following code:
if (p->q != NULL) { ... }
else if (p->q != NULL) { ... }
  • -Wframe-address — Warn when the __builtin_frame_address or __builtin_return_address is called with an argument greater than 0. Such calls may return indeterminate values or crash the program 💀. The warning is included in -Wall.
  • -Wno-discarded-qualifiers (C and Objective-C only) — Do not warn if type qualifiers on pointers are being discarded. Typically, the compiler warns if a const char * variable is passed to a function that takes a char * parameter. This option can be used to suppress such a warning 🙈.
  • -Wno-discarded-array-qualifiers (C and Objective-C only) — Do not warn if type qualifiers on arrays which are pointer targets are being discarded. Typically, the compiler warns if a const int (*)[] variable is passed to a function that takes a int (*)[] parameter. This option can be used to suppress such a warning ✨.
  • -Wno-incompatible-pointer-types (C and Objective-C only) — Do not warn when there is a conversion between pointers that have incompatible types. This warning is for cases not covered by -Wno-pointer-sign, which warns for pointer argument passing or assignment with different signedness 💅.
  • -Wno-int-conversion (C and Objective-C only) — bestie, this one kills the warning about incompatible integer→pointer and pointer→integer conversions. Heads up tho: this warning is all about implicit conversions. For explicit ones you gotta reach for -Wno-int-to-pointer-cast and -Wno-pointer-to-int-cast instead. iykyk 💅
  • -Wzero-length-bounds — warns you when you access elements of zero-length array members that might overlap other members of the same object. And listen, declaring interior zero-length arrays is discouraged because accessing them is undefined — like, don't do it, fr fr. See

For example, in function bad below, the first two stores get diagnosed because the array elements overlap the subsequent members b and c. The third store gets diagnosed by -Warray-bounds because it's beyond the bounds of the enclosing object. 😭

struct X { int a[0]; int b, c; };
struct X x;

void bad (void)
{
  x.a[0] = 0;   // -Wzero-length-bounds
  x.a[1] = 1;   // -Wzero-length-bounds
  x.a[2] = 2;   // -Warray-bounds
}

Lowkey convenient: -Wzero-length-bounds is enabled by -Warray-bounds. ✨

  • -Wno-div-by-zero — do not warn about compile-time integer division by zero. But floating-point division by zero? Not warned about at all, because that can legitimately be how you get your infinities and NaNs. 🌀 Not a bug, it's a feature energy.
  • -Wsystem-headers — prints warning messages for constructs found in system header files. Normally warnings from system headers are suppressed, on the assumption that they usually don't indicate real problems and would just make the compiler output harder to read. Using this command-line option tells GCC to emit warnings from system headers as if they occurred in user code. But — plot twist — using -Wall together with this option does not warn about unknown pragmas in system headers. For that, -Wunknown-pragmas must also be used. 🫶
  • -Wtautological-compare — warns when a self-comparison always evaluates to true or false. It catches little mistakes like this iconic one:
int i = 1;
...
if (i > i) { ... }

It also warns about bitwise comparisons that always evaluate to true or false, for instance:

if ((a & 16) == 10) { ... }

…which will always be false. Not me writing code that can never run 😭. This warning is enabled by -Wall.

  • -Wtrampolines — warns about trampolines generated for pointers to nested functions. A trampoline is a small piece of data or code that's created at run time on the stack when the address of a nested function is taken, and it's used to call the nested function indirectly. For some targets it's made up of data only and thus requires no special treatment. But for most targets it's made up of code, and thus requires the stack to be made executable for the program to work properly. 💀 Executable stack, bestie — be aware.
  • -Wfloat-equal — warns if floating-point values are used in equality comparisons. The idea behind it: sometimes it's convenient (for the programmer) to consider floating-point values as approximations to infinitely precise real numbers. If that's what you're doing, you need to compute — by analyzing the code, or in some other way — the maximum or likely maximum error that the computation introduces, and allow for it when performing comparisons (and when producing output, but that's a different problem). In particular, instead of testing for equality, you should check whether the two values have ranges that overlap; that's done with the relational operators, so equality comparisons are probably mistaken. 🧚 Basically: == on floats is giving chaos.
  • -Wtraditional (C and Objective-C only) — warns about certain constructs that behave differently in traditional C and ISO C. Also warns about ISO C constructs that have no traditional C equivalent, and/or problematic constructs that should be avoided. Buckle up, this list is long 👑
    • Macro parameters that appear within string literals in the macro body. In traditional C, macro replacement takes place within string literals, but in ISO C it does not.
    • In traditional C, some preprocessor directives did not exist. Traditional preprocessors only considered a line to be a directive if the # appeared in column 1 on the line. Therefore -Wtraditional warns about directives that traditional C understands but ignores because the # does not appear as the first character on the line. It also suggests you hide directives like #pragma that traditional C doesn't understand by indenting them. Some traditional implementations don't recognize #elif, so this option suggests avoiding it altogether.
    • A function-like macro that appears without arguments.
    • The unary plus operator.
    • The U integer constant suffix, or the F or L floating-point constant suffixes. (Traditional C does support the L suffix on integer constants.) Note: these suffixes appear in macros defined in the system headers of most modern systems, e.g. the _MIN/_MAX macros in <limits.h>. Use of these macros in user code might normally lead to spurious warnings, however GCC's integrated preprocessor has enough context to avoid warning in these cases. 🫶
    • A function declared external in one block and then used after the end of the block.
    • A switch statement has an operand of type long.
    • A non-static function declaration follows a static one. This construct is not accepted by some traditional C compilers.
    • The ISO type of an integer constant has a different width or signedness from its traditional type. This warning is only issued if the base of the constant is ten. I.e. hexadecimal or octal values, which typically represent bit patterns, are not warned about.
    • Usage of ISO string concatenation is detected.
    • Initialization of automatic aggregates.
    • Identifier conflicts with labels. Traditional C lacks a separate namespace for labels.
    • Initialization of unions. If the initializer is zero, the warning is omitted. This is done under the assumption that the zero initializer in user code appears conditioned on e.g. __STDC__ to avoid missing initializer warnings, and relies on default initialization to zero in the traditional C case.
    • Conversions by prototypes between fixed/floating-point values and vice versa. The absence of these prototypes when compiling with traditional C causes serious problems. This is a subset of the possible conversion warnings; for the full set use -Wtraditional-conversion.
    • Use of ISO C style function definitions. This warning intentionally is not issued for prototype declarations or variadic functions because these ISO C features appear in your code when using libiberty's traditional C compatibility macros, PARAMS and VPARAMS. This warning is also bypassed for nested functions because that feature is already a GCC extension and thus not relevant to traditional C compatibility.
  • -Wtraditional-conversion (C and Objective-C only) — warns if a prototype causes a type conversion that's different from what would happen to the same argument in the absence of a prototype. This includes conversions of fixed point to floating and vice versa, and conversions changing the width or signedness of a fixed-point argument — except when it's the same as the default promotion. ✨
  • -Wdeclaration-after-statement (C and Objective-C only) — warns when a declaration is found after a statement in a block. This construct, known from C++, was introduced with ISO C99 and is by default allowed in GCC. It is not supported by ISO C90. So if you're living that C90 life, this one's your friend 🎀
  • -Wshadow — warns whenever a local variable or type declaration shadows another variable, parameter, type, class member (in C++), or instance variable (in Objective-C), or whenever a built-in function is shadowed. Note that in C++, the compiler warns if a local variable shadows an explicit typedef, but not if it shadows a struct/class/enum. If this warning is enabled, it also includes all instances of local shadowing. This means -Wno-shadow=local and -Wno-shadow=compatible-local are ignored when -Wshadow is used. Same as -Wshadow=global. 👑
  • -Wno-shadow-ivar (Objective-C only) — do not warn whenever a local variable shadows an instance variable in an Objective-C method. 🙈
  • -Wshadow=global — warns for any shadowing. Same as -Wshadow. 🌍
  • -Wshadow=local — warns when a local variable shadows another local variable or parameter. 🏠
  • -Wshadow=compatible-local — warns when a local variable shadows another local variable or parameter whose type is compatible with that of the shadowing variable. In C++, type compatibility here means the type of the shadowing variable can be converted to that of the shadowed variable. The creation of this flag (in addition to -Wshadow=local) is based on the idea that when a local variable shadows another one of incompatible type, it's most likely intentional, not a bug or typo — as shown in the following example:
for (SomeIterator i = SomeObj.begin(); i != SomeObj.end(); ++i)
{
  for (int i = 0; i < N; ++i)
  {
    ...
  }
  ...
}

Since the two variable i in the example above have incompatible types, enabling only -Wshadow=compatible-local does not emit a warning. Because their types are incompatible, if a programmer accidentally uses one in place of the other, type checking is expected to catch that and emit an error or warning. Use of this flag instead of -Wshadow=local can possibly reduce the number of warnings triggered by intentional shadowing. Note that this also means that shadowing const char *i by char *i does not emit a warning. 🦋

This warning is also enabled by -Wshadow=local.

  • -Wlarger-than=byte-size — warns whenever an object is defined whose size exceeds byte-size. -Wlarger-than=PTRDIFF_MAX is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of SIZE_MAX or more, or by -Wno-larger-than. 🔥

Also lowkey it'll yell at you for calling bounded functions like memchr or strnlen with a bound bigger than the actual biggest possible object ever — which is PTRDIFF_MAX bytes by default. And these warnings? The only way to mute them is -Wno-larger-than, periodt.

  • -Wno-larger-than — kills the -Wlarger-than= warnings. It's literally the same thing as -Wlarger-than=SIZE_MAX or bigger. same energy, zero drama 💅
  • -Wframe-larger-than=byte-size — warns you when a function's stack frame gets bigger than byte-size. Okay but heads up bestie: the math it does to figure out the frame size is approximate and not conservative, so the real size can be a lil bigger than byte-size even if you got no warning at all 😭. Also, anything you allocate with alloca, variable-length arrays, or similar constructs? The compiler straight-up doesn't count that when deciding whether to warn. -Wframe-larger-than=PTRDIFF_MAX is on by default, and you can silence these warnings either by passing a byte-size of SIZE_MAX or more, or with -Wno-frame-larger-than.
  • -Wno-frame-larger-than — turns off the -Wframe-larger-than= warnings. Equivalent to -Wframe-larger-than=SIZE_MAX or larger. bye felicia 🫶
  • -Wfree-nonheap-object — calls out when you try to deallocate something that either wasn't allocated on the heap at all, or that you're freeing through a pointer that didn't come from a prior call to the matching allocation function. Like, the call to stpcpy hands you back a pointer to the terminating nul character, not to the start of the object — so this free gets diagnosed:
void f (char *p)
{
  p = stpcpy (p, "abc");
  // ...
  free (p);   // warning
}

-Wfree-nonheap-object is included in -Wall. no cap, it's watching 👀

  • -Wstack-usage=byte-size — warns if a function's stack usage might blow past byte-size. The math here is conservative (unlike that frame one), and any space from alloca, variable-length arrays, or related constructs is counted by the compiler when deciding to warn. ✨

The message matches what -fstack-usage spits out:

  • If the stack usage is fully static but over the limit, it's:
warning: stack usage is 1120 bytes
  • If the stack usage is (partly) dynamic but bounded, it's:
warning: stack usage might be 1648 bytes
  • If the stack usage is (partly) dynamic and not bounded, it's:
warning: stack usage might be unbounded

-Wstack-usage=PTRDIFF_MAX is enabled by default. You can disable the warnings either by passing a byte-size of SIZE_MAX or more, or with -Wno-stack-usage.

  • -Wno-stack-usage — disables -Wstack-usage= warnings. Same as -Wstack-usage=SIZE_MAX or larger. 💜
  • -Wunsafe-loop-optimizations — warns if a loop can't be optimized because the compiler can't assume anything about the bounds of the loop indices. And with -funsafe-loop-optimizations it warns if the compiler does make those assumptions. messy either way 🙈
  • -Wno-pedantic-ms-format (MinGW targets only) — when you use it together with -Wformat and -pedantic and no GNU extensions, this disables the warnings about the non-ISO printf / scanf format width specifiers I32, I64, and I used on Windows targets, since those depend on the MS runtime. iykyk 🪟
  • -Wpointer-arith — warns about anything that depends on the "size of" a function type or of void. GNU C just assigns those types a size of 1 for convenience when doing math with void * pointers and function pointers, so it's being nice, but it's warning you anyway. In C++ it also warns when an arithmetic operation involves NULL. Also enabled by -Wpedantic. ✨
  • -Wno-pointer-compare — don't warn when a pointer gets compared against a zero character constant (which usually means you meant to dereference it, oops). Like this:
const char *p = foo ();
if (p == '\0')
  return 42;

Note that the code above is invalid in C++11, jsyk. This warning is enabled by default.

  • -Wtsan — warns about stuff ThreadSanitizer doesn't support. ThreadSanitizer can't handle std::atomic_thread_fence and can report false positives. This warning is enabled by default. 💀
  • -Wtype-limits — warns when a comparison is always true or always false because the data type's range is limited — but it does not warn for constant expressions. Example: warn if an unsigned variable gets compared against zero with < or >=. Also enabled by -Wextra. slay 💅
  • -Wabsolute-value (C and Objective-C only) — warns on calls to standard functions that compute an absolute value when a better-suited standard function exists. Like, abs(3.14) triggers it because the right function for a double is fabs. It also fires when the argument in that kind of call has an unsigned type. You can suppress it with an explicit type cast, and it's also enabled by -Wextra. 🎀
  • -Wcomment, -Wcomments — warns whenever a comment-start sequence /* shows up inside a /* comment, or whenever a backslash-newline appears inside a // comment. Enabled by -Wall. 💬
  • -Wtrigraphs — warns if any trigraphs pop up that might change what the program means. Trigraphs inside comments don't get warned about, except the ones that would form escaped newlines. 🌀

This option is implied by -Wall. If -Wall isn't given, it's still enabled unless trigraphs are enabled. Want trigraph conversion without the warnings but still get the other -Wall warnings? Use -trigraphs -Wall -Wno-trigraphs.

  • -Wundef — warns if an undefined identifier gets evaluated in an #if directive. Those identifiers just get replaced with zero, but it'll still call it out.
  • -Wexpansion-to-defined — warns whenever defined shows up in the expansion of a macro (including when the macro is expanded by an #if directive). That usage isn't portable. Also enabled by -Wpedantic and -Wextra. 🌈
  • -Wunused-macros — warns about macros defined in the main file that never get used. A macro counts as used if it's expanded or checked for existence at least once. The preprocessor also warns if the macro hasn't been used by the time it gets redefined or undefined. 🦋

Built-in macros, macros defined on the command line, and macros defined in include files are not warned about.

Note: if a macro actually is used but only inside skipped conditional blocks, the preprocessor reports it as unused. 😭 To dodge the warning, you could tighten the macro's definition scope — like moving it into the first skipped block — or just give it a dummy use, something like:

#if defined the_macro_causing_the_warning
#endif
  • -Wno-endif-labels — don't warn when an #else or an #endif is followed by text. This happens sometimes in older programs written like:
#if FOO
...
#else FOO
...
#endif FOO

That second and third FOO should really be in comments. This warning is on by default.

  • -Wbad-function-cast (C and Objective-C only) — warns when a function call gets cast to a type that doesn't match. Like, warn if a call to a function returning an integer type is cast to a pointer type. 🙈
  • -Wc90-c99-compat (C and Objective-C only) — warns about features that aren't in ISO C90 but are in ISO C99. For instance, variable length arrays, the long long type, the bool type, compound literals, designated initializers, and so on. This option is independent of the standards mode, and warnings are disabled in the expression that follows __extension__. 🔥
  • -Wc99-c11-compat (C and Objective-C only) — warns about features not in ISO C99 but present in ISO C11. For instance, anonymous structures and unions, the _Atomic type qualifier, the _Thread_local storage-class specifier, the _Alignas specifier, the Alignof operator, the _Generic keyword, and so on. Independent of the standards mode too, and warnings are disabled in the expression that follows __extension__. ✨
  • -Wc11-c2x-compat (C and Objective-C only) — warns about features not in ISO C11 but present in ISO C2X. For instance, omitting the string in _Static_assert, using [[]] syntax for attributes, decimal floating-point types, and so on. Independent of the standards mode, and warnings are disabled in the expression that follows __extension__. 🧚
  • -Wc++-compat (C and Objective-C only) — warns about ISO C constructs that fall outside the common subset of ISO C and ISO C++, like asking for an implicit conversion from void * to a pointer to a non-void type. 🌸
  • -Wc++11-compat (C++ and Objective-C++ only) — warns about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 2011, e.g. identifiers that were fine in ISO C++ 1998 but are keywords in ISO C++ 2011. This warning turns on -Wnarrowing and is enabled by -Wall. 👑
  • -Wc++14-compat (C++ and Objective-C++ only) — warns about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014. Enabled by -Wall.
  • -Wc++17-compat (C++ and Objective-C++ only) — warns about C++ constructs whose meaning differs between ISO C++ 2014 and ISO C++ 2017. Enabled by -Wall.
  • -Wc++20-compat (C++ and Objective-C++ only) — warns about C++ constructs whose meaning differs between ISO C++ 2017 and ISO C++ 2020. Enabled by -Wall. ⭐
  • -Wno-c++11-extensions (C++ and Objective-C++ only) — don't warn about C++11 constructs when the code is being compiled with an older C++ standard. Even without this option, some C++11 constructs only get diagnosed if -Wpedantic is used. 🫶
  • -Wno-c++14-extensions (C++ and Objective-C++ only) — don't warn about C++14 constructs when compiling with an older C++ standard. Even without this option, some C++14 constructs only get diagnosed if -Wpedantic is used. 💜

💅 -Wno-c++17-extensions (C++ and Objective-C++ only)

okay so this one says: don't warn about C++17 constructs when you're compiling with an older C++ standard. but bestie, heads up — even with this flag on, some C++17 stuff will still get diagnosed, but only if you're also using -Wpedantic. so it's giving "mostly quiet, not fully quiet" ✨

🌸 -Wno-c++20-extensions (C++ and Objective-C++ only)

same vibe, newer year: no warnings about C++20 constructs in code that's being compiled with an older C++ standard. and yeah, same caveat — even without this option, some C++20 constructs only get diagnosed when -Wpedantic is in the mix. 🦋

🎀 -Wno-c++23-extensions (C++ and Objective-C++ only)

and the trilogy finale 💖 — don't warn about C++23 constructs when compiling with an older C++ standard. and yes, once again: even without this option, some C++23 constructs will only be diagnosed if you pass -Wpedantic. iykyk 🫶


🔥 -Wcast-qual

warn whenever a pointer gets cast in a way that removes a type qualifier from the target type. like, if a const char * gets cast to a plain old char *? yeah, that's a warning, and honestly it should be 😭

it also warns when you make a cast that introduces a type qualifier in an unsafe way. for example, casting char ** to const char ** is unsafe — and here's exactly why, look:

/* p is char ** value.  */
const char **q = (const char **) p;
/* Assignment of readonly string to const char * is OK.  */
*q = "string";
/* Now char** pointer points to read-only memory.  */
**p = 'b';

like… see how that sneaks read-only memory into a non-const pointer? 💀 not the vibe.

⭐ -Wcast-align

warn whenever a pointer gets cast such that the required alignment of the target is increased. example time: warn if a char * is cast to an int * on machines where integers can only be accessed at two- or four-byte boundaries. alignment girlies stay winning 🧚

🌈 -Wcast-align=strict

basically the same warning — pointer cast that raises the required alignment of the target, e.g. char * → int * — except this one fires regardless of the target machine. no machines exempted, periodt 👑

💜 -Wcast-function-type

warn when a function pointer is cast to an incompatible function pointer. the deets:

  • in a cast involving function types with a variable argument list, only the types of the initial arguments that are provided are considered
  • any parameter of pointer-type matches any other pointer-type
  • any benign differences in integral types are ignored, like int vs. long on ILP32 targets
  • likewise, type qualifiers are ignored
  • the function type void (*) (void) is special and matches everything — which, fun fact, you can use to suppress this warning 🙈
  • in a cast involving pointer to member types, this warning fires whenever the type cast is changing the pointer to member type

and this warning is enabled by -Wextra. 🫶

🍓 -Wwrite-strings

when compiling C, this gives string constants the type const char[length] — so copying the address of one into a non-const char * pointer produces a warning. these warnings help you catch, at compile time, code that might try to write into a string constant… but only if you've been super careful about using const in declarations and prototypes. otherwise? it's just a nuisance 😭 which is literally why we did not make -Wall request these warnings. iconic reasoning tbh.

when compiling C++, it warns about the deprecated conversion from string literals to char *. and this warning is enabled by default for C++ programs ✨

🧚 -Wclobbered

warn for variables that might get changed by longjmp or vfork. sneaky little gremlins 😤 this warning is also enabled by -Wextra.

👑 -Wconversion

warn for implicit conversions that may alter a value. and the receipts:

  • conversions between real and integer — like abs (x) when x is double
  • conversions between signed and unsigned — like unsigned ui = -1
  • conversions to smaller types — like sqrtf (M_PI)

it does not warn for explicit casts like abs ((int) x) and ui = (unsigned) -1, or if the value isn't changed by the conversion, like in abs (2.0) ✨

warnings about conversions between signed and unsigned integers can be turned off with -Wno-sign-conversion.

for C++, it also warns for confusing overload resolution for user-defined conversions, and conversions that never use a type conversion operator: conversions to void, the same type, a base class, or a reference to them. warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.

oh and — warnings about conversion from arithmetic on a small type back to that type only happen with -Warith-conversion. noted 📝

💀 -Wdangling-else

warn about constructions where it's confusing which if statement an else branch belongs to. here's the classic offender:

{
  if (a)
    if (b)
      foo ();
  else
    bar ();
}

in C/C++, every else branch belongs to the innermost possible if statement — which in this example is if (b). and that is often not what the programmer expected, as the indentation above so rudely illustrates 😭 when there's potential for this confusion, GCC issues a warning when this flag is specified. to kill the warning, add explicit braces around the innermost if statement so there's no way the else can belong to the enclosing if. the glow-up looks like this:

{
  if (a)
    {
      if (b)
        foo ();
      else
        bar ();
    }
}

this warning is enabled by -Wparentheses. 🎀

🦋 -Wdangling-pointer, -Wdangling-pointer=n

warn about uses of pointers (or C++ references) to objects with automatic storage duration after their lifetime has ended. this includes:

  • local variables declared in nested blocks
  • compound literals
  • other unnamed temporary objects

plus it warns about storing the address of such objects in escaped pointers. it's enabled at all optimization levels, but may yield different results with optimization than without 👀

  • -Wdangling-pointer=1 — at level 1, the warning only diagnoses unconditional uses of dangling pointers. for example:
int f (int c1, int c2, x)
{
  char *p = strchr ((char[]){ c1, c2 }, c3);
  return p ? *p : 'x';   // warning: dangling pointer to a compound literal
}

and in the following function, the store of the address of the local variable x in the escaped pointer *p also triggers the warning:

void g (int **p)
{
  int x = 7;
  *p = &x;   // warning: storing the address of a local variable in *p
}
  • -Wdangling-pointer=2 — at level 2, on top of unconditional uses, the warning also diagnoses conditional uses of dangling pointers. for example, because the array a in the following function is out of scope when the pointer s that was set to point at it is used, the warning triggers at this level:
void f (char *s)
{
  if (!s)
    {
      char a[12] = "tmpname";
      s = a;
    }
  strcat (s, ".tmp");   // warning: dangling pointer to a may be used
  ...
}

and btw, -Wdangling-pointer=2 is included in -Wall. slay 🔥

🌸 -Wdate-time

warn when the macros __TIME__, __DATE__ or __TIMESTAMP__ are encountered — because they might prevent bit-wise-identical reproducible compilations. reproducible builds girlies, we see you 🫶

✨ -Wempty-body

warn if an empty body shows up in an if, else or do while statement. like… nothing? in this economy? 😭 this warning is also enabled by -Wextra.

🎀 -Wno-endif-labels

do not warn about stray tokens after #else and #endif. mind ya business 🙈

💖 -Wenum-compare

warn about a comparison between values of different enumerated types. in C++, enumerated type mismatches in conditional expressions are also diagnosed, and the warning is enabled by default. in C, this warning is enabled by -Wall. 🍓

🌈 -Wenum-conversion

warn when a value of enumerated type gets implicitly converted to a different enumerated type. in C, this warning is enabled by -Wextra. ⭐

🧚 -Wjump-misses-init (C, Objective-C only)

warn if a goto statement or a switch statement:

  • jumps forward across the initialization of a variable, or
  • jumps backward to a label after the variable has been initialized

it only warns about variables that are initialized when they're declared, tho. and this warning is only supported for C and Objective-C — because in C++ this sort of branch is an error in any case 💀 no warning needed, the compiler's just gonna say no.

-Wjump-misses-init is included in -Wc++-compat. it can be disabled with the -Wno-jump-misses-init option. 🫶

👑 -Wsign-compare

warn when a comparison between signed and unsigned values could produce an incorrect result when the signed value gets converted to unsigned. classic chaos 😤 in C++, this warning is also enabled by -Wall. in C, it's also enabled by -Wextra.

💜 -Wsign-conversion

warn for implicit conversions that may change the sign of an integer value — like assigning a signed integer expression to an unsigned integer variable. an explicit cast silences the warning. in C, this option is enabled also by -Wconversion. ✨

🍓 -Wfloat-conversion

warn for implicit conversions that reduce the precision of a real value. that includes conversions from real to integer, and from higher precision real to lower precision real values. this option is also enabled by -Wconversion. 💅

🦋 -Wno-scalar-storage-order

do not warn on suspicious constructs involving reverse scalar storage order. nothing to see here, move along 🙈

🔥 -Wsizeof-array-div

warn about divisions of two sizeof operators when the first one is applied to an array and the divisor does not equal the size of the array element. in that case the computation will not yield the number of elements in the array — which is, let's be real, what the user probably wanted 😭 this warning warns about stuff like:

int fn ()
{
  int arr[10];
  return sizeof (arr) / sizeof (short);
}

and this warning is enabled by -Wall. periodt 👑

  • -Wsizeof-pointer-div — this one's for when you do that classic "divide two sizeofs" thing that lowkey only works for arrays, bestie 💅 like the whole sizeof (ptr) / sizeof (ptr[0]) vibe? Yeah, if ptr isn't actually an array but a pointer, that math does NOT work out and GCC will call you out on it. Warning's enabled by -Wall. Slay for catching it.
  • -Wsizeof-pointer-memaccess — warns you about sus length params getting passed to certain string and memory built-ins when the argument is using sizeof, no cap. Like the classic memset (ptr, 0, sizeof (ptr)); situation where ptr is a pointer not an array — GCC flags it and even suggests a possible fix 🫶. Also clocks things like memcpy (&foo, ptr, sizeof (&foo));.

It also warns about calls to bounded string-copy functions like strncat or strncpy that use a sizeof of the source array as the bound. For example, in this function the strncat call specifies the size of the source string as its bound — that's almost certainly a mistake, so the call gets diagnosed:

void make_file (const char *name)
{
  char path[PATH_MAX];
  strncpy (path, name, sizeof path - 1);
  strncat (path, ".text", sizeof ".text");
  ...
}

This option is enabled by -Wall, periodt.

  • -Wno-sizeof-array-argument — do NOT warn when you point sizeof at a parameter that's declared as an array in a function definition. This warning is actually on by default for C and C++ programs, so this flag is your off-switch 💖.
  • -Wmemset-elt-size — warns on sus memset built-in calls where the first arg references an array AND the third arg is a number equal to the number of elements but not equal to the array's size in memory 😭. It's giving "you forgot to multiply by the element size." Enabled by -Wall, iconic.
  • -Wmemset-transposed-args — catches sus memset calls where the second arg isn't zero and the third arg is zero. Like memset (buf, sizeof buf, 0) gets diagnosed because bestie, you clearly meant memset (buf, 0, sizeof buf) 🙈. The diagnostic ONLY fires if the third arg is a literal zero — if it's an expression folded to zero, or a cast of zero to some type, then it's way less likely the args got transposed and no warning happens. Enabled by -Wall.
  • -Waddress — warns about sus uses of address expressions ✨. This includes comparing the address of a function or declared object to the null pointer constant, like this:
void f (void);
void g (void)
{
  if (!func)   // warning: expression evaluates to false
    abort ();
}

comparisons of a pointer to a string literal, like:

void f (const char *x)
{
  if (x == "abc")   // warning: expression evaluates to false
    puts ("equal");
}

and tests of pointer addition/subtraction results for equality to null:

void f (const int *p, int i)
{
  return p + i == NULL;
}

These uses typically mean programmer error 💀 — the address of most functions and objects necessarily evaluates to true (the exception being weak symbols), so using them in a conditional might mean you forgot parentheses in a function call or forgot a dereference in an array expression. The object-pointer subset of the warning can be suppressed by casting the pointer operand to an integer type like inptr_t or uinptr_t. Comparisons against string literals give unspecified behavior, aren't portable, and strongly suggest you meant to call strcmp. Warning's suppressed if the sus expression is the result of macro expansion. -Waddress is enabled by -Wall.

  • -Wno-address-of-packed-member — do NOT warn when the address of a packed member of a struct or union gets taken, which usually gives you an unaligned pointer value. This one's on by default, so this is your off-switch 🎀.
  • -Wlogical-op — warns about sus logical-operator uses in expressions, including using logical operators where a bit-wise one was probably expected 👀. Also warns when a logical operator's operands are the same:
extern int a;
if (a < 0 && a < 0) { ... }
  • -Wlogical-not-parentheses — warns about logical not being used on the left-hand operand of a comparison. Doesn't warn if the right operand is considered a boolean expression. The whole point is catching sus code like:
int a;
...
if (!a > 1) { ... }

You CAN suppress it by wrapping the LHS in parens:

if ((!a) > 1) { ... }

Enabled by -Wall, bestie.

  • -Waggregate-return — warns if any functions that return structs or unions get defined or called. (In languages where you can return an array, that also triggers it.) 🦋
  • -Wno-aggressive-loop-optimizations — warns if, in a loop with a constant number of iterations, the compiler detects undefined behavior in some statement during one or more of those iterations 😭.
  • -Wno-attributes — do NOT warn if an unexpected __attribute__ shows up — like unrecognized attributes, function attributes applied to variables, etc. Doesn't stop errors for incorrect use of supported attributes tho.

Also, with -Wno-attributes=, you can suppress warnings about unknown scoped attributes (in C++11 and C2X) ✨. For example, -Wno-attributes=vendor::attr disables the warning for this declaration:

[[vendor::attr]] void f();

You can also kill warnings about ALL attributes in a namespace using -Wno-attributes=vendor::, which prevents warnings about both of these:

[[vendor::safe]] void f();
[[vendor::unsafe]] void f2();

Note that -Wno-attributes= does NOT imply -Wno-attributes 👑.

  • -Wno-builtin-declaration-mismatch — warns if a built-in function is declared with an incompatible signature or as a non-function, or when a built-in declared with a type that doesn't include a prototype gets called with args whose promoted types don't match what the function expects 🙈. With -Wextra, it ALSO warns when a built-in that takes args is declared without a prototype. The -Wbuiltin-declaration-mismatch warning is on by default. To dodge it, include the appropriate header so the built-in prototypes are in scope.

For example, this memset call gets diagnosed because the function expects a size_t but the type of 32 is int. With -Wextra, the function declaration is diagnosed too:

extern void* memset ();
void f (void *d)
{
  memset (d, '\0', 32);
}
  • -Wno-builtin-macro-redefined — do NOT warn if certain built-in macros get redefined. This suppresses warnings for redefining __TIMESTAMP__, __TIME__, __DATE__, __FILE__, and __BASE_FILE__ 💜.
  • -Wstrict-prototypes (C and Objective-C only) — warns if a function is declared or defined without specifying the argument types. (An old-style function definition is fine with no warning if it's preceded by a declaration that specifies the argument types.) 🌸
  • -Wold-style-declaration (C and Objective-C only) — warns about obsolescent usages in a declaration per the C Standard. Like, warn if storage-class specifiers such as static aren't the first things in a declaration. Also enabled by -Wextra 💅.
  • -Wold-style-definition (C and Objective-C only) — warns if an old-style function definition gets used. You get the warning even if there's a previous prototype. A definition using () is NOT considered old-style in C2X mode (it's equivalent to (void) there), but it IS old-style for older standards 👀.
  • -Wmissing-parameter-type (C and Objective-C only) — a function parameter gets declared without a type specifier in K&R-style functions:
void foo(bar) { }

Also enabled by -Wextra 🎀.

  • -Wmissing-prototypes (C and Objective-C only) — warns if a global function is defined without a previous prototype declaration. Fires even if the definition itself provides a prototype. Use this to catch global functions that don't have a matching prototype declaration in a header file. NOT valid for C++ because all function declarations provide prototypes and a non-matching declaration declares an overload rather than conflicting with an earlier one. Use -Wmissing-declarations to detect missing declarations in C++ 💖.
  • -Wmissing-declarations — warns if a global function is defined without a previous declaration, even if the definition itself provides a prototype. Use it to catch global functions that aren't declared in header files. In C, no warnings for functions with previous non-prototype declarations — use -Wmissing-prototypes for those. In C++, no warnings for function templates, inline functions, or functions in anonymous namespaces ⭐.
  • -Wmissing-field-initializers — warns if a structure's initializer is missing some fields. For example, this code triggers it because x.h is implicitly zero:
struct s { int f, g, h; };
struct s x = { 3, 4 };

Doesn't warn about designated initializers, so this modification doesn't trigger anything:

struct s { int f, g, h; };
struct s x = { .f = 3, .g = 4 };

In C, this option doesn't warn about the universal zero initializer { 0 }:

struct s { int f, g, h; };
struct s x = { 0 };

Likewise, in C++ this option does not warn about the empty { } initializer — like, look:

struct s { int f, g, h; };
s x = { };

This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-missing-field-initializers 💅

  • -Wno-missing-requires — okay so by default the compiler warns you when a concept-id shows up as a C++20 simple-requirement, like:
bool satisfied = requires { C<T> };

Here satisfied will be true if C<T> is a valid expression — which, bestie, it is for all T 😭. Presumably you meant to write:

bool satisfied = requires { requires C<T> };

so satisfied is only true if concept C is satisfied for type T. This warning can be disabled with -Wno-missing-requires.

  • -Wno-missing-template-keyword — the member access tokens ., -> and :: must be followed by the template keyword if the parent object is dependent and the member being named is a template 👑
template <class X>
void DoStuff (X x)
{
  x.template DoSomeOtherStuff<X>(); // Good.
  x.DoMoreStuff<X>(); // Warning, x is dependent.
}

In rare cases it's possible to get false positives. To silence this, wrap the expression in parentheses. For example, the following is treated as a template, even where m and N are integers:

void NotATemplate (my_class t)
{
  int N = 5;

  bool test = t.m < N > (0); // Treated as a template.
  test = (t.m < N) > (0); // Same meaning, but not treated as a template.
}

This warning can be disabled with -Wno-missing-template-keyword.

  • -Wno-multichar — do not warn if a multicharacter constant ('FOOF') is used. Usually they indicate a typo in your code, because they have implementation-defined values and honestly should not be used in portable code 🙈
  • -Wnormalized=[none|id|nfc|nfkc] — in ISO C and ISO C++, two identifiers are different if they're different sequences of characters. But sometimes, when characters outside the basic ASCII character set are used, you can have two different character sequences that look the same 👀. To avoid confusion, the ISO 10646 standard sets out some normalization rules which, when applied, ensure that two sequences that look the same are turned into the same sequence. GCC can warn you if you're using identifiers that have not been normalized, and this option controls that warning.

There are four levels of warning supported by GCC. The default is -Wnormalized=nfc, which warns about any identifier that is not in the ISO 10646 "C" normalized form, NFC. NFC is the recommended form for most uses. It is equivalent to -Wnormalized.

Unfortunately, there are some characters allowed in identifiers by ISO C and ISO C++ that, when turned into NFC, are not allowed in identifiers. That is, there's no way to use these symbols in portable ISO C or C++ and have all your identifiers in NFC. -Wnormalized=id suppresses the warning for these characters. It is hoped that future versions of the standards involved will correct this, which is why this option is not the default 🫶

You can switch the warning off for all characters by writing -Wnormalized=none or -Wno-normalized. You should only do this if you're using some other normalization scheme (like "D"), because otherwise you can easily create bugs that are literally impossible to see 😭

Some characters in ISO 10646 have distinct meanings but look identical in some fonts or display methodologies, especially once formatting has been applied. For instance "\u207F", "SUPERSCRIPT LATIN SMALL LETTER N", displays just like a regular "n" that has been placed in a superscript. ISO 10646 defines the NFKC normalization scheme to convert all these into a standard form as well, and GCC warns if your code is not in NFKC if you use -Wnormalized=nfkc. This warning is comparable to warning about every identifier that contains the letter O because it might be confused with the digit 0, and so is not the default — but it may be useful as a local coding convention if the programming environment can't be fixed to display these characters distinctly ✨

  • -Wno-attribute-warning — do not warn about usage of functions declared with the "warning" attribute. By default, this warning is enabled. -Wno-attribute-warning can be used to disable the warning, or -Wno-error=attribute-warning can be used to disable the error when compiled with the -Werror flag 💖
  • -Wno-deprecated — do not warn about usage of deprecated features. simple as that 🎀
  • -Wno-deprecated-declarations — do not warn about uses of functions, variables, and types marked as deprecated by using the "deprecated" attribute.
  • -Wno-overflow — do not warn about compile-time overflow in constant expressions 🫠
  • -Wno-odr — warn about One Definition Rule violations during link-time optimization. Enabled by default, ngl.
  • -Wopenacc-parallelism — warn about potentially suboptimal choices related to OpenACC parallelism 🌈
  • -Wopenmp-simd — warn if the vectorizer cost model overrides the OpenMP simd directive set by the user. The -fsimd-cost-model=unlimited option can be used to relax the cost model 👑
  • -Woverride-init (C and Objective-C only) — warn if an initialized field without side effects is overridden when using designated initializers. This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-override-init.
  • -Wno-override-init-side-effects (C and Objective-C only) — do not warn if an initialized field with side effects is overridden when using designated initializers. This warning is enabled by default 💫
  • -Wpacked — warn if a structure is given the packed attribute, but the packed attribute has no effect on the layout or size of the structure. Such structures may be mis-aligned for little benefit 🙈. For instance, in this code, the variable f.x in struct bar is misaligned even though struct bar does not itself have the packed attribute:
struct foo {
  int x;
  char a, b, c, d;
} __attribute__((packed));
struct bar {
  char z;
  struct foo f;
};
  • -Wnopacked-bitfield-compat — the 4.1, 4.2 and 4.3 series of GCC ignore the "packed" attribute on bit-fields of type "char". This was fixed in GCC 4.4, but the change can lead to differences in the structure layout 😬. GCC informs you when the offset of such a field has changed in GCC 4.4. For example there is no longer a 4-bit padding between field a and b in this structure:
struct foo
{
  char a:4;
  char b:8;
} __attribute__ ((packed));

This warning is enabled by default. Use -Wno-packed-bitfield-compat to disable this warning.

  • -Wpacked-not-aligned (C, C++, Objective-C and Objective-C++ only) — warn if a structure field with explicitly specified alignment in a packed struct or union is misaligned. For example, a warning will be issued on struct S, like, warning: alignment 1 of 'struct S' is less than 8, in this code:
struct __attribute__ ((aligned (8))) S8 { char a[8]; };
struct __attribute__ ((packed)) S {
  struct S8 s8;
};

This warning is enabled by -Wall 🔥

  • -Wpadded — warn if padding is included in a structure, either to align an element of the structure or to align the whole structure. Sometimes when this happens it's possible to rearrange the fields of the structure to reduce the padding and so make the structure smaller 💅
  • -Wredundant-decls — warn if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing 💀
  • -Wrestrict — warn when an object referenced by a "restrict"-qualified parameter (or, in C++, a "__restrict"-qualified parameter) is aliased by another argument, or when copies between such objects overlap. For example, the call to the "strcpy" function below attempts to truncate the string by replacing its initial characters with the last four. However, because the call writes the terminating NUL into a[4], the copies overlap and the call is diagnosed 😭
void foo (void)
{
  char a[] = "abcd1234";
  strcpy (a, a + 4);
  ...
}

The -Wrestrict option detects some instances of simple overlap even without optimization but works best at -O2 and above. It is included in -Wall.

  • -Wnested-externs (C and Objective-C only) — warn if an "extern" declaration is encountered within a function. like, inside?? yeah 🙈
  • -Winline — warn if a function that is declared as inline cannot be inlined. Even with this option, the compiler does not warn about failures to inline functions declared in system headers.

The compiler uses a variety of heuristics to determine whether or not to inline a function. For example, the compiler takes into account the size of the function being inlined and the amount of inlining that has already been done in the current function. Therefore, seemingly insignificant changes in the source program can cause the warnings produced by -Winline to appear or disappear 🦋 (iconic chaotic behaviour, honestly)

  • -Winterference-size — warn about use of C++17 std::hardware_destructive_interference_size without specifying its value with --param destructive-interference-size. Also warn about questionable values for that option 👀

This variable is intended to be used for controlling class layout, to avoid false sharing in concurrent code:

struct independent_fields {
  alignas(std::hardware_destructive_interference_size) std::atomic<int> one;
  alignas(std::hardware_destructive_interference_size) std::atomic<int> two;
};

Here one and two are intended to be far enough apart that stores to one won't require accesses to the other to reload the cache line 🎀

okay so real talk, bestie: those two --param options, destructive-interference-size and constructive-interference-size, get set by default based on whatever -mtune you're running — usually it's the L1 cache line size for your particular target CPU, and sometimes it's a whole range if you're tuning for a generic target. 🌸 Which means: every translation unit that depends on ABI compatibility for using these variables has to be compiled with the same -mtune (or -mcpu). No mixing and matching, iykyk.

If ABI stability is important for you — like, say, the use is in a header for a library — you should probably not use the hardware interference size variables at all. Like, at all. 🙈 Alternatively, you can force a particular value with --param.

And if you're confident that your use of the variable does not affect ABI outside a single build of your project, you can turn off the warning with -Wno-interference-size. Slay, but be sure bestie. ✨

  • -Wint-in-bool-context — warns you about suspicious use of integer values where boolean values are expected 🫶 — like conditional expressions (?:) using non-boolean integer constants in boolean context, e.g. if (a <= b ? 2 : 3). Or left shifting of signed integers in boolean context, like for (a = 0; 1 << a; a++);. Same energy for all kinds of multiplications regardless of the data type. This warning is enabled by -Wall.
  • -Wno-int-to-pointer-cast — suppresses warnings from casts to pointer type of an integer of a different size. Heads up though: in C++, casting to a pointer type of smaller size is an error. Fr fr. Wint-to-pointer-cast is enabled by default.
  • -Wno-pointer-to-int-cast (C and Objective-C only) — suppresses warnings from casts from a pointer to an integer type of a different size.
  • -Winvalid-pch — warns if a precompiled header is found in the search path but cannot be used. RIP to that PCH 💀
  • -Wlong-long — warns if long long type is used. This is enabled by either -Wpedantic or -Wtraditional in ISO C90 and C++98 modes. To inhibit the warning messages, use -Wno-long-long.
  • -Wvariadic-macros — warns if variadic macros are used in ISO C90 mode, or if the GNU alternate syntax is used in ISO C99 mode. This is enabled by either -Wpedantic or -Wtraditional. To inhibit the warning messages, use -Wno-variadic-macros.
  • -Wno-varargs — do not warn upon questionable usage of the macros used to handle variable arguments like va_start. These warnings are enabled by default.
  • -Wvector-operation-performance — warns if a vector operation is not implemented via SIMD capabilities of the architecture. Mainly useful for the performance tuning, ngl. A vector operation can be implemented:
    • "piecewise" — the scalar operation is performed on every vector element
    • "in parallel" — the vector operation is implemented using scalars of wider type, which normally is more performance efficient 👑
    • "as a single scalar" — the vector fits into a scalar type
  • -Wvla — warns if a variable-length array is used in the code. And -Wno-vla prevents the -Wpedantic warning of the variable-length array.
  • -Wvla-larger-than=byte-size — if this option is used, the compiler warns for declarations of variable-length arrays whose size is either unbounded, or bounded by an argument that allows the array size to exceed byte-size bytes. This is similar to how -Walloca-larger-than=byte-size works, but with variable-length arrays. 🦋

Note that GCC may optimize small variable-length arrays of a known value into plain arrays, so this warning may not get triggered for such arrays. Not a bug, just vibes.

-Wvla-larger-than=PTRDIFF_MAX is enabled by default but is typically only effective when -ftree-vrp is active (default for -O2 and above).

See also -Walloca-larger-than=byte-size.

  • -Wno-vla-larger-than — disables -Wvla-larger-than= warnings. The option is equivalent to -Wvla-larger-than=SIZE_MAX or larger.
  • -Wvla-parameter — warns about redeclarations of functions involving arguments of Variable Length Array types of inconsistent kinds or forms, and enables the detection of out-of-bounds accesses to such parameters by warnings such as -Warray-bounds. 🔥

If the first function declaration uses the VLA form, the bound specified in the array is assumed to be the minimum number of elements expected to be provided in calls to the function and the maximum number of elements accessed by it. Failing to provide arguments of sufficient size or accessing more than the maximum number of elements may be diagnosed.

For example, the warning triggers for the following redeclarations because the first one allows an array of any size to be passed to f while the second one specifies that the array argument must have at least n elements. In addition, calling f with the associated VLA bound parameter in excess of the actual VLA bound triggers a warning as well.

        void f (int n, int[n]);
        void f (int, int[]);     // warning: argument 2 previously declared as a VLA

        void g (int n)
        {
            if (n > 4)
              return;
            int a[n];
            f (sizeof a, a);     // warning: access to a by f may be out of bounds
          ...
        }

-Wvla-parameter is included in -Wall. The -Warray-parameter option triggers warnings for similar problems involving ordinary array arguments.

  • -Wvolatile-register-var — warns if a register variable is declared volatile. Lowkey important: the volatile modifier does not inhibit all optimizations that may eliminate reads and/or writes to register variables. This warning is enabled by -Wall.
  • -Wdisabled-optimization — warns if a requested optimization pass is disabled. This warning does not generally indicate that there is anything wrong with your code — it merely indicates that GCC's optimizers are unable to handle the code effectively. Often, the problem is that your code is too big or too complex; GCC refuses to optimize programs when the optimization itself is likely to take inordinate amounts of time.
  • -Wpointer-sign (C and Objective-C only) — warns for pointer argument passing or assignment with different signedness. This option is only supported for C and Objective-C. It is implied by -Wall and by -Wpedantic, which can be disabled with -Wno-pointer-sign.
  • -Wstack-protector — this option is only active when -fstack-protector is active. It warns about functions that are not protected against stack smashing. 🛡️
  • -Woverlength-strings — warns about string constants that are longer than the "minimum maximum" length specified in the C standard. Modern compilers generally allow string constants that are much longer than the standard's minimum limit, but very portable programs should avoid using longer strings.

The limit applies after string constant concatenation, and does not count the trailing NUL. In C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 does not specify a normative minimum maximum, so we do not diagnose overlength strings in C++.

This option is implied by -Wpedantic, and can be disabled with -Wno-overlength-strings.

  • -Wunsuffixed-float-constants (C and Objective-C only) — issues a warning for any floating constant that does not have a suffix. When used together with -Wsystem-headers, it warns about such constants in system header files. This can be useful when preparing code to use with the FLOAT_CONST_DECIMAL64 pragma from the decimal floating-point extension to C99. 🍓
  • -Wno-lto-type-mismatch — during the link-time optimization, do not warn about type mismatches in global declarations from different compilation units. Requires -flto to be enabled. Enabled by default.
  • -Wno-designated-init (C and Objective-C only) — suppresses warnings when a positional initializer is used to initialize a structure that has been marked with the designated_init attribute.

🧪 Options That Control Static Analysis 🧪

  • -fanalyzer — this option enables a static analysis of program flow which looks for "interesting" interprocedural paths through the code, and issues warnings for problems found on them. 🔍

Girl, this analysis is much more expensive than other GCC warnings. Like, your compile times will feel it.

Enabling this option effectively enables the following warnings:

-Wanalyzer-double-fclose -Wanalyzer-double-free
-Wanalyzer-exposure-through-output-file -Wanalyzer-file-leak
-Wanalyzer-free-of-non-heap -Wanalyzer-malloc-leak
-Wanalyzer-mismatching-deallocation -Wanalyzer-null-argument
-Wanalyzer-null-dereference -Wanalyzer-possible-null-argument
-Wanalyzer-possible-null-dereference -Wanalyzer-shift-count-negative
-Wanalyzer-shift-count-overflow -Wanalyzer-stale-setjmp-buffer
-Wanalyzer-unsafe-call-within-signal-handler
-Wanalyzer-use-after-free
-Wanalyzer-use-of-pointer-in-stale-stack-frame
-Wanalyzer-use-of-uninitialized-value -Wanalyzer-write-to-const
-Wanalyzer-write-to-string-literal

This option is only available if GCC was configured with analyzer support enabled. No analyzer build, no analyzer slay, periodt.

  • -Wanalyzer-too-complex — if -fanalyzer is enabled, the analyzer uses various heuristics to attempt to explore the control flow and data flow in the program, but these can be defeated by sufficiently complicated code. 😭

By default, the analysis silently stops if the code is too complicated for the analyzer to fully explore and it reaches an internal limit. The -Wanalyzer-too-complex option warns if this occurs.

  • -Wno-analyzer-double-fclose — this warning requires -fanalyzer, which enables it; use -Wno-analyzer-double-fclose to disable it.

This diagnostic warns for paths through the code in which a FILE * can have fclose called on it more than once. We love a double-close disaster 💀

  • -Wno-analyzer-double-free — this warning requires -fanalyzer, which enables it; use -Wno-analyzer-double-free to disable it.

This diagnostic warns for paths through the code in which a pointer can have a deallocator called on it more than once, either free, or a deallocator referenced by attribute malloc.

  • -Wno-analyzer-exposure-through-output-file — this warning requires -fanalyzer, which enables it; use -Wno-analyzer-exposure-through-output-file to disable it.

This diagnostic warns for paths through the code in which a security-sensitive value is written to an output file (such as writing a password to a log file). 🙈 Bestie, do not log your passwords, I'm begging.

  • -Wno-analyzer-file-leak — bestie this one needs -fanalyzer, which enables it; use -Wno-analyzer-file-leak to turn it off.

It warns about paths through your code where a <stdio.h> FILE * stream object gets leaked. Like you opened the file, had a whole moment with it, and then just… never closed it. 🙈 Leaked.

  • -Wno-analyzer-free-of-non-heap — again, needs -fanalyzer to be on; -Wno-analyzer-free-of-non-heap disables it.

It flags paths where free gets called on a non-heap pointer — think an on-stack buffer, or a global. That's a yikes, not a slay. 💀

  • -Wno-analyzer-malloc-leak — requires -fanalyzer; use -Wno-analyzer-malloc-leak to disable.

Warns about paths where a pointer allocated via an allocator is leaked: either malloc, or any function marked with attribute malloc. You had one job (free it) and you said no. 😭

  • -Wno-analyzer-mismatching-deallocation — needs -fanalyzer; -Wno-analyzer-mismatching-deallocation turns it off.

This one's the fashion police of memory: it warns about paths where the wrong deallocation function is called on a pointer value, judged by which function allocated it. It'll call out mismatches between free, scalar delete and vector delete[], plus anything marked as allocator/deallocator pairs using attribute malloc. Mixing them is not the vibe. 🎀

  • -Wno-analyzer-possible-null-argument — requires -fanalyzer; disable with -Wno-analyzer-possible-null-argument.

Warns about paths where a possibly-NULL value gets passed into a function argument that's marked with __attribute__((nonnull)) as needing a non-NULL value. So it might be NULL and the function said "no NULLs allowed" — chaotic energy, honestly. ✨

  • -Wno-analyzer-possible-null-dereference — needs -fanalyzer; -Wno-analyzer-possible-null-dereference disables it.

Warns about paths where a possibly-NULL value gets dereferenced. Might be fine! Might be a segfault! The suspense is genuinely too much. 🫶

  • -Wno-analyzer-null-argument — requires -fanalyzer; turn it off with -Wno-analyzer-null-argument.

Same as above but the drama is confirmed: warns about paths where a value known to be NULL is passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. No maybes, it's just NULL, and it's going in anyway. 💀

  • -Wno-analyzer-null-dereference — needs -fanalyzer; -Wno-analyzer-null-dereference disables it.

Warns about paths where a value known to be NULL is dereferenced. Periodt. That pointer is empty and you're still knocking. 😭

  • -Wno-analyzer-shift-count-negative — requires -fanalyzer; disable with -Wno-analyzer-shift-count-negative.

Warns about paths where a shift is attempted with a negative count. (Shifting by -3? bestie where are you going. 🌀) It's analogous to the -Wshift-count-negative diagnostic implemented in the C/C++ front ends, but it's implemented based on analyzing interprocedural paths rather than merely parsing the syntax tree. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings. Ngl, it's lowkey not the analyzer's main character.

  • -Wno-analyzer-shift-count-overflow — requires -fanalyzer; -Wno-analyzer-shift-count-overflow turns it off.

Warns about paths where a shift is attempted with a count greater than or equal to the precision of the operand's type. It's analogous to the -Wshift-count-overflow diagnostic implemented in the C/C++ front ends, but again it's implemented based on analyzing interprocedural paths rather than merely parsing the syntax tree. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings. Same energy as above, different shift crime. 🌈

  • -Wno-analyzer-stale-setjmp-buffer — needs -fanalyzer; -Wno-analyzer-stale-setjmp-buffer disables it.

Warns about paths where longjmp is called to rewind to a jmp_buf relating to a setjmp call in a function that has returned.

Here's the lore: when setjmp is called on a jmp_buf to record a rewind location, it records the stack frame. That stack frame becomes invalid when the function containing the setjmp call returns. Trying to rewind to it via longjmp would reference a stack frame that no longer exists — and likely lead to a crash (or worse). This is not a cute look. 🚩

  • -Wno-analyzer-tainted-allocation-size — this one needs both -fanalyzer and -fanalyzer-checker=taint to enable it; use -Wno-analyzer-tainted-allocation-size to disable it.

Warns about paths where a value that could be under an attacker's control is used as the size of an allocation without being sanitized — so an attacker could inject an excessively large allocation and potentially cause a denial of service attack. 🚨

See @url{https://cwe.mitre.org/data/definitions/789.html, CWE-789: Memory Allocation with Excessive Size Value}.
  • -Wno-analyzer-tainted-array-index — needs both -fanalyzer and -fanalyzer-checker=taint; disable with -Wno-analyzer-tainted-array-index.

Warns about paths where a value that could be under an attacker's control is used as the index of an array access without being sanitized, so an attacker could inject an out-of-bounds access. Sneaking past the bounds like that is not it. 😤

See @url{https://cwe.mitre.org/data/definitions/129.html, CWE-129: Improper Validation of Array Index}.
  • -Wno-analyzer-tainted-divisor — needs both -fanalyzer and -fanalyzer-checker=taint; -Wno-analyzer-tainted-divisor disables it.

Warns about paths where a value that could be under an attacker's control is used as the divisor in a division or modulus operation without being sanitized, so an attacker could inject a division-by-zero. Math said no. 💅

  • -Wno-analyzer-tainted-offset — needs both -fanalyzer and -fanalyzer-checker=taint; use -Wno-analyzer-tainted-offset to disable it.

Warns about paths where a value that could be under an attacker's control is used as a pointer offset without being sanitized, so an attacker could inject an out-of-bounds access. Pointer said "sure, wherever" and that's the problem. 🦋

See @url{https://cwe.mitre.org/data/definitions/823.html, CWE-823: Use of Out-of-range Pointer Offset}.
  • -Wno-analyzer-tainted-size — needs both -fanalyzer and -fanalyzer-checker=taint; -Wno-analyzer-tainted-size disables it.

Warns about paths where a value that could be under an attacker's control is used as the size of an operation such as memset without being sanitized, so an attacker could inject an out-of-bounds access. Size matters and this size is compromised, bestie. 😭

  • -Wno-analyzer-unsafe-call-within-signal-handler — requires -fanalyzer; disable with -Wno-analyzer-unsafe-call-within-signal-handler.

Warns about paths where a function known to be async-signal-unsafe (such as fprintf) is called from a signal handler. Signal handlers are a vibe-check-only zone, keep it minimal. 🚫

  • -Wno-analyzer-use-after-free — needs -fanalyzer; -Wno-analyzer-use-after-free turns it off.

Warns about paths where a pointer is used after a deallocator is called on it: either free, or a deallocator referenced by attribute malloc. You let it go and then you went back. Moving on means moving on. 👋

  • -Wno-analyzer-use-of-pointer-in-stale-stack-frame — requires -fanalyzer; use -Wno-analyzer-use-of-pointer-in-stale-stack-frame to disable it.

Warns about paths where a pointer is dereferenced that points to a variable in a stale stack frame. That memory already left the group chat. 💀

  • -Wno-analyzer-write-to-const — needs -fanalyzer; -Wno-analyzer-write-to-const disables it.

Warns about paths where the analyzer detects an attempt to write through a pointer to a const object. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings. It said const. Const is const. 🔒

  • -Wno-analyzer-write-to-string-literal — requires -fanalyzer; disable with -Wno-analyzer-write-to-string-literal.

Warns about paths where the analyzer detects an attempt to write through a pointer to a string literal. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings. Do not write on the string literal. It is a display piece. 🎀

  • -Wno-analyzer-use-of-uninitialized-value — needs -fanalyzer; -Wno-analyzer-use-of-uninitialized-value turns it off.

Warns about paths where an uninitialized value is used. It's giving "who even are you" but for memory. 🌫️


Pertinent parameters for controlling the exploration are: --param analyzer-bb-explosion-factor=value, --param analyzer-max-enodes-per-program-point=value, --param analyzer-max-recursion-depth=value, and --param analyzer-min-snodes-for-call-summary=value. Save these, they're the levers. 🎛️

The following options control the analyzer.

  • -fanalyzer-call-summaries — simplifies interprocedural analysis by computing the effect of certain calls, rather than exploring all paths through the function from callsite to each possible return. Much less walking, same answer, honestly iconic. ✨

If enabled, call summaries are only used for functions with more than one call site, and that are sufficiently complicated (as per --param analyzer-min-snodes-for-call-summary=value). So the simple ones still get the full tour.

  • -fanalyzer-checker=name — restricts the analyzer to run just the named checker, and enables it. Pick your fighter. 🥊

Some checkers are disabled by default (even with -fanalyzer), such as the taint checker that implements -Wanalyzer-tainted-array-index, and this option is required to enable them. They're not being shy, they're just gated.

Note: currently, -fanalyzer-checker=taint disables the following warnings from -fanalyzer:
  • -Wanalyzer-double-fclose, -Wanalyzer-double-free, -Wanalyzer-exposure-through-output-file, -Wanalyzer-file-leak, -Wanalyzer-free-of-non-heap, -Wanalyzer-malloc-leak, -Wanalyzer-mismatching-deallocation, -Wanalyzer-null-argument, -Wanalyzer-null-dereference, -Wanalyzer-possible-null-argument, -Wanalyzer-possible-null-dereference, -Wanalyzer-unsafe-call-within-signal-handler, -Wanalyzer-use-after-free — the rest of the analyzer warning squad, all named exactly like that, no shortcuts 💅
  • -fno-analyzer-feasibility — okay so this one is literally just for analyzer developers, bestie. By default the analyzer checks that there's actually a feasible control flow path for every diagnostic it emits — meaning the conditions that hold aren't mutually exclusive. Any diagnostic where no feasible path can be found gets rejected. This filtering can be suppressed with -fno-analyzer-feasibility, for debugging issues in this code 🔍
  • -fanalyzer-fine-grained — again, analyzer developers only. Internally the analyzer builds an "exploded graph" that combines control flow graphs with data flow information. By default, an edge in this graph can contain the effects of a run of multiple statements within a basic block. With -fanalyzer-fine-grained, each statement gets its own edge ✨
  • -fanalyzer-show-duplicate-count — devs only, again: if multiple diagnostics are detected as being duplicates of each other, it emits a note when reporting the best diagnostic, giving the number of additional diagnostics that were suppressed by the deduplication logic 🫶
  • -fno-analyzer-state-merge — analyzer developers, you already know. By default the analyzer tries to simplify analysis by merging sufficiently similar states at each program point as it builds its "exploded graph". With -fno-analyzer-state-merge that merging can be suppressed, for debugging state-handling issues 💀
  • -fno-analyzer-state-purge — devs. By default the analyzer tries to simplify analysis by purging aspects of state at a program point that look like they're no longer relevant — e.g. the values of locals that aren't accessed later in the function and which aren't relevant to leak analysis. With -fno-analyzer-state-purge this purging can be suppressed, for debugging state-handling issues 🧹
  • -fanalyzer-transitivity — enables transitivity of constraints within the analyzer 🔥
  • -fanalyzer-verbose-edges — devs only. Enables more verbose, lower-level detail in the descriptions of control flow within diagnostic paths 👑
  • -fanalyzer-verbose-state-changes — devs only. Enables more verbose, lower-level detail in the descriptions of events relating to state machines within diagnostic paths 🌸
  • -fanalyzer-verbosity=level — controls how complex the control flow paths are that get emitted for analyzer diagnostics. The level can be one of:
    • 0 — at this level, interprocedural call and return events are displayed, along with the most pertinent state-change events relating to a diagnostic. For example, for a double-free diagnostic, both calls to free will be shown.
    • 1 — as per the previous level, but also show events for the entry to each function.
    • 2 — as per the previous level, but also show events relating to control flow that are significant to triggering the issue (e.g. "true path taken" at a conditional). This level is the default.
    • 3 — as per the previous level, but show all control flow events, not just significant ones.
    • 4 — this level is intended for analyzer developers; it adds various other events intended for debugging the analyzer.
  • -fdump-analyzer — dumps internal details about what the analyzer is doing to file.analyzer.txt. Lowkey overridden by -fdump-analyzer-stderr 📝
  • -fdump-analyzer-stderr — dumps internal details about what the analyzer is doing to stderr. This option overrides -fdump-analyzer 🌈
  • -fdump-analyzer-callgraph — dumps a representation of the call graph suitable for viewing with GraphViz to file.callgraph.dot 🦋
  • -fdump-analyzer-exploded-graph — dumps a representation of the "exploded graph" suitable for viewing with GraphViz to file.eg.dot. Nodes are color-coded based on state-machine states to emphasize state changes 💅
  • -fdump-analyzer-exploded-nodes — emits diagnostics showing where nodes in the "exploded graph" are in relation to the program source 📍
  • -fdump-analyzer-exploded-nodes-2 — dumps a textual representation of the "exploded graph" to file.eg.txt 💜
  • -fdump-analyzer-exploded-nodes-3 — dumps a textual representation of the "exploded graph" to one dump file per node, to file.eg-id.txt. Heads up: this is typically a large number of dump files 😭
  • -fdump-analyzer-exploded-paths — dumps a textual representation of the "exploded path" for each diagnostic to file.idx.kind.epath.txt 🎀
  • -fdump-analyzer-feasibility — dumps internal details about the analyzer's search for feasible paths. The details are written in a form suitable for viewing with GraphViz to filenames of the form file.*.fg.dot, file.*.tg.dot, and file.*.fpath.txt 🔍
  • -fdump-analyzer-json — dumps a compressed JSON representation of analyzer internals to file.analyzer.json.gz. The precise format is subject to change, so don't get too attached 🫶
  • -fdump-analyzer-state-purge — as per -fdump-analyzer-supergraph, dump a representation of the "supergraph" suitable for viewing with GraphViz, but annotate the graph with information on what state will be purged at each node. The graph is written to file.state-purge.dot 🧹
  • -fdump-analyzer-supergraph — dumps representations of the "supergraph" suitable for viewing with GraphViz to file.supergraph.dot and to file.supergraph-eg.dot. These show all of the control flow graphs in the program, with interprocedural edges for calls and returns. The second dump contains annotations showing nodes in the "exploded graph" and diagnostics associated with them 🌐
  • -fdump-analyzer-untracked — emits custom warnings with internal details intended for analyzer developers 🙈

🐛 Options for Debugging Your Program 🐛

Okay so real talk: to tell GCC to emit extra information for use by a debugger, in almost all cases you literally only need to add -g to your other options. Some debug formats can co-exist (like DWARF with CTF) when each of them is enabled explicitly by adding the respective command line option to your other options 💖

GCC allows you to use -g with -O. But ngl, the shortcuts taken by optimized code may occasionally be surprising 😭:

  • some variables you declared may not exist at all
  • flow of control may briefly move where you did not expect it
  • some statements may not be executed because they compute constant results or their values are already at hand
  • some statements may execute in different places because they have been moved out of loops

Nevertheless it is possible to debug optimized output. Which makes it reasonable to use the optimizer for programs that might have bugs 👑

If you're not using some other optimization option, consider using -Og with -g. With no -O option at all, some compiler passes that collect information useful for debugging don't run at all, so -Og may result in a better debugging experience ✨

  • -g — produce debugging information in the operating system's native format (stabs, COFF, XCOFF, or DWARF). GDB can work with this debugging information. On most systems that use stabs format, -g enables use of extra debugging information that only GDB can use; this extra information makes debugging work better in GDB but probably makes other debuggers crash or refuse to read the program 😬 If you want to control for certain whether to generate the extra information, use -gstabs+, -gstabs, -gxcoff+, -gxcoff, or -gvms (peep below).
  • -ggdb — produce debugging information for use by GDB. This means to use the most expressive format available (DWARF, stabs, or the native format if neither of those are supported), including GDB extensions if at all possible 💅
  • -gdwarf, -gdwarf-version — produce debugging information in DWARF format (if that is supported). The value of version may be either 2, 3, 4 or 5; the default version for most targets is 5 (with the exception of VxWorks, TPF and Darwin/Mac OS X, which default to version 2, and AIX, which defaults to version 4). Note that with DWARF Version 2, some ports require and always use some non-conflicting DWARF 3 extensions in the unwind tables 🌸 Version 4 may require GDB 7.0 and -fvar-tracking-assignments for maximum benefit. Version 5 requires GDB 8.0 or higher 🫶 GCC no longer supports DWARF Version 1, which is substantially different than Version 2 and later. For historical reasons, some other DWARF-related options such as -fno-dwarf2-cfi-asm) retain a reference to DWARF Version 2 in their names, but apply to all currently-supported versions of DWARF 💀
  • -gbtf — request BTF debug information. BTF is the default debugging format for the eBPF target. On other targets, like x86, BTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options 🌈
  • -gctf, -gctflevel — request CTF debug information and use level to specify how much CTF debug information should be produced. If -gctf is specified without a value for level, the default level of CTF debug information is 2. CTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options 🎀
    • Level 0 produces no CTF debug information at all. Thus, -gctf0 negates -gctf.
    • Level 1 produces CTF information for tracebacks only. This includes callsite information, but does not include type information.
    • Level 2 produces type information for entities (functions, data objects etc.) at file-scope or global-scope only 🦋
  • -gstabs — makes debugging info in the stabs format (if that's even supported on your target), without the GDB extensions. Bestie, this is the format DBX uses on most BSD systems. ⚠️ Heads up though: on MIPS, Alpha and System V Release 4 systems, this option produces stabs debugging output that DBX straight-up does not understand. And on System V Release 4 systems, this option requires the GNU assembler.
  • -gstabs+ — same stabs format (if supported), but now with GNU extensions that only the GNU debugger (GDB) understands. 💀 The use of these extensions is likely to make other debuggers crash or refuse to read the program, so like... choose your friends wisely.
  • -gxcoff — debugging info in XCOFF format (if supported). This is the format the DBX debugger uses on IBM RS/6000 systems.
  • -gxcoff+ — XCOFF format (if supported) but with GNU extensions that only GDB understands. Warning, bestie: the use of these extensions is likely to make other debuggers crash or refuse to read the program, and may cause assemblers other than the GNU assembler (GAS) to fail with an error. 😭
  • -gvms — debugging info in Alpha/VMS debug format (if supported). The format DEBUG uses on Alpha/VMS systems. Vintage vibes ✨.
  • -glevel, -ggdblevel, -gstabslevel, -gxcofflevel, -gvmslevel — request debugging information and use level to say how much info you want. The default level is 2. Here's the level lore:
    • Level 0 produces no debug information at all. So -g0 straight up negates -g. Iconic cancellation 🫶
    • Level 1 produces minimal information — enough for making backtraces in parts of the program you don't plan to debug. This includes descriptions of functions and external variables, and line number tables, but no information about local variables.
    • Level 3 includes extra information, such as all the macro definitions present in the program. Some debuggers support macro expansion when you use -g3.

If you use multiple -g options, with or without level numbers, the last such option is the one that is effective. Last one wins, periodt.

Also lowkey important: -gdwarf does not accept a concatenated debug level, to avoid confusion with -gdwarf-level. Instead use an additional -glevel option to change the debug level for DWARF.
  • -fno-eliminate-unused-debug-symbols — by default, no debug information is produced for symbols that are not actually used. Use this option if you want debug information for all symbols. Give me everything or give me nothing 💅
  • -femit-class-debug-always — instead of emitting debugging information for a C++ class in only one object file, emit it in all object files using the class. Use this only with debuggers that are unable to handle the way GCC normally emits debugging information for classes, because using this option increases the size of debugging information by as much as a factor of two. Yeah. Two whole times. 😭
  • -fno-merge-debug-strings — tells the linker not to merge together strings in the debugging information that are identical in different object files. Not all assemblers or linkers support merging anyway. Merging decreases the size of the debug information in the output file at the cost of increasing link processing time. Merging is enabled by default.
  • -fdebug-prefix-map=old=new — when compiling files residing in directory old, record debugging information describing them as if the files resided in directory new instead. You can use this to replace a build-time path with an install-time path in the debug info. It can also change an absolute path into a relative path by using . for new. This gives more reproducible builds which are location independent, but it may require an extra command to tell GDB where to find the source files. See also -ffile-prefix-map. 🎀
  • -fvar-tracking — runs the variable tracking pass. It computes where variables are stored at each position in code, and then better debugging information is generated (if the debugging information format supports this information).

It's enabled by default when compiling with optimization (-Os, -O, -O2, ...), debugging information (-g) and the debug info format supports it. The trifecta ✨

  • -fvar-tracking-assignments — annotates assignments to user variables early in the compilation and tries to carry those annotations over throughout the whole compilation, all the way to the end, in an attempt to improve debug information while optimizing. Using -gdwarf-4 along with it is recommended.

It can be enabled even if var-tracking is disabled — in that case the annotations are created and maintained, but discarded at the end. 🙈 By default this flag is enabled together with -fvar-tracking, except when selective scheduling is enabled.

  • -gsplit-dwarf — if DWARF debugging information is enabled, separate as much debugging information as possible into a separate output file with the extension .dwo. This option lets the build system avoid linking files with debug information. To be useful, this option requires a debugger capable of reading .dwo files. No reader, no vibes.
  • -gdwarf32, -gdwarf64 — if DWARF debugging information is enabled, -gdwarf32 selects the 32-bit DWARF format and -gdwarf64 selects the 64-bit DWARF format. The default is target specific; on most targets it's -gdwarf32 though. The 32-bit DWARF format is smaller but can't support more than 2GiB of debug information in any of the DWARF debug information sections. The 64-bit DWARF format allows larger debug information and might not be well supported by all consumers yet. Bleeding edge, handle with care 🦋
  • -gdescribe-dies — adds description attributes to some DWARF DIEs that have no name attribute, such as artificial variables, external references and call site parameter DIEs. Little name tags for the unnamed ones 🎀
  • -gpubnames — generates DWARF .debug_pubnames and .debug_pubtypes sections.
  • -ggnu-pubnames — generates .debug_pubnames and .debug_pubtypes sections in a format suitable for conversion into a GDB index. This option is only useful with a linker that can produce GDB index version 7. Very specific, very demure.
  • -fdebug-types-section — when using DWARF Version 4 or higher, type DIEs can be put into their own .debug_types section instead of making them part of the .debug_info section. Putting them in a separate comdat section is more efficient since the linker can then remove duplicates. But not all DWARF consumers support .debug_types sections yet, and on some objects .debug_types produces larger instead of smaller debugging information. Betrayal 😭
  • -grecord-gcc-switches, -gno-record-gcc-switches — this switch causes the command-line options used to invoke the compiler that may affect code generation to be appended to the DW_AT_producer attribute in DWARF debugging information. The options are concatenated with spaces separating them from each other and from the compiler version. It is enabled by default. See also -frecord-gcc-switches for another way of storing compiler options into the object file. Receipts, but for compiler flags 🧾
  • -gstrict-dwarf — disallows using extensions of later DWARF standard versions than the one selected with -gdwarf-version. On most targets, using non-conflicting DWARF extensions from later standard versions is allowed (so this is you being strict on purpose).
  • -gno-strict-dwarf — allows using extensions of later DWARF standard versions than the one selected with -gdwarf-version. Permission granted 💅
  • -gas-loc-support — informs the compiler that the assembler supports .loc directives. It may then use them for the assembler to generate DWARF2+ line number tables.

This is generally desirable, because assembler-generated line-number tables are a lot more compact than the ones the compiler can generate itself. This option is enabled by default if, at GCC configure time, the assembler was found to support such directives.

  • -gno-as-loc-support — forces GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are to be generated.
  • -gas-locview-support — informs the compiler that the assembler supports "view" assignment and reset assertion checking in .loc directives. This option is enabled by default if, at GCC configure time, the assembler was found to support them.
  • -gno-as-locview-support — forces GCC to assign view numbers internally, if -gvariable-location-views are explicitly requested.
  • -gcolumn-info, -gno-column-info — emit location column information into DWARF debugging information, rather than just file and line. Enabled by default. Column girlies stay winning 🫶
  • -gstatement-frontiers, -gno-statement-frontiers — this option causes GCC to create markers in the internal representation at the beginning of statements, and to keep them roughly in place throughout compilation, using them to guide the output of is_stmt markers in the line number table. This is enabled by default when compiling with optimization (-Os, -O1, -O2, ...), and outputting DWARF 2 debug information at the normal level.
  • -gvariable-location-views, -gvariable-location-views=incompat5, -gno-variable-location-views — augment variable location lists with progressive view numbers implied from the line number table. This enables debug information consumers to inspect state at certain points of the program, even if no instructions associated with the corresponding source locations are present at that point. If the assembler lacks support for view numbers in line number tables, this will cause the compiler to emit the line number table, which generally makes them somewhat less compact. The augmented line number tables and location lists are fully backward-compatible, so they can be consumed by debug information consumers that are not aware of these augmentations — but they won't derive any benefit from them either. Fair enough tbh.

This is enabled by default when outputting DWARF 2 debug information at the normal level, as long as there is assembler support, -fvar-tracking-assignments is enabled and -gstrict-dwarf is not.

Real talk though: when assembler support is not available, this may still be enabled, but it will force GCC to output internal line number tables, and if -ginternal-reset-location-views is not enabled, that will most certainly lead to silently mismatching location views. Silently!! The worst kind of mismatching 😭💀

There's a proposed representation for view numbers that is not backward compatible with the location list format introduced in DWARF 5, and you can turn it on with -gvariable-location-views=incompat5. Heads up bestie: this option may be removed in the future — it's only there as a reference implementation of the proposed representation. Debug information consumers are not expected to support this extended format, and they'd literally be rendered unable to decode location lists using it. 😭

  • -ginternal-reset-location-views, -gno-internal-reset-location-views — tries to figure out which location views can be left out of location view lists. This needs the compiler to have very accurate insn length estimates, which isn't always the case, and it may cause incorrect view lists to be generated silently when you're using an assembler that doesn't support location view lists. The GNU assembler will flag any such error as a "view number mismatch". This is only enabled on ports that define a reliable estimation function. 🎀
  • -ginline-points, -gno-inline-points — generates extended debug info for inlined functions. Location view tracking markers get inserted at inlined entry points, so address and view numbers can be computed and output in debug info. You can enable this independently of location views — in which case the view numbers won't be output — but it can only be enabled along with statement frontiers, and it's only enabled by default if location views are enabled. ✨
  • -gz[=type] — produce compressed debug sections in DWARF format, if that's supported. If type isn't given, the default depends on the capabilities of the assembler and linker you're using. type can be one of none (don't compress debug sections, ty), zlib (use zlib compression in ELF gABI format), or zlib-gnu (use zlib compression in traditional GNU format). If the linker doesn't support writing compressed debug sections, the option is rejected. Otherwise, if the assembler doesn't support them, -gz is silently ignored when producing object files. 🦋
  • -femit-struct-debug-baseonly — emit debug info for struct-like types only when the base name of the compilation source file matches the base name of the file in which the struct is defined.

This option substantially reduces the size of debugging information, but at significant potential loss in type information to the debugger. See -femit-struct-debug-reduced for a less aggressive option. See -femit-struct-debug-detailed for more detailed control.

This option works only with DWARF debug output.

  • -femit-struct-debug-reduced — emit debug info for struct-like types only when the base name of the compilation source file matches the base name of the file in which the type is defined, unless the struct is a template or defined in a system header.

This option significantly reduces the size of debugging information, with some potential loss in type information to the debugger. See -femit-struct-debug-baseonly for a more aggressive option. See -femit-struct-debug-detailed for more detailed control.

This option works only with DWARF debug output.

  • -femit-struct-debug-detailed[=spec-list] — specify the struct-like types for which the compiler generates debug info. The whole point is to reduce duplicate struct debug info between different object files within the same program. 👑

This option is a detailed version of -femit-struct-debug-reduced and -femit-struct-debug-baseonly, which serves for most needs.

A spec has the syntax:

[dir:|ind:][ord:|gen:](any|sys|base|none)

The optional first word limits the specification to structs that are used directly (dir:) or used indirectly (ind:). A struct type is used directly when it's the type of a variable, member. Indirect uses arise through pointers to structs. That is, when use of an incomplete struct is valid, the use is indirect. An example is struct one direct; struct two * indirect;.

The optional second word limits the spec to ordinary structs (ord:) or generic structs (gen:). Generic structs are a bit complicated to explain — for C++, these are non-explicit specializations of template classes, or non-template classes within the above. Other programming languages have generics, but -femit-struct-debug-detailed does not yet implement them.

The third word specifies the source files for those structs for which the compiler should emit debug info. The values none and any have the normal meaning. The value base means the base of name of the file in which the type declaration appears must match the base of the name of the main compilation file. In practice that means when compiling foo.c, debug info is generated for types declared in that file and foo.h, but not other header files. The value sys means those types satisfying base or declared in system or compiler headers.

You may need to experiment to determine the best settings for your application. ngl, trial and error is the vibe here.

The default is -femit-struct-debug-detailed=all.

This option works only with DWARF debug output.

  • -fno-dwarf2-cfi-asm — emit DWARF unwind info as a compiler-generated ".eh_frame" section instead of using GAS ".cfi_*" directives. 🧚
  • -fno-eliminate-unused-debug-types — normally, when producing DWARF output, GCC avoids producing debug symbol output for types that are nowhere used in the source file being compiled. Sometimes it's useful to have GCC emit debugging info for all types declared in a compilation unit, regardless of whether they're actually used in it — like, say, if you want to cast a value in the debugger to a type that isn't actually used in your program (but is declared). More often, though, this results in a significant amount of wasted space. 🫶

⚡ Options That Control Optimization ⚡

These options control various sorts of optimizations. This is where it gets fun, bestie. 🔥

Without any optimization option, the compiler's goal is to reduce the cost of compilation and to make debugging produce the expected results. Statements are independent: if you stop the program with a breakpoint between statements, you can then assign a new value to any variable or change the program counter to any other statement in the function and get exactly the results you expect from the source code.

Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program. it's giving tradeoffs 💅

The compiler performs optimization based on the knowledge it has of the program. Compiling multiple files at once to a single output file mode allows the compiler to use information gained from all of the files when compiling each of them.

Not all optimizations are controlled directly by a flag. Only optimizations that have a flag are listed in this section.

Most optimizations are completely disabled at -O0 or if an -O level isn't set on the command line, even if individual optimization flags are specified. Similarly, -Og suppresses many optimization passes. 🙈

Depending on the target and how GCC was configured, a slightly different set of optimizations may be enabled at each -O level than those listed here. You can invoke GCC with -Q --help=optimizers to find out the exact set of optimizations that are enabled at each level.

  • -O, -O1 — Optimize. Optimizing compilation takes somewhat more time, and a lot more memory for a large function.

With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.

-O turns on the following optimization flags:

-fauto-inc-dec -fbranch-count-reg -fcombine-stack-adjustments
-fcompare-elim -fcprop-registers -fdce -fdefer-pop -fdelayed-branch
-fdse -fforward-propagate -fguess-branch-probability -fif-conversion
-fif-conversion2 -finline-functions-called-once -fipa-modref
-fipa-profile -fipa-pure-const -fipa-reference
-fipa-reference-addressable -fmerge-constants -fmove-loop-invariants
-fmove-loop-stores -fomit-frame-pointer -freorder-blocks
-fshrink-wrap -fshrink-wrap-separate -fsplit-wide-types
-fssa-backprop -fssa-phiopt -ftree-bit-ccp -ftree-ccp -ftree-ch
-ftree-coalesce-vars -ftree-copy-prop -ftree-dce
-ftree-dominator-opts -ftree-dse -ftree-forwprop -ftree-fre
-ftree-phiprop -ftree-pta -ftree-scev-cprop -ftree-sink -ftree-slsr
-ftree-sra -ftree-ter -funit-at-a-time
  • -O2 — Optimize even more. GCC performs nearly all supported optimizations that don't involve a space-speed tradeoff. As compared to -O, this option increases both compilation time and the performance of the generated code. slay 💅

-O2 turns on all optimization flags specified by -O1. It also turns on the following optimization flags:

-falign-functions  -falign-jumps -falign-labels  -falign-loops
-fcaller-saves -fcode-hoisting -fcrossjumping -fcse-follow-jumps
-fcse-skip-blocks -fdelete-null-pointer-checks -fdevirtualize
-fdevirtualize-speculatively -fexpensive-optimizations
-ffinite-loops -fgcse  -fgcse-lm -fhoist-adjacent-loads
-finline-functions -finline-small-functions -findirect-inlining
-fipa-bit-cp  -fipa-cp  -fipa-icf -fipa-ra  -fipa-sra  -fipa-vrp
-fisolate-erroneous-paths-dereference -flra-remat
-foptimize-sibling-calls -foptimize-strlen -fpartial-inlining
-fpeephole2 -freorder-blocks-algorithm=stc
-freorder-blocks-and-partition  -freorder-functions
-frerun-cse-after-loop -fschedule-insns  -fschedule-insns2
-fsched-interblock  -fsched-spec -fstore-merging -fstrict-aliasing
-fthread-jumps -ftree-builtin-call-dce -ftree-loop-vectorize
-ftree-pre -ftree-slp-vectorize -ftree-switch-conversion
-ftree-tail-merge -ftree-vrp -fvect-cost-model=very-cheap
Please note the warning under -fgcse about invoking -O2 on programs that use computed gotos. ⚠️
  • -O3 — Optimize yet more. -O3 turns on all optimizations specified by -O2 and also turns on the following optimization flags:
-fgcse-after-reload -fipa-cp-clone -floop-interchange
-floop-unroll-and-jam -fpeel-loops -fpredictive-commoning
-fsplit-loops -fsplit-paths -ftree-loop-distribution
-ftree-partial-pre -funswitch-loops -fvect-cost-model=dynamic
-fversion-loops-for-strides
  • -O0 — Reduce compilation time and make debugging produce the expected results. This is the default. 🎀
  • -Os — optimize for size 🎀. Lowkey this turns on all the -O2 optimizations except the ones that usually bloat your code:
-falign-functions  -falign-jumps -falign-labels  -falign-loops
-fprefetch-loop-arrays  -freorder-blocks-algorithm=stc

It also enables -finline-functions, makes the compiler tune for code size instead of execution speed, and runs some extra optimizations that are literally designed to shrink your code. Slay, tiny binary 💅

  • -Ofast — bestie, this one just disregards strict standards compliance. -Ofast enables all -O3 optimizations, plus optimizations that are not valid for all standard-compliant programs. Specifically it turns on -ffast-math, -fallow-store-data-races and the Fortran-specific -fstack-arrays (unless -fmax-stack-var-size is specified), and -fno-protect-parens. It turns off -fsemantic-interposition. So yeah — fast, but it's giving "rules are more of a suggestion" energy 🙈
  • -Og — optimize the debugging experience 🐛. -Og should be your go-to optimization level for the standard edit-compile-debug cycle — it gives you a reasonable level of optimization while keeping compilation fast and the debugging experience good. It's a better choice than -O0 for producing debuggable code, because some compiler passes that collect debug information are disabled at -O0.

Like -O0, -Og completely disables a number of optimization passes, so the individual options controlling them have no effect. Otherwise, -Og enables all -O1 optimization flags except the ones that might interfere with debugging:

-fbranch-count-reg  -fdelayed-branch -fdse  -fif-conversion
-fif-conversion2 -finline-functions-called-once
-fmove-loop-invariants  -fmove-loop-stores  -fssa-phiopt
-ftree-bit-ccp  -ftree-dse  -ftree-pta  -ftree-sra
  • -Oz — optimize aggressively for size rather than speed 🧚. Heads up: this may increase the number of instructions executed if those instructions need fewer bytes to encode. -Oz behaves similarly to -Os, including enabling most -O2 optimizations.
If you use multiple -O options, with or without level numbers, the last such option is the one that's effective. Last one wins, periodt 👑

Options of the form -fflag specify machine-independent flags. Most flags have both a positive and a negative form; the negative form of -ffoo is -fno-foo. In the table below, only one of the forms is listed — the one you typically use. You can figure out the other form by either removing no- or adding it. iykyk 💖

The following options control specific optimizations. They're either activated by -O options or related to ones that are. You can use the following flags in the rare cases when you actually want to "fine-tune" the optimizations being performed. Fancy ✨

  • -fno-defer-pop — for machines that have to pop arguments after a function call, always pop the arguments as soon as each function returns. At levels -O1 and higher, -fdefer-pop is the default; that lets the compiler let arguments accumulate on the stack for several function calls and pop them all at once. Efficiency 💅
  • -fforward-propagate — performs a forward propagation pass on RTL. The pass tries to combine two instructions and checks if the result can be simplified. If loop unrolling is active, two passes are performed and the second is scheduled after loop unrolling.

This option is enabled by default at optimization levels -O1, -O2, -O3, -Os.

  • *-ffp-contract=style* — floating-point expression contraction, your honour 🌸:
    • -ffp-contract=off disables floating-point expression contraction.
    • -ffp-contract=fast enables floating-point expression contraction, like forming fused multiply-add operations if the target has native support for them.
    • -ffp-contract=on enables floating-point expression contraction if the language standard allows it. This is currently not implemented and treated equal to -ffp-contract=off.

The default is -ffp-contract=fast.

  • -fomit-frame-pointer — omit the frame pointer in functions that don't need one. This avoids the instructions to save, set up and restore the frame pointer; on many targets it also makes an extra register available. Free real estate 🔥

On some targets this flag has no effect, because the standard calling sequence always uses a frame pointer, so it can't be omitted.

Note that -fno-omit-frame-pointer doesn't guarantee the frame pointer is used in all functions. Several targets always omit the frame pointer in leaf functions.

Enabled by default at -O1 and higher.

  • -foptimize-sibling-calls — optimize sibling and tail recursive calls. Enabled at levels -O2, -O3, -Os.
  • -foptimize-strlen — optimize various standard C string functions (e.g. strlen, strchr or strcpy) and their _FORTIFY_SOURCE counterparts into faster alternatives. Enabled at levels -O2, -O3. Glow-up for your strings ✨
  • -fno-inline — do not expand any functions inline apart from those marked with the always_inline attribute. This is the default when not optimizing.

Single functions can be exempted from inlining by marking them with the noinline attribute. Not you, bestie 🫶

  • -finline-small-functions — integrate functions into their callers when their body is smaller than the expected function call code (so the overall size of the program gets smaller). The compiler heuristically decides which functions are simple enough to be worth integrating this way. This inlining applies to all functions, even those not declared inline.

Enabled at levels -O2, -O3, -Os.

  • -findirect-inlining — inline also indirect calls that are discovered to be known at compile time thanks to previous inlining. This option only has any effect when inlining itself is turned on by the -finline-functions or -finline-small-functions options.

Enabled at levels -O2, -O3, -Os.

  • -finline-functions — consider all functions for inlining, even if they're not declared inline. The compiler heuristically decides which functions are worth integrating this way.

If all calls to a given function are integrated, and the function is declared static, then the function is normally not output as assembler code in its own right.

Enabled at levels -O2, -O3, -Os. Also enabled by -fprofile-use and -fauto-profile.

  • -finline-functions-called-once — consider all static functions called once for inlining into their caller even if they're not marked inline. If a call to a given function is integrated, then the function is not output as assembler code in its own right.

Enabled at levels -O1, -O2, -O3 and -Os, but not -Og.

  • -fearly-inlining — inline functions marked by always_inline, and functions whose body seems smaller than the function call overhead, early — before doing -fprofile-generate instrumentation and the real inlining pass. Doing this makes profiling significantly cheaper and usually makes inlining faster on programs with large chains of nested wrapper functions.

Enabled by default. Early bird gets the inline 💫

  • -fipa-sra — perform interprocedural scalar replacement of aggregates, removal of unused parameters, and replacement of parameters passed by reference with parameters passed by value. Enabled at levels -O2, -O3 and -Os.
  • *-finline-limit=n* — by default, GCC limits the size of functions that can be inlined. This flag lets you do coarse control of that limit. n is the size of functions that can be inlined, in number of pseudo instructions.

Inlining is actually controlled by a number of parameters, which can be specified individually using --param name=value. The -finline-limit=n option sets some of these parameters like this:

  • max-inline-insns-single — is set to n/2.
  • max-inline-insns-auto — is set to n/2.

See below for documentation of the individual parameters controlling inlining and for the defaults of these parameters.

Note: there may be no value of -finline-limit that results in default behavior.
Note: "pseudo instruction" represents, in this particular context, an abstract measurement of a function's size. In no way does it represent a count of assembly instructions, and as such its exact meaning might change from one release to another. So don't @ me 😭
  • -fno-keep-inline-dllexport — this is a more fine-grained version of -fkeep-inline-functions, which applies only to functions that are declared using the dllexport attribute or declspec.
  • -fkeep-inline-functions — in C, emit static functions that are declared inline into the object file, even if the function has been inlined into all of its callers. This switch does not affect functions using the extern inline extension in GNU C90. In C++, emit any and all inline functions into the object file.
  • -fkeep-static-functions — emit static functions into the object file, even if the function is never used. Iconic hoarder behavior 💀
  • -fkeep-static-consts — emit variables declared static const when optimization isn't turned on, even if the variables aren't referenced.

GCC enables this option by default. If you want to force the compiler to check whether a variable is referenced, regardless of whether or not optimization is turned on, use the -fno-keep-static-consts option.

  • -fmerge-constants — attempt to merge identical constants (string constants and floating-point constants) across compilation units.

This option is the default for optimized compilation if the assembler and linker support it. Use -fno-merge-constants to inhibit this behavior.

Enabled at levels -O1, -O2, -O3, -Os.

  • -fmerge-all-constants — attempt to merge identical constants and identical variables.

This option implies -fmerge-constants. In addition to -fmerge-constants, this considers e.g. even constant initialized arrays or initialized constant variables with integral or floating-point types. Languages like C or C++ require each variable — including multiple instances of the same variable in recursive calls — to have distinct locations, so using this option results in non-conforming behavior. You've been warned, bestie ⚠️

  • -fmodulo-sched — perform swing modulo scheduling immediately before the first scheduling pass. This pass looks at innermost loops and reorders their instructions by overlapping different iterations. Loops but make it fashion 🌈
  • -fmodulo-sched-allow-regmoves — perform more aggressive SMS-based modulo scheduling with register moves allowed. By setting this flag, certain anti-dependence edges are deleted, which triggers the generation of reg-moves based on the life-range analysis. This option is effective only with -fmodulo-sched enabled.
  • -fno-branch-count-reg — turns off the optimization pass that goes hunting for chances to use "decrement and branch" instructions on a count register, instead of the whole boring sequence of decrement a register, compare it against zero, then branch based on the result. Ngl this option only even means anything on architectures that actually have those instructions, and the roster is: x86, PowerPC, IA-64 and S/390 💅

⚠️ Head up bestie — -fno-branch-count-reg does not remove the decrement and branch instructions already sitting in the generated instruction stream that got introduced by other optimization passes. It's not a deep clean, it's just not adding more.

The default is -fbranch-count-reg at -O1 and higher, except for -Og 🎀

  • -fno-function-cse — do not put function addresses in registers, periodt. Every single instruction that calls a constant function gets the function's address containing explicitly in it.

It's giving less efficient code, yeah 😭 — but some strange hacks that alter the assembler output may get straight-up confused by the optimizations that happen when you don't pass this option.

The default is -ffunction-cse ✨

  • -fno-zero-initialized-in-bss — okay so if the target supports a BSS section, GCC by default shoves variables that are initialized to zero into BSS. Free space savings in the resulting code, slay 💖

This option turns that behavior off, because some programs explicitly rely on variables going to the data section — e.g., so that the resulting executable can find the beginning of that section and/or make assumptions based on that. They're built different, lowkey 🙈

The default is -fzero-initialized-in-bss.

  • -fthread-jumps — performs optimizations that check whether a jump branches to a location where another comparison subsumed by the first is found. If it is, the first branch gets redirected to either the destination of the second branch or a point immediately following it, depending on whether the condition is known to be true or false. Main character energy for real 👑

Enabled at levels -O1, -O2, -O3, -Os.

  • -fsplit-wide-types — when you're using a type that occupies multiple registers — think long long on a 32-bit system — this splits the registers apart and allocates them independently. Normally this generates better code for those types, but it may make debugging more difficult (the tradeoff is real 😔).

Enabled at levels -O1, -O2, -O3, -Os.

  • -fsplit-wide-types-early — fully split wide types early, instead of very late. Not me showing up first for once 💅 This option has no effect unless -fsplit-wide-types is turned on.

This is the default on some targets.

  • -fcse-follow-jumps — in common subexpression elimination (CSE), scan through jump instructions when the target of the jump isn't reached by any other path. For example, when CSE encounters an if statement with an else clause, CSE follows the jump when the condition tested is false. It's literally following the vibes 🦋

Enabled at levels -O2, -O3, -Os.

  • -fcse-skip-blocks — similar to -fcse-follow-jumps, but this one causes CSE to follow jumps that conditionally skip over blocks. When CSE encounters a simple if statement with no else clause, -fcse-skip-blocks causes CSE to follow the jump around the body of the if. Same energy, different little path ✨

Enabled at levels -O2, -O3, -Os.

  • -frerun-cse-after-loop — re-run common subexpression elimination after loop optimizations are performed. Like, we're going again, because the first pass didn't see everything 🔁

Enabled at levels -O2, -O3, -Os.

  • -fgcse — performs a global common subexpression elimination pass. This pass also performs global constant and copy propagation. Highkey doing the most 💖
Note: when compiling a program using computed gotos — a GCC extension — you may get better run-time performance if you disable the global common subexpression elimination pass by adding -fno-gcse to the command line.

Enabled at levels -O2, -O3, -Os.

  • -fgcse-lm — when -fgcse-lm is enabled, global common subexpression elimination attempts to move loads that are only killed by stores into themselves. This allows a loop containing a load/store sequence to be changed to a load outside the loop, and a copy/store within the loop. Moving things out of the loop, iconic behavior 👑

Enabled by default when -fgcse is enabled.

  • -fgcse-sm — when -fgcse-sm is enabled, a store motion pass is run after global common subexpression elimination. This pass attempts to move stores out of loops. When used in conjunction with -fgcse-lm, loops containing a load/store sequence can be changed to a load before the loop and a store after the loop. Bestie duo fr fr 🫶

Not enabled at any optimization level.

  • -fgcse-las — when -fgcse-las is enabled, the global common subexpression elimination pass eliminates redundant loads that come after stores to the same memory location (both partial and full redundancies). Redundancy? Not on her watch 💀

Not enabled at any optimization level.

  • -fgcse-after-reload — when -fgcse-after-reload is enabled, a redundant load elimination pass is performed after reload. The purpose of this pass is to clean up redundant spilling. It's giving cleanup era 🧹

Enabled by -O3, -fprofile-use and -fauto-profile.

  • -faggressive-loop-optimizations — this option tells the loop optimizer to use language constraints to derive bounds for the number of iterations of a loop. This assumes that loop code does not invoke undefined behavior by, for example, causing signed integer overflows or out-of-bound array accesses. The bounds for the number of iterations of a loop are used to guide loop unrolling and peeling and loop exit test optimizations.
⚠️ Note that assumption though — it's assuming no undefined behavior. If your loop code does invoke it (signed integer overflows, out-of-bound array accesses), you're in undefined-behavior territory and it is not cute.

This option is enabled by default.

  • -funconstrained-commons — this option tells the compiler that variables declared in common blocks (e.g. Fortran) may later be overridden with longer trailing arrays. This prevents certain optimizations that depend on knowing the array bounds. Can't optimize what you can't pin down 🤷‍♀️
  • -fcrossjumping — performs cross-jumping transformation. This transformation unifies equivalent code and saves code size. The resulting code may or may not perform better than without cross-jumping — no promises, we're just here for the code size glow-up 💅

Enabled at levels -O2, -O3, -Os.

  • -fauto-inc-dec — combines increments or decrements of addresses with memory accesses. This pass is always skipped on architectures that do not have instructions to support this. Enabled by default at -O1 and higher on architectures that support this. iykyk 🎀
  • -fdce — performs dead code elimination (DCE) on RTL. Enabled by default at -O1 and higher. Dead code? Gone. Not invited 💀
  • -fdse — performs dead store elimination (DSE) on RTL. Enabled by default at -O1 and higher. Same energy, but for stores 🦋
  • -fif-conversion — attempt to transform conditional jumps into branch-less equivalents. This includes use of conditional moves, min, max, set flags and abs instructions, and some tricks doable by standard arithmetics. The use of conditional execution on chips where it is available is controlled by -fif-conversion2. Branchless era 🔥

Enabled at levels -O1, -O2, -O3, -Os, but not with -Og.

  • -fif-conversion2 — use conditional execution (where available) to transform conditional jumps into branch-less equivalents.

Enabled at levels -O1, -O2, -O3, -Os, but not with -Og.

  • -fdeclone-ctor-dtor — the C++ ABI requires multiple entry points for constructors and destructors: one for a base subobject, one for a complete object, and one for a virtual destructor that calls operator delete afterwards. For a hierarchy with virtual bases, the base and complete variants are clones, which means two copies of the function. With this option, the base and complete variants are changed to be thunks that call a common implementation. Deduplicating the whole friend group, periodt 👑

Enabled by -Os.

  • -fdelete-null-pointer-checks — assume that programs cannot safely dereference null pointers, and that no code or data element resides at address zero. This option enables simple constant folding optimizations at all optimization levels. In addition, other optimization passes in GCC use this flag to control global dataflow analyses that eliminate useless checks for null pointers; these assume that a memory access to address zero always results in a trap, so that if a pointer is checked after it has already been dereferenced, it cannot be null. Very confident, very slay ✨
⚠️ Note however that in some environments this assumption is not true. Use -fno-delete-null-pointer-checks to disable this optimization for programs that depend on that behavior.

This option is enabled by default on most targets. On Nios II ELF, it defaults to off. On AVR, CR16, and MSP430, this option is completely disabled.

Passes that use the dataflow information are enabled independently at different optimization levels.

  • -fdevirtualize — attempt to convert calls to virtual functions to direct calls. This is done both within a procedure and interprocedurally as part of indirect inlining (-findirect-inlining) and interprocedural constant propagation (-fipa-cp). Cutting out the middleman 💅

Enabled at levels -O2, -O3, -Os.

  • -fdevirtualize-speculatively — attempt to convert calls to virtual functions to speculative direct calls. Based on the analysis of the type inheritance graph, determine for a given call the set of likely targets. If the set is small, preferably of size 1, change the call into a conditional deciding between direct and indirect calls. The speculative calls enable more optimizations, such as inlining. When they seem useless after further optimization, they are converted back into original form. Manifesting the target 🕯️
  • -fdevirtualize-at-ltrans — stream extra information needed for aggressive devirtualization when running the link-time optimizer in local transformation mode. This option enables more devirtualization but significantly increases the size of streamed data. For this reason it is disabled by default. Bigger data, better devirtualization — pick your struggle 😭
  • -fexpensive-optimizations — perform a number of minor optimizations that are relatively expensive. Minor but pricey, the little splurge 💸

Enabled at levels -O2, -O3, -Os.

  • -free — attempt to remove redundant extension instructions. This is especially helpful for the x86-64 architecture, which implicitly zero-extends in 64-bit registers after writing to their lower 32-bit half. Recycling, but make it compiler 🍓

Enabled for Alpha, AArch64 and x86 at levels -O2, -O3, -Os.

  • -fno-lifetime-dse — okay so in C++, an object's value only gets affected by stuff that happens inside its lifetime, periodt. When the constructor begins the object has an indeterminate value, and any changes made during the lifetime are dead the moment the object is destroyed. Normally dead store elimination eats that up (slay), but if your code is lowkey relying on the object's storage value persisting past the lifetime of the object, use this flag to turn that optimization off 💅. If you want to preserve stores made before the constructor starts (like, say, because your operator new clears the object storage) but still treat the object as dead after the destructor, hit up -flifetime-dse=1. The default behavior can be explicitly selected with -lifetime-dse=2. And -flifetime-dse=0 is literally equivalent to -fno-lifetime-dse.
  • -flive-range-shrinkage — try to decrease register pressure via register live range shrinkage ✨. It's giving helpful-for-fast-processors-with-small-or-moderate-size-register-sets, ngl.
  • *-fira-algorithm=algorithm* — use the specified coloring algorithm for the integrated register allocator 🎨. The algorithm argument can be priority, which specifies Chow's priority coloring, or CB, which specifies Chaitin-Briggs coloring. Chaitin-Briggs coloring is not implemented for all architectures bestie 😭, but for the targets that do support it, it's the default because it generates better code. Iconic behavior.
  • *-fira-region=region* — use specified regions for the integrated register allocator. The region argument should be one of these:
    • all — use all loops as register allocation regions. This can give the best results for machines with a small and/or irregular register set 👑.
    • mixed — use all loops except for loops with small register pressure as the regions. This value usually gives the best results in most cases and for most architectures, and it's enabled by default when compiling with optimization for speed (-O, -O2, ...). Main character value fr.
    • one — use all functions as a single region. This typically results in the smallest code size, and it's enabled by default for -Os or -O0.
  • -fira-hoist-pressure — use IRA to evaluate register pressure in the code hoisting pass for decisions to hoist expressions 🦋. This option usually results in smaller code, but it can slow the compiler down ngl. This option is enabled at level -Os for all targets.
  • -fira-loop-pressure — use IRA to evaluate register pressure in loops for decisions to move loop invariants 🔥. This one usually results in generation of faster and smaller code on machines with large register files (>= 32 registers), but it can slow the compiler down. It's enabled at level -O3 for some targets.
  • -fno-ira-share-save-slots — disable sharing of stack slots used for saving call-used hard registers living through a call 💀. Each hard register gets a separate stack slot, and as a result function stack frames are larger. Chonky frames, but that's the tradeoff bestie.
  • -fno-ira-share-spill-slots — disable sharing of stack slots allocated for pseudo-registers. Each pseudo-register that doesn't get a hard register gets its own separate stack slot, and as a result function stack frames are larger again 😭.
  • -flra-remat — enable CFG-sensitive rematerialization in LRA ✨. Instead of loading values of spilled pseudos, LRA tries to rematerialize (recalculate) values if it's profitable. Enabled at levels -O2, -O3, -Os.
  • -fdelayed-branch — if it's supported for the target machine, attempt to reorder instructions to exploit instruction slots available after delayed branch instructions 🎀. Enabled at levels -O1, -O2, -O3, -Os, but not at -Og (sorry -Og girlies).
  • -fschedule-insns — if it's supported for the target machine, attempt to reorder instructions to eliminate execution stalls caused by required data being unavailable ⭐. This helps machines that have slow floating point or memory load instructions by letting other instructions be issued until the result of the load or floating-point instruction is actually required. Enabled at levels -O2, -O3.
  • -fschedule-insns2 — similar to -fschedule-insns, but it requests an additional pass of instruction scheduling after register allocation has been done 💖. This is especially useful on machines with a relatively small number of registers and where memory load instructions take more than one cycle. Enabled at levels -O2, -O3, -Os.
  • -fno-sched-interblock — disable instruction scheduling across basic blocks, which is normally enabled when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher 🙈.
  • -fno-sched-spec — disable speculative motion of non-load instructions, which is normally enabled when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher.
  • -fsched-pressure — enable register pressure sensitive insn scheduling before register allocation 🦋. This only makes sense when scheduling before register allocation is enabled, i.e. with -fschedule-insns or at -O2 or higher. Using this option can improve the generated code and decrease its size by preventing register pressure from increasing above the number of available hard registers and the subsequent spills in register allocation. Chef's kiss honestly.
  • -fsched-spec-load — allow speculative motion of some load instructions. This only makes sense when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher ✨.
  • -fsched-spec-load-dangerous — allow speculative motion of more load instructions 💀. It's giving dangerous, the name is not a vibe check you can ignore. This only makes sense when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher.
  • -fsched-stalled-insns, *-fsched-stalled-insns=n* — define how many insns (if any) can be moved prematurely from the queue of stalled insns into the ready list during the second scheduling pass 🎀. -fno-sched-stalled-insns means that no insns are moved prematurely, and -fsched-stalled-insns=0 means there's no limit on how many queued insns can be moved prematurely. -fsched-stalled-insns without a value is equivalent to -fsched-stalled-insns=1.
  • -fsched-stalled-insns-dep, *-fsched-stalled-insns-dep=n* — define how many insn groups (cycles) are examined for a dependency on a stalled insn that's a candidate for premature removal from the queue of stalled insns 👑. This only has an effect during the second scheduling pass, and only if -fsched-stalled-insns is used. -fno-sched-stalled-insns-dep is equivalent to -fsched-stalled-insns-dep=0. And -fsched-stalled-insns-dep without a value is equivalent to -fsched-stalled-insns-dep=1.
  • -fsched2-use-superblocks — when scheduling after register allocation, use superblock scheduling 🌈. This allows motion across basic block boundaries, resulting in faster schedules. This option is experimental, bestie, because not all machine descriptions used by GCC model the CPU closely enough to avoid unreliable results from the algorithm 😭. This only makes sense when scheduling after register allocation, i.e. with -fschedule-insns2 or at -O2 or higher.
  • -fsched-group-heuristic — enable the group heuristic in the scheduler. This heuristic favors the instruction that belongs to a schedule group 🫶. It's enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -fsched-critical-path-heuristic — enable the critical-path heuristic in the scheduler 🔥. This heuristic favors instructions on the critical path. Enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -fsched-spec-insn-heuristic — enable the speculative instruction heuristic in the scheduler ✨. This heuristic favors speculative instructions with greater dependency weakness. Enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -fsched-rank-heuristic — enable the rank heuristic in the scheduler 💜. This heuristic favors the instruction belonging to a basic block with greater size or frequency. Enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -fsched-last-insn-heuristic — enable the last-instruction heuristic in the scheduler 🌸. This heuristic favors the instruction that is less dependent on the last instruction scheduled. Enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -fsched-dep-count-heuristic — enable the dependent-count heuristic in the scheduler 🎀. This heuristic favors the instruction that has more instructions depending on it. Enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -freschedule-modulo-scheduled-loops — modulo scheduling is performed before traditional scheduling 😤. So if a loop is modulo scheduled, later scheduling passes may change its schedule. Use this option to control that behavior.
  • -fselective-scheduling — schedule instructions using the selective scheduling algorithm 🦋. Selective scheduling runs instead of the first scheduler pass.
  • -fselective-scheduling2 — schedule instructions using the selective scheduling algorithm. Selective scheduling runs instead of the second scheduler pass. (Yes, the 2 is doing a lot of work here, iykyk.)
  • -fsel-sched-pipelining — enable software pipelining of innermost loops during selective scheduling 💫. This option has no effect unless one of -fselective-scheduling or -fselective-scheduling2 is turned on.
  • -fsel-sched-pipelining-outer-loops — when pipelining loops during selective scheduling, also pipeline outer loops 🌀. This option has no effect unless -fsel-sched-pipelining is turned on.
  • -fsemantic-interposition — okay so some object formats (ELF bestie, we're looking at you) let the dynamic linker interpose symbols 👀. Which means for symbols exported from the DSO, the compiler cannot do interprocedural propagation, inlining and other optimizations, because the function or variable in question might just... change. It's a genuinely useful feature, like when you wanna rewrite memory allocation functions with a debugging implementation, but it's expensive in terms of code quality 💸. With -fno-semantic-interposition the compiler assumes that if interposition happens for functions, the overwriting function will have precisely the same semantics (and side effects). Same vibe for variables: if interposition happens, the constructor of the variable will be the same. This flag has no effect for functions explicitly declared inline (where it's never allowed for interposition to change semantics) and for symbols explicitly declared weak.
  • -fshrink-wrap — emit function prologues only before the parts of the function that actually need it, instead of dumping them at the top of the function. Enabled by default at -O and higher ✨.
  • -fshrink-wrap-separate — shrink-wrap separate parts of the prologue and epilogue separately, so those parts only get executed when needed. On by default, but it does literally nothing unless -fshrink-wrap is also turned on and the target supports it 🫶.
  • -fcaller-saves — enable allocation of values to registers that are clobbered by function calls, by emitting extra instructions to save and restore the registers around such calls. Such allocation happens only when it seems to result in better code. This option is always enabled by default on certain machines, usually those which have no call-preserved registers to use instead. Enabled at levels -O2, -O3, -Os 🔥.
  • -fcombine-stack-adjustments — tracks stack adjustments (pushes and pops) and stack memory references, then tries to find ways to combine them. Enabled by default at -O1 and higher.
  • -fipa-ra — use caller save registers for allocation if those registers aren't used by any called function 🎀. In that case it's not necessary to save and restore them around calls. Only possible if the called functions are part of the same compilation unit as the current function and they're compiled before it. Enabled at levels -O2, -O3, -Os, HOWEVER the option is disabled if generated code will be instrumented for profiling (-p, or -pg) or if the callee's register usage cannot be known exactly (this happens on targets that don't expose prologues and epilogues in RTL) 💀.
  • -fconserve-stack — attempt to minimize stack usage. The compiler tries to use less stack space, even if that makes the program slower 😭. This option implies setting the large-stack-frame parameter to 100 and the large-stack-frame-growth parameter to 400.
  • -ftree-reassoc — perform reassociation on trees. Enabled by default at -O1 and higher.
  • -fcode-hoisting — perform code hoisting ✨. Code hoisting tries to move the evaluation of expressions executed on all paths to the function exit as early as possible. Especially useful as a code size optimization, but it often helps for code speed too. Enabled by default at -O2 and higher.
  • -ftree-pre — perform partial redundancy elimination (PRE) on trees. Enabled by default at -O2 and -O3.
  • -ftree-partial-pre — makes partial redundancy elimination (PRE) more aggressive 💅. Enabled by default at -O3.
  • -ftree-forwprop — perform forward propagation on trees. Enabled by default at -O1 and higher.
  • -ftree-fre — perform full redundancy elimination (FRE) on trees. The difference between FRE and PRE is that FRE only considers expressions that are computed on all paths leading to the redundant computation. This analysis is faster than PRE, though it exposes fewer redundancies. Enabled by default at -O1 and higher.
  • -ftree-phiprop — perform hoisting of loads from conditional pointers on trees. This pass is enabled by default at -O1 and higher.
  • -fhoist-adjacent-loads — speculatively hoist loads from both branches of an if-then-else if the loads are from adjacent locations in the same structure and the target architecture has a conditional move instruction 👑. Enabled by default at -O2 and higher.
  • -ftree-copy-prop — perform copy propagation on trees. This pass eliminates unnecessary copy operations. Enabled by default at -O1 and higher.
  • -fipa-pure-const — discover which functions are pure or constant 🦋. Enabled by default at -O1 and higher.
  • -fipa-reference — discover which static variables do not escape the compilation unit. Enabled by default at -O1 and higher.
  • -fipa-reference-addressable — discover read-only, write-only and non-addressable static variables. Enabled by default at -O1 and higher.
  • -fipa-stack-alignment — reduce stack alignment on call sites if possible. Enabled by default.
  • -fipa-pta — perform interprocedural pointer analysis and interprocedural modification and reference analysis. Heads up bestie: this option can cause excessive memory and compile-time usage on large compilation units 😭. It's not enabled by default at any optimization level.
  • -fipa-profile — perform interprocedural profile propagation. Functions called only from cold functions are marked as cold. Also functions executed once (such as "cold", "noreturn", static constructors or destructors) get identified. Cold functions and loop less parts of functions executed once are then optimized for size. Enabled by default at -O1 and higher.
  • -fipa-modref — perform interprocedural mod/ref analysis. This optimization analyzes the side effects of functions (memory locations that are modified or referenced) and enables better optimization across the function call boundary 🫶. Enabled by default at -O1 and higher.
  • -fipa-cp — perform interprocedural constant propagation. This optimization analyzes the program to figure out when values passed to functions are constants and then optimizes accordingly. Can substantially increase performance if the application has constants passed to functions 🔥. Enabled by default at -O2, -Os and -O3. It's also enabled by -fprofile-use and -fauto-profile.
  • -fipa-cp-clone — perform function cloning to make interprocedural constant propagation stronger. When enabled, interprocedural constant propagation performs function cloning when an externally visible function can be called with constant arguments. Because this optimization can create multiple copies of functions, it may significantly increase code size (see --param ipa-cp-unit-growth=value) 💀. Enabled by default at -O3. Also enabled by -fprofile-use and -fauto-profile.
  • -fipa-bit-cp — when enabled, perform interprocedural bitwise constant propagation ✨. Enabled by default at -O2 and by -fprofile-use and -fauto-profile. It requires that -fipa-cp is enabled.
  • -fipa-vrp — when enabled, perform interprocedural propagation of value ranges. Enabled by default at -O2. It requires that -fipa-cp is enabled.
  • -fipa-icf — perform Identical Code Folding for functions and read-only variables. The optimization reduces code size and may disturb unwind stacks by replacing a function by an equivalent one with a different name 😬. The optimization works more effectively with link-time optimization enabled. Although the behavior is similar to the Gold Linker's ICF optimization, GCC ICF works on different levels and thus the optimizations are not the same — there are equivalences that are found only by GCC and equivalences found only by Gold. Enabled by default at -O2 and -Os.
  • -flive-patching=level — control GCC's optimizations to produce output suitable for live-patching 🧚.

Okay so if the compiler's optimization uses a function's body or information extracted from its body to optimize/change another function, that latter one is called an impacted function of the former. And if a function is patched, its impacted functions should be patched too.

The impacted functions are determined by the compiler's interprocedural optimizations. For example, a caller is impacted when inlining a function into its caller, cloning a function and changing its caller to call this new clone, or extracting a function's pureness/constness information to optimize its direct or indirect callers, etc.

Usually, the more IPA optimizations enabled, the larger the number of impacted functions for each function. In order to control the number of impacted functions and more easily compute the list of impacted functions, IPA optimizations can be partially enabled at two different levels 🌸.

The level argument should be one of the following:

  • inline-clone — only enable inlining and cloning optimizations, which includes inlining, cloning, interprocedural scalar replacement of aggregates and partial inlining. As a result, when patching a function, all its callers and its clones' callers are impacted, therefore need to be patched as well. -flive-patching=inline-clone disables the following optimization flags: -fwhole-program -fipa-pta -fipa-reference -fipa-ra -fipa-icf -fipa-icf-functions -fipa-icf-variables -fipa-bit-cp -fipa-vrp -fipa-pure-const -fipa-reference-addressable -fipa-stack-alignment -fipa-modref
  • inline-only-static — only enable inlining of static functions. As a result, when patching a static function, all its callers are impacted and so need to be patched as well. In addition to all the flags that -flive-patching=inline-clone disables, -flive-patching=inline-only-static disables the following additional optimization flags: -fipa-cp-clone -fipa-sra -fpartial-inlining -fipa-cp

When -flive-patching is specified without any value, the default value is inline-clone.

This flag is disabled by default.

⚠️ Note that -flive-patching is not supported with link-time optimization (-flto). Like, at all. 💀
  • -fisolate-erroneous-paths-dereference — okay so this one sniffs out paths that trigger erroneous or undefined behavior by dereferencing a null pointer 😬 then it isolates those paths away from the main control flow and turns the statement with the erroneous or undefined behavior into a trap. It's enabled by default at -O2 and higher, and it depends on -fdelete-null-pointer-checks also being enabled. team effort bestie 💅
  • -fisolate-erroneous-paths-attribute — same vibe, different crime: it detects paths that trigger erroneous or undefined behavior because a null value got used in a way that a returns_nonnull or nonnull attribute forbids. Isolates those paths from the main control flow and turns the statement with erroneous or undefined behavior into a trap. This is not currently enabled, but it may be enabled by -O2 in the future. manifesting ✨
  • -ftree-sink — performs forward store motion on trees. Enabled by default at -O1 and higher. slay, moving stores forward 💫
  • -ftree-bit-ccp — performs sparse conditional bit constant propagation on trees and propagates pointer alignment information. This pass only operates on local scalar variables and is enabled by default at -O1 and higher, except for -Og. It requires that -ftree-ccp is enabled. iykyk 🔥
  • -ftree-ccp — performs sparse conditional constant propagation (CCP) on trees. This pass only operates on local scalar variables and is enabled by default at -O1 and higher. iconic behavior honestly 👑
  • -fssa-backprop — propagates information about uses of a value up the definition chain so the definitions can be simplified. Like, for example, this pass strips sign operations if the sign of a value never matters. Enabled by default at -O1 and higher. it's giving "why are you even here" energy 💀
  • -fssa-phiopt — performs pattern matching on SSA PHI nodes to optimize conditional code. Enabled by default at -O1 and higher, except for -Og. 🦋
  • -ftree-switch-conversion — performs conversion of simple initializations in a switch to initializations from a scalar array. Enabled by default at -O2 and higher. switch glow-up fr fr 🌸
  • -ftree-tail-merge — looks for identical code sequences. When it finds them, it replaces one with a jump to the other. This optimization is known as tail merging</> or cross jumping</>. Enabled by default at -O2 and higher. The compilation time in this pass can be limited using max-tail-merge-comparisons parameter and max-tail-merge-iterations parameter. twin behavior, no cap 👯‍♀️
ngl those two parameters are literally named exactly like that, i'm not making it up 🫶
  • -ftree-dce — performs dead code elimination (DCE) on trees. Enabled by default at -O1 and higher. rip to the dead code, you will not be missed 💀✨
  • -ftree-builtin-call-dce — performs conditional dead code elimination (DCE) for calls to built-in functions that may set errno but are otherwise free of side effects. Enabled by default at -O2 and higher if -Os is not also specified. conditional queen 👑
  • -ffinite-loops — assumes that a loop with an exit will eventually take the exit and not loop indefinitely. This lets the compiler remove loops that otherwise have no side-effects, since it's not considering eventual endless looping as a side-effect.

Enabled by default at -O2 for C++ with -std=c++11 or higher. bestie said "the loop WILL end" and honestly, respect 🫡

  • -ftree-dominator-opts — performs a variety of simple scalar cleanups (constant/copy propagation, redundancy elimination, range propagation and expression simplification) based on a dominator tree traversal. It also performs jump threading (to reduce jumps to jumps). Enabled by default at -O1 and higher. little bit of everything, main character of optimizations 💅
  • -ftree-dse — performs dead store elimination (DSE) on trees. A dead store is a store into a memory location that's later overwritten by another store without any intervening loads. In that case the earlier store can be deleted. Enabled by default at -O1 and higher. ma'am, that store was never getting read, let her go 😭
  • -ftree-ch — performs loop header copying on trees. This is beneficial since it increases the effectiveness of code motion optimizations. It also saves one jump. Enabled by default at -O1 and higher. It is not enabled for -Os, since it usually increases code size. trade-offs, we know her 💅
  • -ftree-loop-optimize — performs loop optimizations on trees. Enabled by default at -O1 and higher. looping looping looping 🌈
  • -ftree-loop-linear
  • -floop-strip-mine
  • -floop-block — these three do loop nest optimizations. Same as -floop-nest-optimize. To use this code transformation, GCC has to be configured with --with-isl to enable the Graphite loop transformation infrastructure. trio energy 🎀
  • -fgraphite-identity — enables the identity transformation for graphite. For every SCoP we generate the polyhedral representation and transform it back to gimple. Using -fgraphite-identity we can check the costs or benefits of the GIMPLE -> GRAPHITE -> GIMPLE transformation. Some minimal optimizations are also performed by the code generator isl, like index splitting and dead code elimination in loops. GIMPLE -> GRAPHITE -> GIMPLE is such a journey honestly 💫
  • -floop-nest-optimize — enables the isl based loop nest optimizer. This is a generic loop nest optimizer based on the Pluto optimization algorithms. It calculates a loop structure optimized for data-locality and parallelism. This option is experimental. 🙈
  • -floop-parallelize-all — uses the Graphite data dependence analysis to identify loops that can be parallelized. Parallelizes all the loops that can be analyzed to not contain loop carried dependences, without checking that it is profitable to parallelize the loops. bestie just does it, no vibe check first 😭
  • -ftree-coalesce-vars — while transforming the program out of the SSA representation, it attempts to reduce copying by coalescing versions of different user-defined variables, instead of just compiler temporaries. This may severely limit the ability to debug an optimized program compiled with -fno-var-tracking-assignments. In the negated form, this flag prevents SSA coalescing of user variables. Enabled by default if optimization is enabled, and it does very little otherwise. worth it for the debugging pain? that's your call 🫶
  • -ftree-loop-if-convert — attempts to transform conditional jumps in the innermost loops into branch-less equivalents. The intent is to remove control-flow from the innermost loops so the vectorization pass can handle those loops better. Enabled by default if vectorization is enabled. branch-less slay 🌸
  • -ftree-loop-distribution — performs loop distribution. This flag can improve cache performance on big loop bodies and allow further loop optimizations, like parallelization or vectorization, to take place. For example, the loop
        DO I = 1, N
          A(I) = B(I) + C
          D(I) = E(I) * F
        ENDDO

is transformed to

        DO I = 1, N
           A(I) = B(I) + C
        ENDDO
        DO I = 1, N
           D(I) = E(I) * F
        ENDDO

Enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile. split it, distribute it, slay it ✨

  • -ftree-loop-distribute-patterns — performs loop distribution of patterns that can be code generated with calls to a library. Enabled by default at -O2 and higher, and by -fprofile-use and -fauto-profile.

This pass distributes the initialization loops and generates a call to memset zero. For example, the loop

        DO I = 1, N
          A(I) = 0
          B(I) = A(I) + I
        ENDDO

is transformed to

        DO I = 1, N
           A(I) = 0
        ENDDO
        DO I = 1, N
           B(I) = A(I) + I
        ENDDO

and the initialization loop is transformed into a call to memset zero. Enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile. memset zero is the moment 💅

  • -floop-interchange — performs loop interchange outside of graphite. This flag can improve cache performance on loop nest and allow further loop optimizations, like vectorization, to take place. For example, the loop
        for (int i = 0; i < N; i++)
          for (int j = 0; j < N; j++)
            for (int k = 0; k < N; k++)
              c[i][j] = c[i][j] + a[i][k]*b[k][j];

is transformed to

        for (int i = 0; i < N; i++)
          for (int k = 0; k < N; k++)
            for (int j = 0; j < N; j++)
              c[i][j] = c[i][j] + a[i][k]*b[k][j];

Enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile. notice how j and k literally swapped places 😭 iconic

  • -floop-unroll-and-jam — applies unroll and jam transformations on feasible loops. In a loop nest this unrolls the outer loop by some factor and fuses the resulting multiple inner loops. Enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile. unroll AND jam, like a little breakfast combo 🍓
  • -ftree-loop-im — performs loop invariant motion on trees. This pass moves only invariants that are hard to handle at RTL level (function calls, operations that expand to nontrivial sequences of insns). With -funswitch-loops it also moves operands of conditions that are invariant out of the loop, so that we can use just trivial invariantness analysis in loop unswitching. The pass also includes store motion. moving things out of the loop = self care 🧚
  • -ftree-loop-ivcanon — creates a canonical counter for number of iterations in loops for which determining the number of iterations requires complicated analysis. Later optimizations then may determine the number easily. Useful especially in connection with unrolling. bestie said "let me just count it for you" 🫶
  • -ftree-scev-cprop — performs final value replacement. If a variable is modified in a loop in such a way that its value when exiting the loop can be determined using only its initial value and the number of loop iterations, replace uses of the final value by such a computation, provided it is sufficiently cheap. This reduces data dependencies and may allow further simplifications. Enabled by default at -O1 and higher. math girlboss 💜
  • -fivopts — performs induction variable optimizations (strength reduction, induction variable merging and induction variable elimination) on trees. strength reduction, merging AND elimination, she does it all 👑
  • -ftree-parallelize-loops=n — parallelizes loops, i.e., splits their iteration space to run in n threads. This is only possible for loops whose iterations are independent and can be arbitrarily reordered. The optimization is only profitable on multiprocessor machines, for loops that are CPU-intensive, rather than constrained e.g. by memory bandwidth. This option implies -pthread, and thus is only supported on targets that have support for -pthread. n threads!! multithreading era 🔥
lowkey obsessed with how many of these are just "we moved this thing so it's faster now" — but the details matter bestie, we keep every single one 💅
  • -ftree-pta — does function-local points-to analysis on trees 🧚 it's on by default at -O1 and up, except for -Og (she sits that one out, respectfully).
  • -ftree-sra — scalar replacement of aggregates, bestie 💅 this pass swaps structure references out for scalars so structures don't get committed to memory too early (no rushing into things, we're not doing that here). Enabled by default at -O1 and higher, except for -Og.
  • -fstore-merging — merges narrow stores that land on consecutive memory addresses ✨ the pass fuses contiguous stores of immediate values narrower than a word into fewer wider stores, so like, fewer instructions overall. On by default at -O2 and higher, plus -Os.
  • -ftree-ter — temporary expression replacement during the SSA->normal phase 🌀 single use/single def temporaries get replaced at their use location with their defining expression. Result? Non-GIMPLE code, but the expanders get way more complex trees to work with, which gives better RTL generation. Lowkey a glow-up. Enabled by default at -O1 and higher.
  • -ftree-slsr — straight-line strength reduction on trees 🫶 it spots related expressions involving multiplications and swaps them for less expensive calculations when it can. Enabled by default at -O1 and higher.
  • -ftree-vectorize — vectorization on trees ⚡ this flag turns on -ftree-loop-vectorize and -ftree-slp-vectorize if you didn't explicitly specify them.
  • -ftree-loop-vectorize — loop vectorization on trees 🔥 enabled by default at -O2 and by -ftree-vectorize, -fprofile-use, and -fauto-profile.
  • -ftree-slp-vectorize — basic block vectorization on trees 🌈 enabled by default at -O2 and by -ftree-vectorize, -fprofile-use, and -fauto-profile.

💜 -ftrivial-auto-var-init=choice 💜

Okay so this one initializes automatic variables with either a pattern or with zeroes, and the whole point is upping the security and predictability of a program by preventing uninitialized memory disclosure and use 🔒 iconic behavior honestly.

GCC still considers an automatic variable that doesn't have an explicit initializer as uninitialized — yes, -Wuninitialized and -Wanalyzer-use-of-uninitialized-value will still report warning messages on those bad boys. With this option, GCC will also initialize any padding of automatic variables that have structure or union types to zeroes ✨

But — and this is the tea ☕ the current implementation cannot initialize automatic variables that are declared between the controlling expression and the first case of a switch statement. Use -Wtrivial-auto-var-init to report all such cases, bestie.

The three values of choice are:

  • uninitialized — doesn't initialize any automatic variables. This is C and C++'s default 🫡
  • pattern — initializes automatic variables with values which will likely transform logic bugs into crashes down the line, are easily recognized in a crash dump, and without being values that programmers can rely on for useful program semantics. The current value is a byte-repeatable pattern with byte 0xFE 🎀 The values used for pattern initialization might be changed in the future, so don't get attached.
  • zero — initializes automatic variables with zeroes ⭐

The default is uninitialized.

You can control this behavior for a specific variable by using the variable attribute uninitialized 👑


  • -fvect-cost-model=model — changes up the cost model used for vectorization 🦋 model should be one of unlimited, dynamic, cheap or very-cheap. Here's the breakdown:
    • unlimited — the vectorized code-path is assumed to be profitable 💰
    • dynamic — a runtime check guards the vectorized code-path so it only kicks in for iteration counts that will likely run faster than the original scalar loop
    • cheap — disables vectorization of loops where doing so would be cost prohibitive (think required runtime checks for data dependence or alignment), but otherwise it's equal to the dynamic model
    • very-cheap — only allows vectorization if the vector code would entirely replace the scalar code being vectorized. For example, if each iteration of a vectorized loop could only handle exactly four iterations of the scalar loop, very-cheap would only allow vectorization if the scalar iteration count is known to be a multiple of four 🔢

The default cost model depends on other optimization flags and is either dynamic or cheap ✨

  • -fsimd-cost-model=model — alters the cost model used for vectorization of loops marked with the OpenMP simd directive 🌸 model should be one of unlimited, dynamic, cheap. All values of model mean the same thing as described in -fvect-cost-model, and by default a cost model defined with -fvect-cost-model is used.
  • -ftree-vrp — Value Range Propagation on trees 📈 similar to the constant propagation pass, except instead of values, ranges of values are propagated. This lets the optimizers yeet unnecessary range checks like array bound checks and null pointer checks. Enabled by default at -O2 and higher. Heads up tho: null pointer check elimination is only done if -fdelete-null-pointer-checks is enabled 👀
  • -fsplit-paths — splits paths leading to loop backedges 🌿 can improve dead code elimination and common subexpression elimination. Enabled by default at -O3 and above.
  • -fsplit-ivs-in-unroller — lets values of induction variables in later iterations of the unrolled loop be expressed using the value in the first iteration 🌀 this breaks long dependency chains, which improves efficiency of the scheduling passes.

A combo of -fweb and CSE is often enough to get the same effect. But it's not reliable when the loop body is more complicated than a single basic block 😬 and it also doesn't work at all on some architectures due to restrictions in the CSE pass.

This optimization is enabled by default ✅

  • -fvariable-expansion-in-unroller — with this option the compiler creates multiple copies of some local variables when unrolling a loop, which can result in superior code ✨ enabled by default for PowerPC targets, but disabled by default otherwise (PowerPC stays winning, everyone else sits this one out).
  • -fpartial-inlining — inlines parts of functions 🫶 this option only has any effect when inlining itself is turned on by the -finline-functions or -finline-small-functions options.

Enabled at levels -O2, -O3, -Os.

  • -fpredictive-commoning — predictive commoning optimization, i.e. reusing computations (especially memory loads and stores) performed in previous iterations of loops 🔁 enabled at level -O3, and it's also enabled by -fprofile-use and -fauto-profile.
  • -fprefetch-loop-arrays — if the target machine supports it, generates instructions to prefetch memory to improve the performance of loops that access large arrays 🚀 real "look ahead, bestie" energy.

Fair warning: this option may generate better or worse code — results are highly dependent on the structure of loops within the source code 🙈

Disabled at level -Os.


🎀 -fno-printf-return-value 🎀

So this one says: do NOT substitute constants for the known return value of formatted output functions such as sprintf, snprintf, vsprintf, and vsnprintf (but not printf or fprintf — those aren't invited to this party) 🚫

When the transformation is on, it lets GCC optimize or even eliminate branches based on the known return value of these functions, called with arguments that are either constant, or whose values are known to be in a range that makes determining the exact return value possible. For example, when -fprintf-return-value is in effect, both the branch and the body of the if statement (but not the call to snprintf) can be optimized away when i is a 32-bit or smaller integer, because the return value is guaranteed to be at most 8 👑

char buf[9];
if (snprintf (buf, "%08x", i) >= sizeof buf)
  ...

The -fprintf-return-value option relies on other optimizations and yields best results with -O2 and above. It works in tandem with the -Wformat-overflow and -Wformat-truncation options 💖 and yes, -fprintf-return-value is enabled by default.


  • -fno-peephole, -fno-peephole2 — disable any machine-specific peephole optimizations 🦋 the difference between -fno-peephole and -fno-peephole2 is in how they're implemented in the compiler; some targets use one, some use the other, a few use both.

-fpeephole is enabled by default. -fpeephole2 is enabled at levels -O2, -O3, -Os.

  • -fno-guess-branch-probability — do not guess branch probabilities using heuristics 🙅‍♀️ GCC uses heuristics to guess branch probabilities if they aren't provided by profiling feedback (-fprofile-arcs). These heuristics are based on the control flow graph. If some branch probabilities are specified by __builtin_expect, then the heuristics are used to guess branch probabilities for the rest of the control flow graph, taking the __builtin_expect info into account.

The interactions between the heuristics and __builtin_expect can be complex 😵‍💫 and in some cases it may be useful to disable the heuristics so the effects of __builtin_expect are easier to understand.

You can also specify the expected probability of the expression with the __builtin_expect_with_probability built-in function ✨

The default is -fguess-branch-probability at levels -O, -O2, -O3, -Os.

  • -freorder-blocks — reorders basic blocks in the compiled function to reduce the number of taken branches and improve code locality 🏘️ enabled at levels -O1, -O2, -O3, -Os.
  • -freorder-blocks-algorithm=algorithm — uses the specified algorithm for basic block reordering 💅 algorithm can be simple, which doesn't increase code size (except sometimes due to secondary effects like alignment), or stc, the "software trace cache" algorithm, which tries to put all often executed code together, minimizing the number of branches executed by making extra copies of code.

The default is simple at levels -O1, -Os, and stc at levels -O2, -O3 🎀

  • -freorder-blocks-and-partition — okay so on TOP of reordering the basic blocks in your compiled function (which already reduces how many branches actually get taken, slay), this one goes further and partitions your hot 🔥 and cold 🥶 basic blocks into separate sections of the assembly and .o files. Why? Paging. Cache locality. Performance. It's giving main character optimization energy, honestly.
🚨 bestie listen — this optimization gets automatically turned OFF when any of these show up: exception handling or unwind tables (on targets using setjump/longjump or a target specific scheme), linkonce sections, functions with a user-defined section attribute, and literally any architecture that doesn't support named sections. Also, when -fsplit-stack is used, this option is not enabled by default (to avoid linker errors), but you can enable it explicitly — if you're using a working linker. No cap.

Enabled for x86 at levels -O2, -O3, -Os. 💅

  • -freorder-functions — reorders functions inside the object file so the code locality is better. How? It uses special subsections — .text.hot for the most frequently executed functions and .text.unlikely for the ones that basically never run 🙈. The linker does the actual reordering, so the object file format has to support named sections and the linker has to place them somewhere reasonable.
Heads up: this option isn't effective unless you either provide profile feedback (peep -fprofile-arcs for the deets) or manually annotate functions with hot or cold attributes. Otherwise it's just vibes with no data.

Enabled at levels -O2, -O3, -Os. ✨

  • -fstrict-aliasing — lets the compiler assume the strictest aliasing rules that apply to whatever language you're compiling. For C (and C++), this activates optimizations based on the type of expressions. Specifically: an object of one type is assumed to never live at the same address as an object of a different type, unless the types are almost the same. So for example, an unsigned int can alias an int, but not a void* or a double. A character type may alias any other type. iykyk 🦋

Pay special attention to code like this:

union a_union {
  int i;
  double d;
};

int f() {
  union a_union t;
  t.d = 3.0;
  return t.i;
}

The practice of reading from a different union member than the one most recently written to (called "type-punning") is common. And even with -fstrict-aliasing, type-punning is allowed — provided the memory is accessed through the union type. So the code above works as expected. 💖 However, this code might not:

int f() {
  union a_union t;
  int* ip;
  t.d = 3.0;
  ip = &t.i;
  return *ip;
}

Similarly, access by taking the address, casting the resulting pointer and dereferencing the result has undefined behavior 😭 — even if the cast uses a union type, e.g.:

int f() {
  double d = 3.0;
  return ((union a_union *) &d)->i;
}

The -fstrict-aliasing option is enabled at levels -O2, -O3, -Os. 🎀

  • -fipa-strict-aliasing — controls whether the rules of -fstrict-aliasing get applied across function boundaries. Note bestie: if multiple functions get inlined into a single function, the memory accesses are no longer considered to be crossing a function boundary. 🧚

The -fipa-strict-aliasing option is enabled by default and is effective only in combination with -fstrict-aliasing. ✨

  • -falign-functions
  • -falign-functions=n
  • -falign-functions=n:m
  • -falign-functions=n:m:n2
  • -falign-functions=n:m:n2:m2 — aligns the start of functions to the next power-of-two greater than or equal to n, skipping up to m-1 bytes. This ensures at least the first m bytes of the function can be fetched by the CPU without crossing an n-byte alignment boundary. 🫶

If m is not specified, it defaults to n.

Examples, because examples ate: -falign-functions=32 aligns functions to the next 32-byte boundary, -falign-functions=24 aligns to the next 32-byte boundary only if this can be done by skipping 23 bytes or less, -falign-functions=32:7 aligns to the next 32-byte boundary only if this can be done by skipping 6 bytes or less. ⭐

The second pair of n2:m2 values lets you specify a secondary alignment: -falign-functions=64:7:32:3 aligns to the next 64-byte boundary if this can be done by skipping 6 bytes or less, otherwise aligns to the next 32-byte boundary if this can be done by skipping 2 bytes or less. If m2 is not specified, it defaults to n2. 🦋

Some assemblers only support this flag when n is a power of two — in that case, it gets rounded up.

-fno-align-functions and -falign-functions=1 are equivalent and mean that functions are not aligned. periodt.

If n is not specified or is zero, use a machine-dependent default. The maximum allowed n option value is 65536.

Enabled at levels -O2, -O3. 💜

  • -flimit-function-alignment — if this option is enabled, the compiler tries to avoid unnecessarily overaligning functions. It attempts to instruct the assembler to align by the amount specified by -falign-functions, but not to skip more bytes than the size of the function. Lowkey a polite little option honestly 🌸
  • -falign-labels
  • -falign-labels=n
  • -falign-labels=n:m
  • -falign-labels=n:m:n2
  • -falign-labels=n:m:n2:m2 — aligns all branch targets to a power-of-two boundary. 🎯

Parameters of this option are analogous to the -falign-functions option. -fno-align-labels and -falign-labels=1 are equivalent and mean that labels are not aligned.

If -falign-loops or -falign-jumps are applicable and are greater than this value, then their values are used instead. 👑

If n is not specified or is zero, use a machine-dependent default which is very likely to be 1, meaning no alignment. The maximum allowed n option value is 65536.

Enabled at levels -O2, -O3. ✨

  • -falign-loops
  • -falign-loops=n
  • -falign-loops=n:m
  • -falign-loops=n:m:n2
  • -falign-loops=n:m:n2:m2 — aligns loops to a power-of-two boundary. If the loops are executed many times, this makes up for any execution of the dummy padding instructions. So the padding pays for itself, iconic 💅

If -falign-labels is greater than this value, then its value is used instead.

Parameters of this option are analogous to the -falign-functions option. -fno-align-loops and -falign-loops=1 are equivalent and mean that loops are not aligned. The maximum allowed n option value is 65536.

If n is not specified or is zero, use a machine-dependent default.

Enabled at levels -O2, -O3. 🔥

  • -falign-jumps
  • -falign-jumps=n
  • -falign-jumps=n:m
  • -falign-jumps=n:m:n2
  • -falign-jumps=n:m:n2:m2 — aligns branch targets to a power-of-two boundary, but only for branch targets where the targets can only be reached by jumping. In this case, no dummy operations need be executed — no wasted instructions, we love a zero-waste queen 🧚

If -falign-labels is greater than this value, then its value is used instead.

Parameters of this option are analogous to the -falign-functions option. -fno-align-jumps and -falign-jumps=1 are equivalent and mean that loops are not aligned.

If n is not specified or is zero, use a machine-dependent default. The maximum allowed n option value is 65536.

Enabled at levels -O2, -O3. 💖

  • -fno-allocation-dce — do not remove unused C++ allocations in dead code elimination. That's it, that's the whole vibe 🙈
  • -fallow-store-data-races — allows the compiler to perform optimizations that may introduce new data races on stores, without proving that the variable can't be concurrently accessed by other threads. 👀 Does not affect optimization of local data. It's safe to use this option if it is known that global data will not be accessed by multiple threads.

Examples of optimizations enabled by -fallow-store-data-races include hoisting or if-conversions that may cause a value that was already in memory to be re-written with that same value. Such re-writing is safe in a single threaded context but may be unsafe in a multi-threaded context. Note that on some processors, if-conversions may be required in order to enable vectorization. 🦋

Enabled at level -Ofast. ⚡

  • -funit-at-a-time — this option is left for compatibility reasons. -funit-at-a-time has no effect, while -fno-unit-at-a-time implies -fno-toplevel-reorder and -fno-section-anchors. Yes bestie it's basically a legacy decoration at this point 💀

Enabled by default.

  • -fno-toplevel-reorder — do not reorder top-level functions, variables, and asm statements. Output them in the same order they appear in the input file. When this option is used, unreferenced static variables are not removed. This option is intended to support existing code that relies on a particular ordering. For new code, it's better to use attributes when possible. 🎀

-ftoplevel-reorder is the default at -O1 and higher, and also at -O0 if -fsection-anchors is explicitly requested. Additionally -fno-toplevel-reorder implies -fno-section-anchors.

  • -fweb — constructs webs as commonly used for register allocation purposes and assigns each web an individual pseudo register. This allows the register allocation pass to operate on pseudos directly, but also strengthens several other optimization passes — like CSE, the loop optimizer and the trivial dead code remover. It can, however, make debugging impossible, since variables no longer stay in a "home register". 😭 Gotta love a tradeoff.

Enabled by default with -funroll-loops.

  • -fwhole-program — assumes that the current compilation unit represents the whole program being compiled. All public functions and variables — except main and those merged by attribute externally_visible — become static functions, and in effect get optimized more aggressively by interprocedural optimizers. 👑
Bestie, do not use this option in combination with -flto. Relying on a linker plugin instead should provide safer and more precise information. fr fr.
  • -flto[=n] — this option runs the standard link-time optimizer. When invoked with source code, it generates GIMPLE (one of GCC's internal representations) and writes it to special ELF sections in the object file. When the object files get linked together, all the function bodies are read from these ELF sections and instantiated as if they had been part of the same translation unit. 🦋✨ It's giving "surprise, we were one file all along" energy.

Okay so to actually use the link-time optimizer, bestie, you gotta put -flto and your optimization options at compile time and during the final link. 💖 It’s recommended that you compile every file joining the same link with the same options, and also specify those options at link time. Like:

gcc -c -O2 -flto foo.c
gcc -c -O2 -flto bar.c
gcc -o myprog -flto -O2 foo.o bar.o

The first two invocations to GCC save a bytecode representation of GIMPLE into special ELF sections inside foo.o and bar.o. Then the final invocation reads the GIMPLE bytecode from foo.o and bar.o, merges the two files into one single internal image, and compiles the result as usual. Since both foo.o and bar.o get merged into a single image, all the interprocedural analyses and optimizations in GCC work across the two files like they were one file. So, for example, the inliner can inline functions in bar.o into functions in foo.o and vice-versa. ✨

Another (simpler) way to enable link-time optimization is:

gcc -o myprog -flto -O2 foo.c bar.c

That generates bytecode for foo.c and bar.c, merges them together into a single GIMPLE representation, and optimizes them as usual to produce myprog. 🫶

The important thing to keep in mind is that to enable link-time optimizations you need to use the GCC driver to perform the link step. GCC automatically performs link-time optimization if any of the objects involved were compiled with the -flto command-line option. You can always override the automatic decision to do link-time optimization by passing -fno-lto to the link command. 💅

To make whole program optimization effective, it is necessary to make certain whole program assumptions. The compiler needs to know what functions and variables can be accessed by libraries and runtime outside of the link-time optimized unit. When supported by the linker, the linker plugin (see -fuse-linker-plugin) passes information to the compiler about used and externally visible symbols. When the linker plugin is not available, -fwhole-program should be used to allow the compiler to make these assumptions, which leads to more aggressive optimization decisions. 👑

When a file is compiled with -flto without -fuse-linker-plugin, the generated object file is larger than a regular object file because it contains GIMPLE bytecodes and the usual final code (see -ffat-lto-objects). This means that object files with LTO information can be linked as normal object files; if -fno-lto is passed to the linker, no interprocedural optimizations are applied. Note that when -fno-fat-lto-objects is enabled the compile stage is faster, but you cannot perform a regular, non-LTO link on them. 😭

When producing the final binary, GCC only applies link-time optimizations to those files that contain bytecode. Therefore, you can mix and match object files and libraries with GIMPLE bytecodes and final object code. GCC automatically selects which files to optimize in LTO mode and which files to link without further processing. 🌈

Generally, options specified at link time override those specified at compile time, although in some cases GCC attempts to infer link-time options from the settings used to compile the input files. ⭐

If you do not specify an optimization level option -O at link time, then GCC uses the highest optimization level used when compiling the object files. Note that it is generally ineffective to specify an optimization level option only at link time and not at compile time, for two reasons. First, compiling without optimization suppresses compiler passes that gather information needed for effective optimization at link time. Second, some early optimization passes can be performed only at compile time and not at link time. 💀

There are some code generation flags preserved by GCC when generating bytecodes, as they need to be used during the final link. Currently, the following options and their settings are taken from the first object file that explicitly specifies them: -fcommon, -fexceptions, -fnon-call-exceptions, -fgnu-tm and all the -m target flags. 🎀

The following options -fPIC, -fpic, -fpie and -fPIE are combined based on the following scheme:

-fPIC + -fpic = -fpic
-fPIC + -fno-pic = -fno-pic
-fpic/-fPIC + (no option) = (no option)
-fPIC + -fPIE = -fPIE
-fpic + -fPIE = -fpie
-fPIC/-fpic + -fpie = -fpie

Certain ABI-changing flags are required to match in all compilation units, and trying to override this at link time with a conflicting value is ignored. This includes options such as -freg-struct-return and -fpcc-struct-return. 🙈

Other options such as -ffp-contract, -fno-strict-overflow, -fwrapv, -fno-trapv or -fno-strict-aliasing are passed through to the link stage and merged conservatively for conflicting translation units. Specifically -fno-strict-overflow, -fwrapv and -fno-trapv take precedence; and for example -ffp-contract=off takes precedence over -ffp-contract=fast. You can override them at link time. 🦋

Diagnostic options such as -Wstringop-overflow are passed through to the link stage and their setting matches that of the compile-step at function granularity. Note that this matters only for diagnostics emitted during optimization. Note that code transforms such as inlining can lead to warnings being enabled or disabled for regions of code that are not consistent with the setting at compile time. 🌸

When you need to pass options to the assembler via -Wa or -Xassembler, make sure to either compile such translation units with -fno-lto or consistently use the same assembler options on all translation units. You can alternatively also specify assembler options at LTO link time. 🧚

To enable debug info generation you need to supply -g at compile time. If any of the input files at link time were built with debug info generation enabled, the link will enable debug info generation as well. Any elaborate debug info settings like the dwarf level -gdwarf-5 need to be explicitly repeated at the linker command line, and mixing different settings in different translation units is discouraged. 💜

If LTO encounters objects with C linkage declared with incompatible types in separate translation units to be linked together (undefined behavior according to ISO C99 6.2.7), a non-fatal diagnostic may be issued. The behavior is still undefined at run time. Similar diagnostics may be raised for other languages. 😭

Another feature of LTO is that it is possible to apply interprocedural optimizations on files written in different languages:

gcc -c -flto foo.c
g++ -c -flto bar.cc
gfortran -c -flto baz.f90
g++ -o myprog -flto -O3 foo.o bar.o baz.o -lgfortran

Notice that the final link is done with g++ to get the C++ runtime libraries and -lgfortran is added to get the Fortran runtime libraries. In general, when mixing languages in LTO mode, you should use the same link command options as when mixing languages in a regular (non-LTO) compilation. 🔥

If object files containing GIMPLE bytecode are stored in a library archive, say libfoo.a, it is possible to extract and use them in an LTO link if you are using a linker with plugin support. To create static libraries suitable for LTO, use gcc-ar and gcc-ranlib instead of ar and ranlib; to show the symbols of object files with GIMPLE bytecode, use gcc-nm. Those commands require that ar, ranlib and nm have been compiled with plugin support. At link time, use the flag -fuse-linker-plugin to ensure that the library participates in the LTO optimization process:

gcc -o myprog -O2 -flto -fuse-linker-plugin a.o b.o -lfoo

With the linker plugin enabled, the linker extracts the needed GIMPLE files from libfoo.a and passes them on to the running GCC to make them part of the aggregated GIMPLE image to be optimized. 👑

If you are not using a linker with plugin support and/or do not enable the linker plugin, then the objects inside libfoo.a are extracted and linked as usual, but they do not participate in the LTO optimization process. In order to make a static library suitable for both LTO optimization and usual linkage, compile its object files with -flto -ffat-lto-objects. 💖

Link-time optimizations do not require the presence of the whole program to operate. If the program does not require any symbols to be exported, it is possible to combine -flto and -fwhole-program to allow the interprocedural optimizers to use more aggressive assumptions which may lead to improved optimization opportunities. Use of -fwhole-program is not needed when linker plugin is active (see -fuse-linker-plugin). ✨

The current implementation of LTO makes no attempt to generate bytecode that is portable between different types of hosts. The bytecode files are versioned and there is a strict version check, so bytecode files generated in one version of GCC do not work with an older or newer version of GCC. 💀

Link-time optimization does not work well with generation of debugging information on systems other than those using a combination of ELF and DWARF. 🫶

If you specify the optional n, the optimization and code generation done at link time is executed in parallel using n parallel jobs by utilizing an installed make program. The environment variable MAKE may be used to override the program used. 🌟

You can also specify -flto=jobserver to use GNU make’s job server mode to determine the number of parallel jobs. This is useful when the Makefile calling GCC is already executing in parallel. You must prepend a + to the command recipe in the parent Makefile for this to work. This option likely only works if MAKE is GNU make. Even without the option value, GCC tries to automatically detect a running GNU make’s job server. 🎀

Use -flto=auto to use GNU make’s job server, if available, or otherwise fall back to autodetection of the number of CPU threads present in your system. 🌈

  • -flto-partition=alg — bestie, this one picks the partitioning algorithm the link-time optimizer uses. The value can be 1to1, which mirrors your original source files one-to-one, balanced, which splits into equally sized chunks (whenever possible), or max, which makes a new partition for every symbol where possible. If you say none as the algorithm, partitioning and streaming are completely disabled 🛑. The default is balanced. Now, 1to1 can be used as a workaround for various code ordering issues, and max is intended for internal testing only (so like, don't @ me if it's weird). The value one means exactly one partition should be used, while none bypasses partitioning and executes the link-time optimization step directly from the WPA phase. slay, now you know ✨
  • -flto-compression-level=n — this sets the level of compression used for the intermediate language written to LTO object files, and it's only meaningful in conjunction with LTO mode (-flto). GCC currently supports two LTO compression algorithms: for zstd, valid values are 0 (no compression) to 19 (maximum compression), while zlib supports values from 0 to 9. Values outside this range are clamped to either the minimum or maximum of the supported values. If you don't give the option at all, a default balanced compression setting is used 🎀
  • -fuse-linker-plugin — enables the use of a linker plugin during link-time optimization. This relies on plugin support in the linker, which is available in gold or in GNU ld 2.21 or newer, iykyk 💅

This option enables the extraction of object files with GIMPLE bytecode out of library archives. This improves the quality of optimization by exposing more code to the link-time optimizer. This information specifies what symbols can be accessed externally (by non-LTO object or during dynamic linking). Resulting code quality improvements on binaries (and shared libraries that use hidden visibility) are similar to -fwhole-program. See -flto for a description of the effect of this flag and how to use it 👑

This option is enabled by default when LTO support in GCC is enabled and GCC was configured for use with a linker supporting plugins (GNU ld 2.21 or newer or gold).

  • -ffat-lto-objects — fat LTO objects are object files that contain both the intermediate language and the object code. That makes them usable for both LTO linking and normal linking. This option is effective only when compiling with -flto and is ignored at link time 🙈

-fno-fat-lto-objects improves compilation time over plain LTO, but it requires the complete toolchain to be aware of LTO. It requires a linker with linker plugin support for basic functionality. Additionally, nm, ar and ranlib need to support linker plugins to allow a full-featured build environment (capable of building static libraries etc). GCC provides the gcc-ar, gcc-nm, gcc-ranlib wrappers to pass the right options to these tools. With non fat LTO, makefiles need to be modified to use them 🛠️

Note that modern binutils provide a plugin auto-load mechanism. Installing the linker plugin into $libdir/bfd-plugins has the same effect as usage of the command wrappers (gcc-ar, gcc-nm and gcc-ranlib).

The default is -fno-fat-lto-objects on targets with linker plugin support. periodt 💜

  • -fcompare-elim — after register allocation and post-register allocation instruction splitting, this pass identifies arithmetic instructions that compute processor flags similar to a comparison operation based on that arithmetic. If possible, it eliminates the explicit comparison operation 🔥

This pass only applies to certain targets that cannot explicitly represent the comparison operation before register allocation is complete.

Enabled at levels -O1, -O2, -O3, -Os.

  • -fcprop-registers — after register allocation and post-register allocation instruction splitting, this performs a copy-propagation pass to try to reduce scheduling dependencies and occasionally eliminate the copy. Enabled at levels -O1, -O2, -O3, -Os ✨
  • -fprofile-correction — profiles collected using an instrumented binary for multi-threaded programs may be inconsistent due to missed counter updates 😭. When this option is specified, GCC uses heuristics to correct or smooth out such inconsistencies. By default, GCC emits an error message when an inconsistent profile is detected (so like, it's not being dramatic, it's just strict).

This option is enabled by -fauto-profile.

  • -fprofile-partial-training — with -fprofile-use, all portions of programs not executed during the train run are optimized aggressively for size rather than speed. In some cases it is not practical to train all possible hot paths in the program. (For example, a program may contain functions specific for a given hardware and training may not cover all hardware configurations the program is run on.) With -fprofile-partial-training, profile feedback will be ignored for all functions not executed during the train run, leading them to be optimized as if they were compiled without profile feedback. This leads to better performance when the train run is not representative, but also leads to significantly bigger code 💀 (we love a tradeoff)
  • -fprofile-use
  • -fprofile-use=path — enable profile feedback-directed optimizations, plus the following optimizations, many of which are generally profitable only with profile feedback available 👇
-fbranch-probabilities  -fprofile-values -funroll-loops
-fpeel-loops  -ftracer  -fvpt -finline-functions  -fipa-cp
-fipa-cp-clone  -fipa-bit-cp -fpredictive-commoning  -fsplit-loops
-funswitch-loops -fgcse-after-reload  -ftree-loop-vectorize
-ftree-slp-vectorize -fvect-cost-model=dynamic
-ftree-loop-distribute-patterns -fprofile-reorder-functions

Before you can use this option, you must first generate profiling information, bestie — no skipping steps 🫶

By default, GCC emits an error message if the feedback profiles do not match the source code. This error can be turned into a warning by using -Wno-error=coverage-mismatch. Note this may result in poorly optimized code. Additionally, by default, GCC also emits a warning message if the feedback profiles do not exist (see -Wmissing-profile).

If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.

  • -fauto-profile
  • -fauto-profile=path — enable sampling-based feedback-directed optimizations, plus the following optimizations, many of which are generally profitable only with profile feedback available 🌈
-fbranch-probabilities  -fprofile-values -funroll-loops
-fpeel-loops  -ftracer  -fvpt -finline-functions  -fipa-cp
-fipa-cp-clone  -fipa-bit-cp -fpredictive-commoning  -fsplit-loops
-funswitch-loops -fgcse-after-reload  -ftree-loop-vectorize
-ftree-slp-vectorize -fvect-cost-model=dynamic
-ftree-loop-distribute-patterns -fprofile-correction

path is the name of a file containing AutoFDO profile information. If omitted, it defaults to fbdata.afdo in the current directory 🍓

Producing an AutoFDO profile data file requires running your program with the perf utility on a supported GNU/Linux target system. For more information, see <https://perf.wiki.kernel.org/>.

E.g.:

perf record -e br_inst_retired:near_taken -b -o perf.data \
    -- your_program

Then use the create_gcov tool to convert the raw profile data to a format that can be used by GCC. You must also supply the unstripped binary for your program to this tool. See <https://github.com/google/autofdo>.

E.g.:

create_gcov --binary=your_program.unstripped --profile=perf.data \
    --gcov=profile.afdo

The following options control compiler behavior regarding floating-point arithmetic. These options trade off between speed and correctness ⚖️. All must be specifically enabled — none of these are coming for free.

  • -ffloat-store — do not store floating-point variables in registers, and inhibit other options that might change whether a floating-point value is taken from a register or memory. 🧚

This option prevents undesirable excess precision on machines such as the 68000 where the floating registers (of the 68881) keep more precision than a double is supposed to have. Similarly for the x86 architecture. For most programs, the excess precision does only good, but a few programs rely on the precise definition of IEEE floating point. Use -ffloat-store for such programs, after modifying them to store all pertinent intermediate computations into variables. like, actually modify them first, don't just slap the flag on ⭐

  • -fexcess-precision=style — this option allows further control over excess precision on machines where floating-point operations occur in a format with more precision or range than the IEEE standard and interchange floating-point types. By default, -fexcess-precision=fast is in effect; this means that operations may be carried out in a wider precision than the types specified in the source if that would result in faster code, and it is unpredictable when rounding to the types specified in the source code takes place 😳. When compiling C, if -fexcess-precision=standard is specified then excess precision follows the rules specified in ISO C99; in particular, both casts and assignments cause values to be rounded to their semantic types (whereas -ffloat-store only affects assignments). This option is enabled by default for C if a strict conformance option such as -std=c99 is used. -ffast-math enables -fexcess-precision=fast by default regardless of whether a strict conformance option is used 💅

-fexcess-precision=standard is not implemented for languages other than C. On the x86, it has no effect if -mfpmath=sse or -mfpmath=sse+387 is specified; in the former case, IEEE semantics apply without excess precision, and in the latter, rounding is unpredictable. no cap, unpredictable means unpredictable 💀

  • -ffast-math — sets the options -fno-math-errno, -funsafe-math-optimizations, -ffinite-math-only, -fno-rounding-math, -fno-signaling-nans, -fcx-limited-range and -fexcess-precision=fast 🔥

This option causes the preprocessor macro __FAST_MATH__ to be defined.

⚠️ This option is not turned on by any -O option besides -Ofast, since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications. so yeah — speed demon energy, but know what you're signing up for 🎀
  • -fno-math-errno — bestie, this one says: don't bother setting errno after calling math functions that run as a single instruction, like sqrt 🧮. If your program handles math errors via IEEE exceptions instead, you might wanna flip this on for speed while still keeping IEEE arithmetic compatibility ✨.

Heads up though — no -O option turns this on, because it can straight-up produce incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions 😭. It may, however, yield faster code for programs that don't require the guarantees of those specifications.

The default is -fmath-errno.

On Darwin systems the math library never sets errno, so there's literally no reason for the compiler to consider the possibility that it might — and -fno-math-errno is the default there 🍓.

  • -funsafe-math-optimizations — the name is not a drill, bestie 💀. This allows optimizations for floating-point arithmetic that (a) assume arguments and results are valid and (b) may violate IEEE or ANSI standards. When used at link time, it may include libraries or startup files that change the default FPU control word or other similar optimizations 🌀.

Not turned on by any -O option, because it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that don't require the guarantees of those specifications. It enables -fno-signed-zeros, -fno-trapping-math, -fassociative-math and -freciprocal-math 👑

The default is -fno-unsafe-math-optimizations.

  • -fassociative-math — allows re-association of operands in series of floating-point operations 🔀. This violates the ISO C and C++ language standard by possibly changing computation result. NOTE: re-ordering may change the sign of zero as well as ignore NaNs and inhibit or create underflow or overflow (and thus cannot be used on code that relies on rounding behavior like (x + 2**52) - 2**52) 😬. May also reorder floating-point comparisons and thus may not be used when ordered comparisons are required. This option requires that both -fno-signed-zeros and -fno-trapping-math be in effect. Moreover, it doesn't make much sense with -frounding-math. For Fortran the option is automatically enabled when both -fno-signed-zeros and -fno-trapping-math are in effect 🧚.

The default is -fno-associative-math.

  • -freciprocal-math — allow the reciprocal of a value to be used instead of dividing by the value, if this enables optimizations 💫. For example x / y can be replaced with x * (1/y), which is useful if (1/y) is subject to common subexpression elimination. Note that this loses precision and increases the number of flops operating on the value 🙈.

The default is -fno-reciprocal-math.

  • -ffinite-math-only — allow optimizations for floating-point arithmetic that assume arguments and results are not NaNs or +-Infs 🌈.

Not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that don't require the guarantees of those specifications.

The default is -fno-finite-math-only.

  • -fno-signed-zeros — allow optimizations for floating-point arithmetic that ignore the signedness of zero 🅾️. IEEE arithmetic specifies the behavior of distinct +0.0 and -0.0 values, which then prohibits simplification of expressions such as x+0.0 or 0.0*x (even with -ffinite-math-only). This option implies that the sign of a zero result isn't significant.

The default is -fsigned-zeros.

  • -fno-trapping-math — compile code assuming that floating-point operations cannot generate user-visible traps 🪤. These traps include division by zero, overflow, underflow, inexact result and invalid operation. This option requires that -fno-signaling-nans be in effect. Setting this option may allow faster code if one relies on "non-stop" IEEE arithmetic, for example.
This option should never be turned on by any -O option, since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. Like, seriously, never-ever 💀.

The default is -ftrapping-math.

  • -frounding-math — disable transformations and optimizations that assume default floating-point rounding behavior 🔄. This is round-to-zero for all floating point to integer conversions, and round-to-nearest for all other arithmetic truncations. This option should be specified for programs that change the FP rounding mode dynamically, or that may be executed with a non-default rounding mode. This option disables constant folding of floating-point expressions at compile time (which may be affected by rounding mode) and arithmetic transformations that are unsafe in the presence of sign-dependent rounding modes.

The default is -fno-rounding-math.

⚠️ This option is experimental and does not currently guarantee to disable all GCC optimizations that are affected by rounding mode. Future versions of GCC may provide finer control of this setting using C99's FENV_ACCESS pragma. This command-line option will be used to specify the default state for FENV_ACCESS.
  • -fsignaling-nans — compile code assuming that IEEE signaling NaNs may generate user-visible traps during floating-point operations 🚨. Setting this option disables optimizations that may change the number of exceptions visible with signaling NaNs. This option implies -ftrapping-math.

This option causes the preprocessor macro __SUPPORT_SNAN__ to be defined ✨.

The default is -fno-signaling-nans.

⚠️ This option is experimental and does not currently guarantee to disable all GCC optimizations that affect signaling NaN behavior.
  • -fno-fp-int-builtin-inexact — don't allow the built-in functions ceil, floor, round and trunc, and their float and long double variants, to generate code that raises the "inexact" floating-point exception for noninteger arguments 🙅‍♀️. ISO C99 and C11 allow these functions to raise the "inexact" exception, but ISO/IEC TS 18661-1:2014, the C bindings to IEEE 754-2008, as integrated into ISO C2X, does not allow these functions to do so.

The default is -ffp-int-builtin-inexact, allowing the exception to be raised, unless C2X or a later C standard is selected. This option does nothing unless -ftrapping-math is in effect 👀.

Even if -fno-fp-int-builtin-inexact is used, if the functions generate a call to a library function then the "inexact" exception may be raised if the library implementation does not follow TS 18661 😭.

  • -fsingle-precision-constant — treat floating-point constants as single precision instead of implicitly converting them to double-precision constants 🎯.
  • -fcx-limited-range — when enabled, this option states that a range reduction step is not needed when performing complex division 🧮. Also, there's no checking whether the result of a complex multiplication or division is NaN + I*NaN, with an attempt to rescue the situation in that case. The default is -fno-cx-limited-range, but is enabled by -ffast-math.

This option controls the default setting of the ISO C99 CX_LIMITED_RANGE pragma. Nevertheless, the option applies to all languages 🌍.

  • -fcx-fortran-rules — complex multiplication and division follow Fortran rules 🏰. Range reduction is done as part of complex division, but there's no checking whether the result of a complex multiplication or division is NaN + I*NaN, with an attempt to rescue the situation in that case.

The default is -fno-cx-fortran-rules.


The following options control optimizations that may improve performance, but are not enabled by any -O options 🚫. This section includes experimental options that may produce broken code — so like, proceed with caution, bestie 💅.


  • -fbranch-probabilities — after running a program compiled with -fprofile-arcs, you can compile it a second time using -fbranch-probabilities, to improve optimizations based on the number of times each branch was taken 📊. When a program compiled with -fprofile-arcs exits, it saves arc execution counts to a file called sourcename.gcda for each source file. The information in this data file is very dependent on the structure of the generated code, so you must use the same source code and the same optimization options for both compilations 🫶. See details about the file naming in -fprofile-arcs.

With -fbranch-probabilities, GCC puts a REG_BR_PROB note on each JUMP_INSN and CALL_INSN. These can be used to improve optimization. Currently they're only used in one place: in reorg.cc, instead of guessing which path a branch is most likely to take, the REG_BR_PROB values are used to exactly determine which path is taken more often 🔥.

Enabled by -fprofile-use and -fauto-profile.

  • -fprofile-values — if combined with -fprofile-arcs, it adds code so that some data about values of expressions in the program is gathered 📈.

With -fbranch-probabilities, it reads back the data gathered from profiling values of expressions for usage in optimizations.

Enabled by -fprofile-generate, -fprofile-use, and -fauto-profile.

  • -fprofile-reorder-functions — function reordering based on profile instrumentation collects first time of execution of a function and orders these functions in ascending order ⏱️.

Enabled with -fprofile-use.

  • -fvpt — if combined with -fprofile-arcs, this option instructs the compiler to add code to gather information about values of expressions 🔍.

With -fbranch-probabilities, it reads back the data gathered and actually performs the optimizations based on them. Currently the optimizations include specialization of division operations using the knowledge about the value of the denominator.

Enabled with -fprofile-use and -fauto-profile.

  • -frename-registers — attempt to avoid false dependencies in scheduled code by making use of registers left over after register allocation 🧩. This optimization most benefits processors with lots of registers. Depending on the debug information format adopted by the target, however, it can make debugging impossible, since variables no longer stay in a "home register" 💀 — so like, great for speed, cursed for gdb, iykyk.

Enabled by default with -funroll-loops.


  • -fschedule-fusion — makes a little target-dependent pass over the instruction stream so it can plop instructions of the same type next to each other 👯 — because your target machine is way happier when same-vibes instructions are adjacent in the instruction flow.

On at levels -O2, -O3, -Os. ✨

  • -ftracer — does tail duplication to beef up superblock size. Basically it untangles the control flow of the function so the other optimizations can actually do their thing and shine 🦋.

Turned on by -fprofile-use and -fauto-profile.

  • -funroll-loops — unrolls loops when the number of iterations is knowable at compile time or right when you enter the loop. This one's a package deal: -funroll-loops implies -frerun-cse-after-loop, -fweb and -frename-registers. It also switches on complete loop peeling (as in, completely removing loops that have a small constant number of iterations). Heads up though: it makes your code bigger, and it may or may not make it run faster. Roll the dice 🎲

Enabled by -fprofile-use and -fauto-profile.

  • -funroll-all-loops — unrolls every loop, even the ones where the iteration count is a mystery when you enter the loop. Ngl, this usually makes programs run more slowly 💀. -funroll-all-loops implies the same options as -funroll-loops.
  • -fpeel-loops — peels loops when there's enough info that they don't roll much (info from profile feedback or static analysis). Same as above, it also turns on complete loop peeling (complete removal of loops with a small constant number of iterations).

Enabled by -O3, -fprofile-use, and -fauto-profile.

  • -fmove-loop-invariants — enables the loop invariant motion pass in the RTL loop optimizer. Enabled at level -O1 and higher, except for -Og.
  • -fmove-loop-stores — enables the loop store motion pass in the GIMPLE loop optimizer. What it does: it moves invariant stores to after the end of the loop, and in exchange it carries the stored value in a register across the iteration. ⚠️ Note that for this option to actually do anything, -ftree-loop-im has to be enabled too. Enabled at level -O1 and higher, except for -Og.
  • -fsplit-loops — splits a loop into two when it contains a condition that's always true for one side of the iteration space and always false for the other. Clean split, no notes 🤝

Enabled by -fprofile-use and -fauto-profile.

  • -funswitch-loops — moves branches with loop invariant conditions out of the loop, and duplicates the loop on both branches (each modified according to the result of the condition).

Enabled by -fprofile-use and -fauto-profile.

  • -fversion-loops-for-strides — if a loop iterates over an array with a variable stride, this makes another version of the loop that just assumes the stride is always one. So like:
        for (int i = 0; i < n; ++i)
          x[i * stride] = ...;

becomes:

        if (stride == 1)
          for (int i = 0; i < n; ++i)
            x[i] = ...;
        else
          for (int i = 0; i < n; ++i)
            x[i * stride] = ...;

This is especially useful for assumed-shape arrays in Fortran, where (for example) it lets the compiler vectorize better by assuming contiguous accesses 🔥. This flag is enabled by default at -O3. It's also enabled by -fprofile-use and -fauto-profile.

  • -ffunction-sections
  • -fdata-sections — puts each function or data item into its own section in the output file, if the target supports arbitrary sections. The name of the function or the data item decides what the section gets called in the output file 🏷️

Use these on systems where the linker can optimize for better locality of reference in the instruction space. Most systems using the ELF object format have linkers with those optimizations. On AIX, the linker rearranges sections (CSECTs) based on the call graph. The performance impact varies.

Pair them with a linker garbage collection (the linker --gc-sections option) and these options may give you smaller statically-linked executables (after stripping).

On ELF/DWARF systems these options don't degrade the quality of the debug information. There could be issues with other object files/debug info formats.

Only use these options when there are significant benefits from doing so. When you specify them, the assembler and linker create larger object and executable files and are also slower. These options affect code generation — they prevent optimizations by the compiler and assembler that use relative locations inside a translation unit, since the locations are unknown until link time. An example of that kind of optimization is relaxing calls to short call instructions.
  • -fstdarg-opt — optimizes the prologue of variadic argument functions with respect to how those arguments are used.
  • -fsection-anchors — tries to cut down the number of symbolic address calculations by using shared "anchor" symbols to address nearby objects. This transformation can help reduce the number of GOT entries and GOT accesses on some targets 💅

For example, the implementation of this function foo:

        static int a, b, c;
        int foo (void) { return a + b + c; }

usually calculates the addresses of all three variables — but if you compile it with -fsection-anchors, it accesses the variables from a common anchor point instead. The effect is similar to this pseudocode (which isn't valid C, bestie, don't try it):

        int foo (void)
        {
          register int *xr = &x;
          return xr[&a - &x] + xr[&b - &x] + xr[&c - &x];
        }

Not all targets support this option.

  • -fzero-call-used-regs=choice — zeroes call-used registers at function return, which bumps up program security either by mitigating Return-Oriented Programming (ROP) attacks or by preventing information leakage through registers 🔐

The possible values of choice are the same as for the zero_call_used_regs attribute. The default is skip.

You can control this behavior for a specific function by using the function attribute zero_call_used_regs.

  • --param name=value — sometimes GCC uses various constants to control how much optimization it does. For example, GCC doesn't inline functions that contain more than a certain number of instructions. You can control some of these constants right on the command line with the --param option 🎛️
The names of specific parameters, and the meaning of the values, are tied to the internals of the compiler, and are subject to change without notice in future releases.

To get the minimal, maximal and default value of a parameter, you can use the --help=param -Q options.

In every case, the value is an integer. These choices of name are recognized for all targets:

  • predictable-branch-outcome — when a branch is predicted to be taken with a probability lower than this threshold (in percent), then it's considered well predictable.
  • max-rtl-if-conversion-insns — RTL if-conversion tries to remove conditional branches around a block and replace them with conditionally executed instructions. This parameter gives the max number of instructions in a block that should even be considered for if-conversion. The compiler also uses other heuristics to decide whether if-conversion is likely to be profitable.
  • max-rtl-if-conversion-predictable-cost — RTL if-conversion tries to remove conditional branches around a block and replace them with conditionally executed instructions. These parameters give the maximum permissible cost for the sequence that if-conversion would generate, depending on whether the branch is statically determined to be predictable or not. The units for this parameter are the same as those for the GCC internal seq_cost metric. The compiler tries to provide a reasonable default for this parameter using the BRANCH_COST target macro.
  • max-crossjump-edges — the max number of incoming edges to consider for cross-jumping. The algorithm -fcrossjumping uses is O(N^2) in the number of edges incoming to each block. Bigger values mean more aggressive optimization, which makes compilation time go up with probably a small improvement in executable size.
  • min-crossjump-insns — the minimum number of instructions that must match at the end of two blocks before cross-jumping gets performed on them. This value is ignored when all instructions in the block being cross-jumped from are matched.
  • max-grow-copy-bb-insns — the maximum code size expansion factor when copying basic blocks instead of jumping. The expansion is relative to a jump instruction.
  • max-goto-duplication-insns — the max number of instructions to duplicate to a block that jumps to a computed goto. To dodge O(N^2) behavior in a bunch of passes, GCC factors computed gotos early in the compilation process and unfactors them as late as possible. Only computed jumps at the end of a basic block with no more than max-goto-duplication-insns get unfactored.
  • max-delay-slot-insn-search — the max number of instructions to consider when hunting for an instruction to fill a delay slot. If more than this arbitrary number of instructions get searched, the time savings from filling the delay slot are minimal, so it stops searching. Bigger values mean more aggressive optimization, making compilation time go up with probably a small improvement in execution time.
  • max-delay-slot-live-search — when trying to fill delay slots, the max number of instructions to consider when searching for a block with valid live register information. Raising this arbitrarily chosen value means more aggressive optimization, which increases the compilation time. This parameter should be removed when the delay slot code gets rewritten to maintain the control-flow graph.
  • max-gcse-memory — bestie, this is the approximate maximum amount of memory in kB that can be allocated to perform the global common subexpression elimination optimization. If more memory than specified is required, the optimization is not done. it literally just says “nope, too much” 💅
  • max-gcse-insertion-ratio — if the ratio of expression insertions to deletions is larger than this value for any expression, then RTL PRE inserts or removes the expression and thus leaves partially redundant computations in the instruction stream. RTL PRE lore unlocked 🔥
  • max-pending-list-length — the maximum number of pending dependencies scheduling allows before flushing the current state and starting over. Large functions with few branches or calls can create excessively large lists which needlessly consume memory and resources. messy queue energy 😭
  • max-modulo-backtrack-attempts — the maximum number of backtrack attempts the scheduler should make when modulo scheduling a loop. Larger values can exponentially increase compilation time. bestie, this can get spicy real fast 🌶️
  • max-inline-functions-called-once-loop-depth — maximal loop depth of a call considered by inline heuristics that tries to inline all functions called once. called-once girlies stay winning 🫶
  • max-inline-functions-called-once-insns — maximal estimated size of functions produced while inlining functions called once. size check, but for inlined once-only functions ✨
  • max-inline-insns-single — several parameters control the tree inliner used in GCC. This number sets the maximum number of instructions (counted in GCC's internal representation) in a single function that the tree inliner considers for inlining. This only affects functions declared inline and methods implemented in a class declaration (C++). single-function inliner budget, iconic behavior 👑
  • max-inline-insns-auto — when you use -finline-functions (included in -O3), a lot of functions that would otherwise not be considered for inlining by the compiler are investigated. To those functions, a different (more restrictive) limit compared to functions declared inline can be applied (--param max-inline-insns-auto). auto-inline mode has trust issues, and honestly same 💀
  • max-inline-insns-small — this is bound applied to calls which are considered relevant with -finline-small-functions. small function vibes, big decisions 🍓
  • max-inline-insns-size — this is bound applied to calls which are optimized for size. Small growth may be desirable to anticipate optimization oppurtunities exposed by inlining. (yes, “oppurtunities” is exactly what the manpage says — we do not edit the sacred text 💅)
  • uninlined-function-insns — number of instructions accounted by inliner for function overhead such as function prologue and epilogue. prologue/epilogue tax, fr fr 🎀
  • uninlined-function-time — extra time accounted by inliner for function overhead such as time needed to execute function prologue and epilogue. time tax for the function wrapper moment ⏳
  • inline-heuristics-hint-percent — the scale (in percents) applied to inline-insns-single, inline-insns-single-O2, inline-insns-auto when inline heuristics hints that inlining is very profitable (will enable later optimizations). heuristics said “this one’s a keeper” 💜
  • uninlined-thunk-insns, uninlined-thunk-time — same as --param uninlined-function-insns and --param uninlined-function-time but applied to function thunks. thunk edition, same rules 🫶
  • inline-min-speedup — when estimated performance improvement of caller + callee runtime exceeds this threshold (in percent), the function can be inlined regardless of the limit on --param max-inline-insns-single and --param max-inline-insns-auto. speedup so real it overrides the usual limits ⭐
  • large-function-insns — the limit specifying really large functions. For functions larger than this limit after inlining, inlining is constrained by --param large-function-growth. This parameter is useful primarily to avoid extreme compilation time caused by non-linear algorithms used by the back end. big function warning, compilation time said “chill” 😭
  • large-function-growth — specifies maximal growth of large function caused by inlining in percents. For example, parameter value 100 limits large function growth to 2.0 times the original size. growth cap, but make it percent 💅
  • large-unit-insns — the limit specifying large translation unit. Growth caused by inlining of units larger than this limit is limited by --param inline-unit-growth. For small units this might be too tight. For example, consider a unit consisting of function A that is inline and B that just calls A three times. If B is small relative to A, the growth of unit is 300\% and yet such inlining is very sane. For very large units consisting of small inlineable functions, however, the overall unit growth limit is needed to avoid exponential explosion of code size. Thus for smaller units, the size is increased to --param large-unit-insns before applying --param inline-unit-growth. translation-unit math is giving “it’s complicated” 🦋
  • lazy-modules — maximum number of concurrently open C++ module files when lazy loading. lazy loading but make it a limit 🌈
  • inline-unit-growth — specifies maximal overall growth of the compilation unit caused by inlining. For example, parameter value 20 limits unit growth to 1.2 times the original size. Cold functions (either marked cold via an attribute or by profile feedback) are not accounted into the unit size. cold functions don’t count toward the unit size, periodt 🧚
  • ipa-cp-unit-growth — specifies maximal overall growth of the compilation unit caused by interprocedural constant propagation. For example, parameter value 10 limits unit growth to 1.1 times the original size. IPA-CP said “small growth only” 🍑
  • ipa-cp-large-unit-insns — the size of translation unit that IPA-CP pass considers large. IPA-CP’s “large” threshold, iykyk 👑
  • large-stack-frame — the limit specifying large stack frames. While inlining the algorithm is trying to not grow past this limit too much. stack frame said “don’t make me huge” 😭
  • large-stack-frame-growth — specifies maximal growth of large stack frames caused by inlining in percents. For example, parameter value 1000 limits large stack frame growth to 11 times the original size. 11x stack frame growth is wild, ngl 💀
  • max-inline-insns-recursive, max-inline-insns-recursive-auto — specifies the maximum number of instructions an out-of-line copy of a self-recursive inline function can grow into by performing recursive inlining. --param max-inline-insns-recursive applies to functions declared inline. For functions not declared inline, recursive inlining happens only when -finline-functions (included in -O3) is enabled; --param max-inline-insns-recursive-auto applies instead. recursive inlining said “I can fix her” 🔁✨
  • max-inline-recursive-depth, max-inline-recursive-depth-auto — specifies the maximum recursion depth used for recursive inlining. --param max-inline-recursive-depth applies to functions declared inline. For functions not declared inline, recursive inlining happens only when -finline-functions (included in -O3) is enabled; --param max-inline-recursive-depth-auto applies instead. depth limit for the recursive girlies 🌀
  • min-inline-recursive-probability — recursive inlining is profitable only for function having deep recursion in average and can hurt for function having little recursion depth by increasing the prologue size or complexity of function body to other optimizers. When profile feedback is available (see -fprofile-generate) the actual recursion depth can be guessed from the probability that function recurses via a given call expression. This parameter limits inlining only to call expressions whose probability exceeds the given threshold (in percents). probability threshold: if it’s not likely, bestie, we don’t inline it 💅
  • early-inlining-insns — specify growth that the early inliner can make. In effect it increases the amount of inlining for code having a large abstraction penalty. early inliner gets a little room to cook 🍳
  • max-early-inliner-iterations — limit of iterations of the early inliner. This basically bounds the number of nested indirect calls the early inliner can resolve. Deeper chains are still handled by late inlining. early inliner can only go so deep; late inlining picks up the rest 🫶
  • comdat-sharing-probability — probability (in percent) that C++ inline function with comdat visibility are shared across multiple compilation units. comdat sharing, but probability-coded 💜
  • modref-max-bases, modref-max-refs, modref-max-accesses — specifies the maximal number of base pointers, references and accesses stored for a single function by mod/ref analysis. mod/ref storage caps: bases, refs, accesses, all accounted for 🎀
  • modref-max-tests — specifies the maxmal number of tests alias oracle can perform to disambiguate memory locations using the mod/ref information. This parameter ought to be bigger than --param modref-max-bases and --param modref-max-refs. (“maxmal” is the manpage’s word, not mine — we preserve the lore 🙈)
  • modref-max-depth — specifies the maximum depth of DFS walk used by modref escape analysis. Setting to 0 disables the analysis completely. setting it to 0 is the “off” switch, bestie — analysis disabled completely 💀
  • modref-max-escape-points — specifies the maximum number of escape points tracked by modref per SSA-name. escape points per SSA-name, tracked and capped 🦋
  • modref-max-adjustments — specifies the maximum number the access range is enlarged during modref dataflow analysis. access range enlargement cap during modref dataflow analysis ✨
  • profile-func-internal-id — a parameter to control whether to use function internal id in profile database lookup. If the value is 0, the compiler uses an id that is based on function assembler name and filename, which makes old profile data more tolerant to source changes such as function reordering etc. profile data staying tolerant to source changes is lowkey iconic 👑
  • min-vect-loop-bound — the minimum number of iterations under which loops are not vectorized when -ftree-vectorize is used. The number of iterations after vectorization needs to be greater than the value specified by this option to allow vectorization. loop vectorization said “not unless the iteration count is big enough” 🌈
  • gcse-cost-distance-ratio — scaling factor in calculation of maximum distance an expression can be moved by GCSE optimizations. This is currently supported only in the code hoisting pass. The bigger the ratio, the more aggressive code hoisting is with simple expressions, i.e., the expressions that have cost less than gcse-unrestricted-cost. Specifying 0 disables hoisting of simple expressions. bigger ratio = more aggressive hoisting for simple expressions; 0 says “no hoisting for you” 💅
  • gcse-unrestricted-cost — the cost threshold (roughly measured as the cost of one single typical machine instruction 🛠️) at which GCSE optimizations stop constraining how far an expression is allowed to travel. Lowkey only supported in the code hoisting pass rn. The lesser the cost, the more aggressive code hoisting gets — so set it to 0 and literally every expression can travel unrestricted distances. go off ✨
  • max-hoist-depth — how deep we search the dominator tree looking for expressions to hoist 🎀. This exists so the hoisting algorithm doesn't go quadratic on us (we're not doing that today, bestie). A value of 0 means the search is not limited, but fair warning: that may slow down compilation of huge functions 😭.
  • max-tail-merge-comparisons — the max amount of similar bbs we'll compare a bb against. Again: avoiding quadratic behavior in tree tail merging 🦋.
  • max-tail-merge-iterations — the max amount of iterations of the pass over the function. This one's here to cap compilation time in tree tail merging ⏳.
  • store-merging-allow-unaligned — lets the store merging pass introduce unaligned stores, but only if it's legal to do so 💅.
  • max-stores-to-merge — the max number of stores the store merging pass will attempt to merge into wider stores 🧚.
  • max-store-chains-to-track — the max number of store chains we'll track at the same time while trying to merge them into wider stores in the store merging pass 👑
  • max-stores-to-track — the max number of stores to track at the same time while attempting to merge them into wider stores in the store merging pass.
  • max-unrolled-insns — the max number of instructions a loop may have and still be unrolled. And if a loop does get unrolled, this parameter also determines how many times the loop code is unrolled 🔁.
  • max-average-unrolled-insns — same deal, but the instruction count is biased by the probabilities of their execution. If a loop is unrolled, this parameter also determines how many times the loop code is unrolled 🌸.
  • max-unroll-times — the max number of unrollings of a single loop. one loop, so many unrolls 💫
  • max-peeled-insns — the max number of instructions a loop may have and still be peeled. If a loop is peeled, this parameter also determines how many times the loop code is peeled 🍓.
  • max-peel-times — the max number of peelings of a single loop.
  • max-peel-branches — the max number of branches on the hot path through the peeled sequence 🔥.
  • max-completely-peeled-insns — the max number of insns of a completely peeled loop.
  • max-completely-peel-times — the max number of iterations of a loop for it to be suitable for complete peeling.
  • max-completely-peel-loop-nest-depth — the max depth of a loop nest that's suitable for complete peeling 🪆.
  • max-unswitch-insns — the max number of insns of an unswitched loop.
  • max-unswitch-level — the max number of branches unswitched in a single loop.
  • lim-expensive — the minimum cost of an expensive expression in loop invariant motion 💸.
  • min-loop-cond-split-prob — when FDO profile information is available, this specifies the minimum threshold for the probability of a semi-invariant condition statement to trigger a loop split 🎯.
  • iv-consider-all-candidates-bound — a bound on the number of induction variable candidates, below which all candidates get considered for each use in induction variable optimizations. Got more candidates than this? Then only the most relevant ones are considered, to dodge quadratic time complexity ⚡.
  • iv-max-considered-uses — the induction variable optimizations simply give up on loops containing more induction variable uses than this 🙈.
  • iv-always-prune-cand-set-bound — if the number of candidates in the set is smaller than this value, always try to remove unnecessary ivs from the set whenever a new one is added ✂️.
  • avg-loop-niter — average number of iterations of a loop.
  • dse-max-object-size — max size (in bytes 📏) of objects tracked bytewise by dead store elimination. Larger values may result in larger compilation times.
  • dse-max-alias-queries-per-store — max number of queries into the alias oracle per store. Larger values result in larger compilation times, and may result in more removed dead stores 🗑️.
  • scev-max-expr-size — a bound on the size of expressions used in the scalar evolutions analyzer. Large expressions slow the analyzer down 🐌.
  • scev-max-expr-complexity — a bound on the complexity of the expressions in the scalar evolutions analyzer. Complex expressions slow the analyzer down too 😮‍💨.
  • max-tree-if-conversion-phi-args — max number of arguments in a PHI that TREE if conversion supports — unless the loop is marked with simd pragma, then this doesn't apply 👀.
  • vect-max-version-for-alignment-checks — the max number of run-time checks that can be performed when doing loop versioning for alignment in the vectorizer.
  • vect-max-version-for-alias-checks — the max number of run-time checks that can be performed when doing loop versioning for alias in the vectorizer.
  • vect-max-peeling-for-alignment — the max number of loop peels to enhance access alignment for the vectorizer. A value of -1 means no limit 🚫.
  • max-iterations-to-track — the max number of iterations of a loop that the brute-force algorithm (the one analyzing loop iteration counts) tries to evaluate 🧮.
  • hot-bb-count-fraction — the denominator n of fraction 1/n of the maximal execution count of a basic block in the whole program that a basic block needs to at least have to be considered hot 🔥. Default is 10000, meaning a basic block counts as hot if its execution count is greater than 1/10000 of the maximal execution count. 0 means it is never considered hot. Used in non-LTO mode.
  • hot-bb-count-ws-permille — the number of most-executed permilles (ranging from 0 to 1000) of the profiled execution of the entire program that a basic block's execution count must be part of to be considered hot 🔥. Default is 990, meaning a basic block counts as hot if its execution count contributes to the upper 990 permilles — that's 99.0% — of the profiled execution of the entire program. 0 means it is never considered hot. Used in LTO mode.
  • hot-bb-frequency-fraction — the denominator n of fraction 1/n of the execution frequency of a function's entry block that a basic block of that function needs to at least have to be considered hot 🔥. Default is 1000, meaning a basic block is considered hot within a function if it's executed more frequently than 1/1000 of the frequency of that function's entry block. 0 means it is never considered hot.
  • unlikely-bb-count-fraction — the denominator n of fraction 1/n of the number of profiled runs of the entire program below which the execution count of a basic block must be in order for that basic block to be considered unlikely executed 🥶. Default is 20, meaning a basic block counts as unlikely executed if it's executed in fewer than 1/20 — 5% — of the program's runs. 0 means it is always considered unlikely executed.
  • max-predicted-iterations — the max number of loop iterations we predict statically 🔮. Super useful when a function contains one loop with a known bound and another loop with an unknown bound: the known iteration count gets predicted correctly, while the unknown count averages to roughly 10. Which means the loop without bounds looks artificially cold compared to the other one ❄️.
  • builtin-expect-probability — controls the probability of the expression having the specified value. Takes a percentage (i.e. 0 ... 100) as input 🎲.
  • builtin-string-cmp-inline-length — the max length of a constant string for a builtin string cmp call to be eligible for inlining 📏.
  • align-threshold — selects the fraction of the maximal frequency of executions of a basic block in a function for aligning that basic block 📐.
  • align-loop-iterations — a loop expected to iterate at least the selected number of iterations gets aligned 🔄.
  • tracer-dynamic-coverage, tracer-dynamic-coverage-feedback — this value limits superblock formation once the given percentage of executed instructions is covered 🎯. Keeps unnecessary code size expansion in check.

The tracer-dynamic-coverage-feedback parameter is used only when profile feedback is available. Real profiles (as opposed to statically estimated ones) are much less balanced, which allows the threshold to be a larger value 🌈.

  • tracer-max-code-growth — stops tail duplication once code growth has reached the given percentage 🛑. It's a pretty artificial limit, since most of the duplicates get eliminated later in cross jumping — so it may be set to much higher values than the code growth you actually want.
  • tracer-min-branch-ratio — stops reverse growth when the reverse probability of the best edge is less than this threshold (in percent) 📉.
  • tracer-min-branch-probability, tracer-min-branch-probability-feedback — stops forward growth if the best edge has a probability lower than this threshold.

Same energy as tracer-dynamic-coverage: two parameters are provided. tracer-min-branch-probability-feedback is used for compilation with profile feedback, while tracer-min-branch-probability is for compilation without it 💅. The value for compilation with profile feedback needs to be more conservative (higher) to make tracer effective.

  • stack-clash-protection-guard-size — okay so this one sets the size of the OS-provided stack guard as 2 raised to num bytes, bestie 💅. Higher values may reduce the number of explicit probes, but a value larger than the operating system provided guard will leave code vulnerable to stack clash style attacks. Not cute, don't do it.
  • stack-clash-protection-probe-interval — stack clash protection involves probing stack space as it's allocated, and this param controls the maximum distance between probes into the stack as 2 raised to num bytes 🔍. Higher values may reduce the number of explicit probes, but a value larger than the operating system provided guard will leave code vulnerable to stack clash style attacks. Same warning, same energy — keep it safe.
  • max-cse-path-length — the maximum number of basic blocks on a path that CSE considers, periodt ✨.
  • max-cse-insns — the maximum number of instructions CSE processes before flushing 🫶.
  • ggc-min-expand — GCC uses a garbage collector to manage its own memory allocation, and this parameter specifies the minimum percentage by which the garbage collector's heap should be allowed to expand between collections 💖. Tuning this may improve compilation speed; it has no effect on code generation.

The default is 30% + 70% * (RAM/1GB) with an upper bound of 100% when RAM >= 1GB. If getrlimit is available, the notion of "RAM" is the smallest of actual RAM and RLIMIT_DATA or RLIMIT_AS. If GCC is not able to calculate RAM on a particular platform, the lower bound of 30% is used. Setting this parameter and ggc-min-heapsize to zero causes a full collection to occur at every opportunity. This is extremely slow, but can be useful for debugging 🐌.

  • ggc-min-heapsize — minimum size of the garbage collector's heap before it begins bothering to collect garbage 🗑️. The first collection occurs after the heap expands by ggc-min-expand% beyond ggc-min-heapsize. Again, tuning this may improve compilation speed, and has no effect on code generation.

The default is the smaller of RAM/8, RLIMIT_RSS, or a limit that tries to ensure that RLIMIT_DATA or RLIMIT_AS are not exceeded, but with a lower bound of 4096 (four megabytes) and an upper bound of 131072 (128 megabytes) 💾. If GCC is not able to calculate RAM on a particular platform, the lower bound is used. Setting this parameter very large effectively disables garbage collection. Setting this parameter and ggc-min-expand to zero causes a full collection to occur at every opportunity.

  • max-reload-search-insns — the maximum number of instruction reload should look backward for an equivalent register, ngl 🔄. Increasing values mean more aggressive optimization, making the compilation time increase with probably slightly better performance.
  • max-cselib-memory-locations — the maximum number of memory locations cselib should take into account 🧠. Increasing values mean more aggressive optimization, making the compilation time increase with probably slightly better performance.
  • max-sched-ready-insns — the maximum number of instructions ready to be issued the scheduler should consider at any given time during the first scheduling pass ⏳. Increasing values mean more thorough searches, making the compilation time increase with probably little benefit. Lowkey not worth it most of the time.
  • max-sched-region-blocks — the maximum number of blocks in a region to be considered for interblock scheduling 🧩.
  • max-pipeline-region-blocks — the maximum number of blocks in a region to be considered for pipelining in the selective scheduler 🚿.
  • max-sched-region-insns — the maximum number of insns in a region to be considered for interblock scheduling ✨.
  • max-pipeline-region-insns — the maximum number of insns in a region to be considered for pipelining in the selective scheduler 🌈.
  • min-spec-prob — the minimum probability (in percents) of reaching a source block for interblock speculative scheduling 🎲.
  • max-sched-extend-regions-iters — the maximum number of iterations through CFG to extend regions 🔁. A value of 0 disables region extensions.
  • max-sched-insn-conflict-delay — the maximum conflict delay for an insn to be considered for speculative motion 💫.
  • sched-spec-prob-cutoff — the minimal probability of speculation success (in percents), so that speculative insns are scheduled 🎯.
  • sched-state-edge-prob-cutoff — the minimum probability an edge must have for the scheduler to save its state across it 🧚.
  • sched-mem-true-dep-cost — minimal distance (in CPU cycles) between store and load targeting same memory locations ⏱️.
  • selsched-max-lookahead — the maximum size of the lookahead window of selective scheduling 👀. It is a depth of search for available instructions.
  • selsched-max-sched-times — the maximum number of times that an instruction is scheduled during selective scheduling 🔂. This is the limit on the number of iterations through which the instruction may be pipelined.
  • selsched-insns-to-rename — the maximum number of best instructions in the ready list that are considered for renaming in the selective scheduler 🏷️.
  • sms-min-sc — the minimum value of stage count that swing modulo scheduler generates 🎛️.
  • max-last-value-rtl — the maximum size measured as number of RTLs that can be recorded in an expression in combiner for a pseudo register as last known value of that register 📝.
  • max-combine-insns — the maximum number of instructions the RTL combiner tries to combine 🧬.
  • integer-share-limit — small integer constants can use a shared data structure, reducing the compiler's memory usage and increasing its speed ⚡. This sets the maximum value of a shared integer constant.
  • ssp-buffer-size — the minimum size of buffers (i.e. arrays) that receive stack smashing protection when -fstack-protector is used 🛡️.
  • min-size-for-stack-sharing — the minimum size of variables taking part in stack slot sharing when not optimizing 📦.
  • max-jump-thread-duplication-stmts — maximum number of statements allowed in a block that needs to be duplicated when threading jumps 🧵.
  • max-fields-for-field-sensitive — maximum number of fields in a structure treated in a field sensitive manner during pointer analysis 🔬.
  • prefetch-latency — estimate on average number of instructions that are executed before prefetch finishes 🏃‍♀️. The distance prefetched ahead is proportional to this constant. Increasing this number may also lead to less streams being prefetched (see simultaneous-prefetches).
  • simultaneous-prefetches — maximum number of prefetches that can run at the same time 🌀.
  • l1-cache-line-size — the size of cache line in L1 data cache, in bytes 📏.
  • l1-cache-size — the size of L1 data cache, in kilobytes 💾.
  • l2-cache-size — the size of L2 data cache, in kilobytes 💽.
  • prefetch-dynamic-strides — whether the loop array prefetch pass should issue software prefetch hints for strides that are non-constant 🤔. In some cases this may be beneficial, though the fact the stride is non-constant may make it hard to predict when there is clear benefit to issuing these hints.

Set to 1 if the prefetch hints should be issued for non-constant strides. Set to 0 if prefetch hints should be issued only for strides that are known to be constant and below prefetch-minimum-stride 👑.

  • prefetch-minimum-stride — minimum constant stride, in bytes, to start using prefetch hints for 📐. If the stride is less than this threshold, prefetch hints will not be issued.

This setting is useful for processors that have hardware prefetchers, in which case there may be conflicts between the hardware prefetchers and the software prefetchers. If the hardware prefetchers have a maximum stride they can handle, it should be used here to improve the use of software prefetchers.

A value of -1 means we don't have a threshold and therefore prefetch hints can be issued for any constant stride.

This setting is only useful for strides that are known and constant ✨.

  • destructive-interference-size, constructive-interference-size — the values for the C++17 variables std::hardware_destructive_interference_size and std::hardware_constructive_interference_size 🧸. The destructive interference size is the minimum recommended offset between two independent concurrently-accessed objects; the constructive interference size is the maximum recommended size of contiguous memory accessed together. Typically both will be the size of an L1 cache line for the target, in bytes. For a generic target covering a range of L1 cache line sizes, typically the constructive interference size will be the small end of the range and the destructive size will be the large end.

The destructive interference size is intended to be used for layout, and thus has ABI impact 🚨. The default value is not expected to be stable, and on some targets varies with -mtune, so use of this variable in a context where ABI stability is important, such as the public interface of a library, is strongly discouraged; if it is used in that context, users can stabilize the value using this option.

The constructive interference size is less sensitive, as it is typically only used in a static_assert to make sure that a type fits within a cache line.

See also -Winterference-size 💜.

  • loop-interchange-max-num-stmts — the maximum number of stmts in a loop to be interchanged 🔄.
  • loop-interchange-stride-ratio — the minimum ratio between stride of two loops for interchange to be profitable 💰.
  • min-insn-to-prefetch-ratio — the minimum ratio between the number of instructions and the number of prefetches before prefetching in a loop gets switched on ✨
  • prefetch-min-insn-to-mem-ratio — same vibe, different count: the minimum ratio between the number of instructions and the number of memory references needed to enable prefetching in a loop 💅
  • use-canonical-types — whether the compiler should use the "canonical" type system. Bestie, this should always be 1, which uses a more efficient internal mechanism for comparing types in C++ and Objective-C++. But — if bugs in the canonical type system are making your compiles fail, set this value to 0 to disable canonical types 🫶
  • switch-conversion-max-branch-ratio — Switch initialization conversion refuses to create arrays that are bigger than switch-conversion-max-branch-ratio times the number of branches in the switch. no cap, it just won't go there 💀
  • max-partial-antic-length — maximum length of the partial antic set computed during the tree partial redundancy elimination optimization (-ftree-pre) when optimizing at -O3 and above. For some sorts of source code, the enhanced partial redundancy elimination optimization can literally run away and consume ALL the memory available on the host machine 😭 so this parameter sets a limit on the length of the sets that are computed, which prevents that runaway behavior. Setting a value of 0 for this parameter allows an unlimited set length (you're on your own then 🙈).
  • rpo-vn-max-loop-depth — maximum loop depth that is value-numbered optimistically. When the limit hits, the innermost rpo-vn-max-loop-depth loops and the outermost loop in the loop nest get value-numbered optimistically and the remaining ones don't ✨
  • sccvn-max-alias-queries-per-access — maximum number of alias-oracle queries we perform when looking for redundancies for loads and stores. If this limit is hit, the search is aborted and the load or store is not considered redundant. The number of queries is algorithmically limited to the number of stores on all paths from the load to the function entry 🔥
  • ira-max-loops-num — IRA uses regional register allocation by default. If a function contains more loops than the number given by this parameter, only at most that number of the most frequently-executed loops form regions for regional register allocation 👑
  • ira-max-conflict-table-size — okay so IRA uses a sophisticated algorithm to compress the conflict table, but the table can still require excessive amounts of memory for huge functions. If the conflict table for a function could be more than the size in MB given by this parameter, the register allocator instead uses a faster, simpler, and lower-quality algorithm that does not require building a pseudo-register conflict table. trade-off city 💀
  • ira-loop-reserved-regs — IRA can be used to evaluate more accurate register pressure in loops for decisions to move loop invariants (see -O3). The number of available registers reserved for some other purposes is given by this parameter. Default of the parameter is the best found from numerous experiments 🧚
  • ira-consider-dup-in-all-alts — makes IRA consider matching constraint (duplicated operand number) heavily in all available alternatives for preferred register class. If it is set as zero, it means IRA only respects the matching constraint when it's in the only available alternative with an appropriate register class. Otherwise, it means IRA will check all available alternatives for preferred register class even if it has found some choice with an appropriate register class and respect the found qualified matching constraint 💖
  • lra-inheritance-ebb-probability-cutoff — LRA tries to reuse values reloaded in registers in subsequent insns. This optimization is called inheritance. EBB is used as a region to do this optimization. The parameter defines a minimal fall-through edge probability in percentage used to add BB to inheritance EBB in LRA. The default value was chosen from numerous runs of SPEC2000 on x86-64 ⭐
  • loop-invariant-max-bbs-in-loop — loop invariant motion can be very expensive, both in compilation time and in amount of needed compile-time memory, with very large loops. Loops with more basic blocks than this parameter won't have loop invariant motion optimization performed on them 🙅‍♀️
  • loop-max-datarefs-for-datadeps — building data dependencies is expensive for very large loops. This parameter limits the number of data references in loops that are considered for data dependence analysis. These large loops aren't handled by the optimizations using loop data dependencies 💅
  • max-vartrack-size — sets a maximum number of hash table slots to use during variable tracking dataflow analysis of any function. If this limit is exceeded with variable tracking at assignments enabled, analysis for that function is retried without it, after removing all debug insns from the function. If the limit is exceeded even without debug insns, var tracking analysis is completely disabled for the function. Setting the parameter to zero makes it unlimited 🌈
  • max-vartrack-expr-depth — sets a maximum number of recursion levels when attempting to map variable names or debug temporaries to value expressions. This trades compilation time for more complete debug information. If this is set too low, value expressions that are available and could be represented in debug information may end up not being used; setting this higher may enable the compiler to find more complex debug expressions, but compile time and memory use may grow 😭
  • max-debug-marker-count — sets a threshold on the number of debug markers (e.g. begin stmt markers) to avoid complexity explosion at inlining or expanding to RTL. If a function has more such gimple stmts than the set limit, such stmts will be dropped from the inlined copy of a function, and from its RTL expansion 🦋
  • min-nondebug-insn-uid — use uids starting at this parameter for nondebug insns. The range below the parameter is reserved exclusively for debug insns created by -fvar-tracking-assignments, but debug insns may get (non-overlapping) uids above it if the reserved range is exhausted 🌸
  • ipa-sra-ptr-growth-factor — IPA-SRA replaces a pointer to an aggregate with one or more new parameters only when their cumulative size is less or equal to ipa-sra-ptr-growth-factor times the size of the original pointer parameter ✨
  • ipa-sra-max-replacements — maximum pieces of an aggregate that IPA-SRA tracks. As a consequence, it is also the maximum number of replacements of a formal parameter 🎀
  • sra-max-scalarization-size-Ospeed
  • sra-max-scalarization-size-Osize — the two Scalar Reduction of Aggregates passes (SRA and IPA-SRA) aim to replace scalar parts of aggregates with uses of independent scalar variables. These parameters control the maximum size, in storage units, of aggregate which is considered for replacement when compiling for speed (sra-max-scalarization-size-Ospeed) or size (sra-max-scalarization-size-Osize) respectively 🔥
  • sra-max-propagations — the maximum number of artificial accesses that Scalar Replacement of Aggregates (SRA) will track, per one local variable, in order to facilitate copy propagation 💜
  • tm-max-aggregate-size — when making copies of thread-local variables in a transaction, this parameter specifies the size in bytes after which variables are saved with the logging functions as opposed to save/restore code sequence pairs. This option only applies when using -fgnu-tm 👑
  • graphite-max-nb-scop-params — to avoid exponential effects in the Graphite loop transforms, the number of parameters in a Static Control Part (SCoP) is bounded. A value of zero can be used to lift the bound. A variable whose value is unknown at compilation time and defined outside a SCoP is a parameter of the SCoP 🌟
  • loop-block-tile-size — loop blocking or strip mining transforms, enabled with -floop-block or -floop-strip-mine, strip mine each loop in the loop nest by a given number of iterations. The strip length can be changed using the loop-block-tile-size parameter 🧚
  • ipa-jump-function-lookups — specifies number of statements visited during jump function offset discovery 💫
  • ipa-cp-value-list-size — IPA-CP attempts to track all possible values and types passed to a function's parameter in order to propagate them and perform devirtualization. ipa-cp-value-list-size is the maximum number of values and types it stores per one formal parameter of a function 🍓
  • ipa-cp-eval-threshold — IPA-CP calculates its own score of cloning profitability heuristics and performs those cloning opportunities with scores that exceed ipa-cp-eval-threshold 💅
  • ipa-cp-max-recursive-depth — maximum depth of recursive cloning for self-recursive function 🌀
  • ipa-cp-min-recursive-probability — recursive cloning only when the probability of call being executed exceeds the parameter 🫶
  • ipa-cp-profile-count-base — when using -fprofile-use option, IPA-CP will consider the measured execution count of a call graph edge at this percentage position in their histogram as the basis for its heuristics calculation 📊
  • ipa-cp-recursive-freq-factor — the number of times interprocedural copy propagation expects recursive functions to call themselves 🔁
  • ipa-cp-recursion-penalty — percentage penalty the recursive functions will receive when they are evaluated for cloning 😬
  • ipa-cp-single-call-penalty — percentage penalty functions containing a single call to another function will receive when they are evaluated for cloning 💀
  • ipa-max-agg-items — okay so IPA-CP can also propagate a bunch of scalar values that got passed inside an aggregate 💅 and this param caps the max number of those values per one parameter. No cap? chaos. We love a limit.
  • ipa-cp-loop-hint-bonus — when IPA-CP figures out that a cloning candidate would make the number of iterations of a loop known, it literally adds a bonus of ipa-cp-loop-hint-bonus to that candidate's profitability score ✨ like giving it extra credit for being helpful.
  • ipa-max-loop-predicates — the max number of different predicates IPA will use to describe when loops in a function have known properties. Keeping the receipts to a reasonable number, bestie 🧾
  • ipa-max-aa-steps — during its analysis of function bodies, IPA-CP uses alias analysis to track the values pointed to by function parameters. But bestie, it is not about to spend forever analyzing huge functions — so after examining ipa-max-aa-steps statements that modify memory, it gives up and considers all memory clobbered 💀 iykyk, it's a timeout but for memory.
  • ipa-max-switch-predicate-bounds — maximal number of boundary endpoints of case ranges in a switch statement. If a switch exceeds this limit, IPA-CP will not construct the cloning cost predicate (the thing used to estimate cloning benefit) for the default case of that switch. Sorry default case, you're on your own 🙈
  • ipa-max-param-expr-ops — IPA-CP will analyze a conditional statement that references some function parameter, to estimate the benefit of cloning on a certain constant value. But if the number of operations in a parameter expression exceeds ipa-max-param-expr-ops, the expression gets treated as a complicated one and is just not handled by IPA analysis 🫠 too much going on, respectfully.
  • lto-partitions — specify the desired number of partitions produced during WHOPR compilation. The number of partitions should exceed the number of CPUs used for compilation. More partitions than CPUs, got it 👑
  • lto-min-partition — size of the minimal partition for WHOPR (in estimated instructions). This is the anti-chaos setting: it prevents the expense of splitting very small programs into way too many partitions 🎀
  • lto-max-partition — size of the max partition for WHOPR (in estimated instructions). It provides an upper bound for the individual size of a partition, and it's meant to be used only with balanced partitioning. Read the fine print bestie ✨
  • lto-max-streaming-parallelism — maximal number of parallel processes used for LTO streaming. That's the cap on the parallel vibes 🔥
  • cxx-max-namespaces-for-diagnostic-help — the max number of namespaces to consult for suggestions when C++ name lookup fails for an identifier. So when you typo something, the compiler will dig through this many namespaces looking for what you meant 😭 helpful queen.
  • sink-frequency-threshold — the max relative execution frequency (in percents) of the target block relative to a statement's original block, which is what allows statement sinking of a statement. Larger numbers = more aggressive statement sinking. And a small positive adjustment gets applied for statements with memory operands, because those are even more profitable to sink 💸 we love an optimized little guy.
  • max-stores-to-sink — the max number of conditional store pairs that can be sunk. Set it to 0 if either vectorization (-ftree-vectorize) or if-conversion (-ftree-loop-if-convert) is disabled. Just zero it out, no cap.
  • case-values-threshold — the smallest number of different values for which it's best to use a jump-table instead of a tree of conditional branches. If the value is 0, use the default for the machine 🖥️ let the machine decide, honestly.
  • jump-table-max-growth-ratio-for-size — the max code size growth ratio when expanding into a jump table (in percent). This one's the param used when optimizing for size 🎀
  • jump-table-max-growth-ratio-for-speed — same deal: the max code size growth ratio when expanding into a jump table (in percent), but this is the param used when optimizing for speed 🔥
  • tree-reassoc-width — set the max number of instructions executed in parallel in a reassociated tree. This parameter overrides the target dependent heuristics used by default, but only if it has a non zero value. Zero means "nah, do your thing" ✨
  • sched-pressure-algorithm — choose between the two available implementations of -fsched-pressure 👑
    • Algorithm 1 is the original implementation and is the more likely one to prevent instructions from being reordered.
    • Algorithm 2 was designed as a compromise between the relatively conservative approach of algorithm 1 and the rather aggressive approach of the default scheduler. It relies more heavily on having a regular register file and accurate register pressure classes.

See haifa-sched.cc in the GCC sources for more details — the lore is all there 📖 And the default choice depends on the target.

  • max-slsr-cand-scan — set the max number of existing candidates that get considered when seeking a basis for a new straight-line strength reduction candidate. Scanning the options, not the whole timeline 💅
  • asan-globals — enable buffer overflow detection for global objects. This kind of protection is enabled by default if you're using -fsanitize=address. To disable global objects protection, use --param asan-globals=0 🛡️
  • asan-stack — enable buffer overflow detection for stack objects. Enabled by default when using -fsanitize=address. To disable stack protection, use the --param asan-stack=0 option.
  • asan-instrument-reads — enable buffer overflow detection for memory reads. Enabled by default when using -fsanitize=address. To disable memory reads protection, use --param asan-instrument-reads=0 👀
  • asan-instrument-writes — enable buffer overflow detection for memory writes. Enabled by default when using -fsanitize=address. To disable memory writes protection, use the --param asan-instrument-writes=0 option ✍️
  • asan-memintrin — enable detection for built-in functions. Enabled by default when using -fsanitize=address. To disable built-in functions protection, use --param asan-memintrin=0 🧚
  • asan-use-after-return — enable detection of use-after-return. Enabled by default when using the -fsanitize=address option. To disable it, use --param asan-use-after-return=0.
Note: by default the check is disabled at run time. To enable it, add "detect_stack_use_after_return=1" to the environment variable ASAN_OPTIONS. It's giving "off by default, opt in bestie" 🙈
  • asan-instrumentation-with-call-threshold — if the number of memory accesses in the function being instrumented is greater than or equal to this number, use callbacks instead of inline checks. E.g. to disable inline code, use --param asan-instrumentation-with-call-threshold=0 📞
  • hwasan-instrument-stack — enable hwasan instrumentation of statically sized stack-allocated variables. This kind of instrumentation is enabled by default when using -fsanitize=hwaddress and disabled by default when using -fsanitize=kernel-hwaddress. To disable stack instrumentation, use --param hwasan-instrument-stack=0, and to enable it, use --param hwasan-instrument-stack=1 🦋
  • hwasan-random-frame-tag — when using stack instrumentation, decide tags for stack variables using a deterministic sequence beginning at a random tag for each frame. With this parameter unset, tags are chosen using the same sequence but beginning from 1. Enabled by default for -fsanitize=hwaddress and unavailable for -fsanitize=kernel-hwaddress. To disable it, use --param hwasan-random-frame-tag=0 🎲
  • hwasan-instrument-allocas — enable hwasan instrumentation of dynamically sized stack-allocated variables. Enabled by default when using -fsanitize=hwaddress and disabled by default when using -fsanitize=kernel-hwaddress. To disable instrumentation of such variables, use --param hwasan-instrument-allocas=0, and to enable it, use --param hwasan-instrument-allocas=1 ✨
  • hwasan-instrument-reads — enable hwasan checks on memory reads. Instrumentation of reads is enabled by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. To disable checking memory reads, use --param hwasan-instrument-reads=0 👑
  • hwasan-instrument-writes — enable hwasan checks on memory writes. Instrumentation of writes is enabled by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. To disable checking memory writes, use --param hwasan-instrument-writes=0 💅
  • hwasan-instrument-mem-intrinsics — enable hwasan instrumentation of builtin functions. Instrumentation of these builtin functions is enabled by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. To disable instrumentation of builtin functions, use --param hwasan-instrument-mem-intrinsics=0 🧚
  • use-after-scope-direct-emission-threshold — if the size of a local variable in bytes is smaller than or equal to this number, directly poison (or unpoison) shadow memory instead of using run-time callbacks 🍓 small enough to just do it ourselves.
  • tsan-distinguish-volatile — emit special instrumentation for accesses to volatiles. Volatile girlies get their own special treatment ✨
  • tsan-instrument-func-entry-exit — emit instrumentation calls to __tsan_func_entry() and __tsan_func_exit(). In and out, both instrumented 🚪
  • max-fsm-thread-path-insns — max number of instructions to copy when duplicating blocks on a finite state automaton jump thread path. Copy smart, not a lot 💅
  • max-fsm-thread-length — max number of basic blocks on a jump thread path. Keep the thread cute and short 🎀
  • threader-debug — threader-debug=[none|all] enables verbose dumping of the threader solver. So you can actually see what it's doing 👀
  • parloops-chunk-size — chunk size of the omp schedule for loops parallelized by parloops. Chunk it up 🍫
  • parloops-schedule — schedule type of the omp schedule for loops parallelized by parloops (static, dynamic, guided, auto, runtime). Pick your vibe, all five are valid 🔥
  • parloops-min-per-thread — the minimum number of iterations per thread of an innermost parallelized loop for which the parallelized variant is preferred over the single threaded one. And heads up bestie: for a parallelized loop nest, the minimum number of iterations of the outermost loop per thread is two 👑 two or nothing.
  • max-ssa-name-query-depth — the max recursion depth when we're querying properties of SSA names in things like fold routines. One level of recursion = following a use-def chain. 🌀
  • max-speculative-devirt-maydefs — the max number of may-defs we analyze when hunting for a must-def that specifies the dynamic type of an object invoking a virtual call we might be able to devirtualize speculatively. 🔍
  • max-vrp-switch-assertions — the max number of assertions to add along the default edge of a switch statement during VRP. 🎯
  • evrp-sparse-threshold — max number of basic blocks before EVRP starts using a sparse cache. 🧊
  • evrp-mode — specifies the mode Early VRP should operate in. 🎛️
  • vrp1-mode — specifies the mode VRP pass 1 should operate in. 1️⃣
  • vrp2-mode — specifies the mode VRP pass 2 should operate in. 2️⃣
  • ranger-debug — specifies the type of debug output to be issued for ranges. 🐞
  • evrp-switch-limit — the max number of switch cases before EVRP just ignores a switch. 🙈
  • unroll-jam-min-percent — the minimum percentage of memory references that must be optimized away for the unroll-and-jam transformation to be considered profitable. 💸
  • unroll-jam-max-unroll — the max number of times the outer loop should be unrolled by the unroll-and-jam transformation. 🔁
  • max-rtl-if-conversion-unpredictable-cost — max permissible cost for the sequence that would be generated by the RTL if-conversion pass for a branch that's considered unpredictable. 🎢
  • max-variable-expansions-in-unroller — if -fvariable-expansion-in-unroller is used, this is the max number of times that an individual variable will be expanded during loop unrolling. 🫧
  • partial-inlining-entry-probability — maximum probability of the entry BB of a split region (in percent relative to the entry BB of the function) to make partial inlining happen. 🎲
  • max-tracked-strlens — max number of strings for which the strlen optimization pass will track string lengths. 🧵
  • gcse-after-reload-partial-fraction — the threshold ratio for performing partial redundancy elimination after reload. ⚖️
  • gcse-after-reload-critical-fraction — the threshold ratio of critical edges execution count that permits performing redundancy elimination after reload. 🚦
  • max-loop-header-insns — the max number of insns in a loop header duplicated by the copy loop headers pass. 📦
  • vect-epilogues-nomask — enable loop epilogue vectorization using a smaller vector size. 🧬
  • vect-partial-vector-usage — controls when the loop vectorizer considers using partial vector loads and stores as an alternative to falling back to scalar code. 0 stops the vectorizer from ever using partial vector loads and stores. 1 allows partial vector loads and stores if vectorization removes the need for the code to iterate. 2 allows partial vector loads and stores in all loops. The parameter only has an effect on targets that support partial vector loads and stores. 🧩
  • vect-inner-loop-cost-factor — the max factor which the loop vectorizer applies to the cost of statements in an inner loop relative to the loop being vectorized. The factor applied is the maximum of the estimated number of iterations of the inner loop and this parameter. The default value of this parameter is 50. 📐
  • vect-induction-float — enable loop vectorization of floating point inductions. 🌊
  • avoid-fma-max-bits — max number of bits for which we avoid creating FMAs. 🚫
  • sms-loop-average-count-threshold — a threshold on the average loop count considered by the swing modulo scheduler. 🎠
  • sms-dfa-history — the number of cycles the swing modulo scheduler considers when checking conflicts using DFA. 🕰️
  • graphite-allow-codegen-errors — whether codegen errors should be ICEs when -fchecking. 🧨
  • sms-max-ii-factor — a factor for tuning the upper bound that the swing modulo scheduler uses for scheduling a loop. 📈
  • lra-max-considered-reload-pseudos — the max number of reload pseudos which are considered during spilling a non-reload pseudo. 🧳
  • max-pow-sqrt-depth — max depth of sqrt chains to use when synthesizing exponentiation by a real constant. 🧮
  • max-dse-active-local-stores — max number of active local stores in RTL dead store elimination. 🗃️
  • asan-instrument-allocas — enable asan allocas/VLAs protection. 🛡️
  • max-iterations-computation-cost — bound on the cost of an expression to compute the number of iterations. 🧾
  • max-isl-operations — max number of isl operations; 0 means unlimited. ♾️
  • graphite-max-arrays-per-scop — max number of arrays per scop. 🧺
  • max-vartrack-reverse-op-size — max size of loc list for which reverse ops should be added. ↩️
  • fsm-scale-path-stmts — scale factor to apply to the number of statements in a threading path when comparing to the number of (scaled) blocks. 📊
  • uninit-control-dep-attempts — max number of nested calls to search for control dependencies during uninitialized variable analysis. 🕵️‍♀️
  • fsm-scale-path-blocks — scale factor to apply to the number of blocks in a threading path when comparing to the number of (scaled) statements. 🧱
  • sched-autopref-queue-depth — hardware autoprefetcher scheduler model control flag. Number of lookahead cycles the model looks into; at ' ' only enable instruction sorting heuristic. 🔭
  • loop-versioning-max-inner-insns — the max number of instructions that an inner loop can have before the loop versioning pass considers it too big to copy. ✂️
  • loop-versioning-max-outer-insns — the max number of instructions that an outer loop can have before the loop versioning pass considers it too big to copy, discounting any instructions in inner loops that directly benefit from versioning. 🧵
  • ssa-name-def-chain-limit — the max number of SSA_NAME assignments to follow in determining a property of a variable such as its value. This limits the number of iterations or recursive calls GCC performs when optimizing certain statements or when determining their validity prior to issuing diagnostics. 🔗
  • store-merging-max-size — max size of a single store merging region in bytes. 📏
  • hash-table-verification-limit — the number of elements for which hash table verification is done for each searched element. 🔎
  • max-find-base-term-values — max number of VALUEs handled during a single find_base_term call. 🧮
  • analyzer-max-enodes-per-program-point — the max number of exploded nodes per program point within the analyzer, before terminating analysis of that point. 💥
  • analyzer-max-constraints — the max number of constraints per state. 🧷
  • analyzer-min-snodes-for-call-summary — the minimum number of supernodes within a function for the analyzer to consider summarizing its effects at call sites. 🪄
  • analyzer-max-enodes-for-full-dump — the max depth of exploded nodes that should appear in a dot dump before switching to a less verbose format. 🌳
  • analyzer-max-recursion-depth — the max number of times a callsite can appear in a call stack within the analyzer, before terminating analysis of a call that would recurse deeper. 🪜
  • analyzer-max-svalue-depth — the max depth of a symbolic value, before approximating the value as unknown. 🌫️
  • analyzer-max-infeasible-edges — the max number of infeasible edges to reject before declaring a diagnostic as infeasible. 🚧
  • gimple-fe-computed-hot-bb-threshold — the number of executions of a basic block which is considered hot. The parameter is used only in GIMPLE FE. 🔥
  • analyzer-bb-explosion-factor — the max number of 'after supernode' exploded nodes within the analyzer per supernode, before terminating analysis. 💣
  • ranger-logical-depth — max depth of logical expression evaluation ranger will look through when evaluating outgoing edge ranges. 🧠
  • relation-block-limit — max number of relations the oracle will register in a basic block. 🧾
  • min-pagesize — minimum page size for warning purposes. 📄
  • openacc-kernels — specify mode of OpenACC kernels constructs handling. With --param=openacc-kernels=decompose, OpenACC kernels constructs are decomposed into parts, a sequence of compute constructs, each then handled individually. This is work in progress. With --param=openacc-kernels=parloops, OpenACC kernels constructs are handled by the parloops pass, en bloc. This is the current default. 🌊
  • openacc-privatization — specify mode of OpenACC privatization diagnostics for -fopt-info-omp-note and applicable -fdump-tree-*-details. With --param=openacc-privatization=quiet, don't diagnose. This is the current default. With --param=openacc-privatization=noisy, do diagnose. 🔔

And on AArch64 targets, these choices of name are also available 👑✨:

  • aarch64-sve-compare-costs — when vectorizing for SVE, consider using "unpacked" vectors for smaller elements and use the cost model to pick the cheapest approach. Also use the cost model to choose between SVE and Advanced SIMD vectorization. Using unpacked vectors includes storing smaller elements in larger containers and accessing elements with extending loads and truncating stores. 🧬
  • aarch64-float-recp-precision — the number of Newton iterations for calculating the reciprocal for float type. The precision of division is proportional to this param when division approximation is enabled. The default value is 1. 🍓
  • aarch64-double-recp-precision — how many Newton iterations we do when computing the reciprocal of a double. Basically, when division approximation is turned on, the precision of your division is proportional to this param. Default? 2. ✨
  • aarch64-autovec-preference — this one forces a whole ISA selection strategy for auto-vectorization, bestie. It takes values 0 through 4, inclusive:
    • 0 — just use the default heuristics, no drama.
    • 1 — Advanced SIMD only for auto-vectorization, periodt.
    • 2 — SVE only for auto-vectorization, and nothing else.
    • 3 — both Advanced SIMD and SVE are on the table, but Advanced SIMD wins when the costs come out equal.
    • 4 — both Advanced SIMD and SVE again, but this time SVE gets the tiebreak when the costs are deemed equal.

The default value is 0.

  • aarch64-loop-vect-issue-rate-niters — okay so the tuning for some AArch64 CPUs lowkey tries to weigh both latencies and issue rates when it's deciding whether a loop should get vectorized with SVE, vectorized with Advanced SIMD, or just... not vectorized at all. If you set this parameter to n, GCC will skip that heuristic entirely for loops that are known to execute in fewer than n Advanced SIMD iterations.
  • aarch64-vect-unroll-limit — the vectorizer looks at whatever tuning info it has to figure out whether unrolling the main vectorized loop would actually be worth it, and by how much. This parameter sets the upper bound on how much the vectorizer will unroll that main loop. Default is four. 🎀

The following choices of name are available on i386 and x86_64 targets:

  • x86-stlf-window-ninsns — the instruction count above which an STFL stall penalty can be compensated for. iykyk 💅

🌸 PROGRAM INSTRUMENTATION OPTIONS 🌸

GCC has a whole lil collection of command-line options that control adding run-time instrumentation to the code it normally generates, and honestly? Obsessed. 🫶 Like, one purpose of instrumentation is to collect profiling statistics — for finding program hot spots, for code coverage analysis, or for profile-guided optimizations. Another whole class of program instrumentation is adding run-time checking to catch programming errors like invalid pointer dereferences or out-of-bounds array accesses, plus deliberately hostile attacks such as stack smashing or C++ vtable hijacking. (Not cute. Very much not cute. 💀) And there's also a general hook you can use to implement other forms of tracing or function-level instrumentation for debug or program analysis purposes. Main character energy for your binary tbh.

  • -p, -pg — generate extra code that writes profile information suitable for the analysis program prof (for -p) or gprof (for -pg). Bestie, listen: you must use this option when compiling the source files you want data about, and you must also use it when linking. Both times. No cap.

You can use the function attribute no_instrument_function to suppress profiling of individual functions when compiling with these options. 🦋

  • -fprofile-arcs — adds code so that program flow arcs get instrumented. During execution the program records how many times each branch and call is executed and how many times it's taken or returns. On targets that support constructors with priority support, profiling properly handles constructors, destructors and C++ constructors (and destructors) of classes which are used as a type of a global variable. ✨

When the compiled program exits it saves this data to a file called auxname.gcda for each source file. That data may be used for profile-directed optimizations (-fbranch-probabilities), or for test coverage analysis (-ftest-coverage). Each object file's auxname is generated from the name of the output file, if explicitly specified and it's not the final executable, otherwise it's the basename of the source file. In both cases any suffix is removed (e.g. foo.gcda for input file dir/foo.c, or dir/foo.gcda for output file specified as -o dir/foo.o).

Heads up 🫶 — note that if a command line directly links source files, the corresponding .gcda files will be prefixed with the unsuffixed name of the output file. E.g. gcc a.c b.c -o binary would generate binary-a.gcda and binary-b.gcda files.
  • --coverage — this option is used to compile and link code instrumented for coverage analysis. It's a synonym for -fprofile-arcs -ftest-coverage (when compiling) and -lgcov (when linking). See the documentation for those options for more details. 💖
    • Compile the source files with -fprofile-arcs plus optimization and code generation options. For test coverage analysis, use the additional -ftest-coverage option. You do not need to profile every source file in a program.
    • Compile the source files additionally with -fprofile-abs-path to create absolute path names in the .gcno files. This allows gcov to find the correct sources in projects where compilations occur with different working directories.
    • Link your object files with -lgcov or -fprofile-arcs (the latter implies the former).
    • Run the program on a representative workload to generate the arc profile information. This may be repeated any number of times. You can run concurrent instances of your program, and provided that the file system supports locking, the data files will be correctly updated. Unless a strict ISO C dialect option is in effect, fork calls are detected and correctly handled without double counting.

Moreover, an object file can be recompiled multiple times and the corresponding .gcda file merges as long as the source file and the compiler options are unchanged. 🌈

  • For profile-directed optimizations, compile the source files again with the same optimization and code generation options plus -fbranch-probabilities.
  • For test coverage analysis, use gcov to produce human readable information from the .gcno and .gcda files. Refer to the gcov documentation for further information.

With -fprofile-arcs, for each function of your program GCC creates a program flow graph, then finds a spanning tree for the graph. Only arcs that are not on the spanning tree have to be instrumented: the compiler adds code to count the number of times that these arcs are executed. When an arc is the only exit or only entrance to a block, the instrumentation code can be added to the block; otherwise, a new basic block must be created to hold the instrumentation code. (Lowkey so elegant, I can't. 😭)

  • -ftest-coverage — produce a notes file that the gcov code-coverage utility can use to show program coverage. Each source file's note file is called auxname.gcno. Refer to the -fprofile-arcs option above for a description of auxname and instructions on how to generate test coverage data. Coverage data matches the source files more closely if you do not optimize. 🎀
  • -fprofile-abs-path — automatically converts relative source file names to absolute path names in the .gcno files. This allows gcov to find the correct sources in projects where compilations occur with different working directories. Slay.
  • *-fprofile-dir=path* — sets the directory to search for the profile data files in to path. This option affects only the profile data generated by -fprofile-generate, -ftest-coverage, -fprofile-arcs and used by -fprofile-use and -fbranch-probabilities and its related options. Both absolute and relative paths can be used. By default, GCC uses the current directory as path, thus the profile data file appears in the same directory as the object file. In order to prevent the file name clashing, if the object file name is not an absolute path, we mangle the absolute path of the sourcename.gcda file and use it as the file name of a .gcda file. See details about the file naming in -fprofile-arcs. See similar option -fprofile-note. 💅

When an executable is run in a massive parallel environment, it's recommended to save profile to different folders. That can be done with variables in path that are exported during run-time:

  • %p — process ID.
  • %q{VAR} — value of environment variable VAR.
  • -fprofile-generate, -fprofile-generate=path — enable options usually used for instrumenting an application to produce a profile useful for later recompilation with profile feedback based optimization. You **must use -fprofile-generate both when compiling and when linking your program.

The following options are enabled: -fprofile-arcs, -fprofile-values, -finline-functions, and -fipa-bit-cp.

If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.

To optimize the program based on the collected profile information, use -fprofile-use. 🔥

  • -fprofile-info-section, -fprofile-info-section=name — register the profile information in the specified section instead of using a constructor/destructor. The section name is name if it's specified, otherwise the section name defaults to ".gcov_info". A pointer to the profile information generated by -fprofile-arcs is placed in the specified section for each translation unit. This option disables the profile information registration through a constructor and it disables the profile information processing through a destructor. This option is **not intended to be used in hosted environments such as GNU/Linux. It targets free-standing environments (for example embedded systems) with limited resources which do not support constructors/destructors or the C library file I/O. 🧚

The linker could collect the input sections in a continuous memory block and define start and end symbols. A GNU linker script example which defines a linker output section follows:

          .gcov_info      :
          {
            PROVIDE (__gcov_info_start = .);
            KEEP (*(.gcov_info))
            PROVIDE (__gcov_info_end = .);
          }

The program could dump the profiling information registered in this linker set for example like this:

      #include <gcov.h>
      #include <stdio.h>
      #include <stdlib.h>

      extern const struct gcov_info *__gcov_info_start[];
      extern const struct gcov_info *__gcov_info_end[];

      static void
      filename (const char *f, void *arg)
      {
        puts (f);
      }

...and the example just keeps going, bestie, we're still in the middle of it 💖

                   static void
                   dump (const void *d, unsigned n, void *arg)
                   {
                     const unsigned char *c = d;

                     for (unsigned i = 0; i < n; ++i)
                       printf ("%02x", c[i]);
                   }

                   static void *
                   allocate (unsigned length, void *arg)
                   {
                     return malloc (length);
                   }

                   static void
                   dump_gcov_info (void)
                   {
                     const struct gcov_info **info = __gcov_info_start;
                     const struct gcov_info **end = __gcov_info_end;

                     /* Obfuscate variable to prevent compiler optimizations.  */
                     __asm__ ("" : "+r" (info));

                     while (info != end)
                     {
                       void *arg = NULL;
                       __gcov_info_to_gcda (*info, filename, dump, allocate, arg);
                       putchar ('\n');
                       ++info;
                     }
                   }

                   int
                   main()
                   {
                     dump_gcov_info();
                     return 0;
                   }

  • -fprofile-note=path — like, if you actually give it a path, GCC drops the .gcno file in that exact spot ✨. but heads up: if you pair this with multiple source files, the .gcno file gets overwritten 😭 — one file, many sources, only the last one survives. no cap.
  • -fprofile-prefix-path=path — this one's a team player 🫶, it works together with profile-generate=profile_dir and profile-use=profile_dir to tell GCC where the base directory of your built source tree actually lives. Here's the tea: by default profile_dir ends up stuffed with files carrying mangled absolute paths for every object file in the project 💀. That's lowkey a problem when the directory you built the instrumented binary in is different from the directory you build the profile-feedback-optimized binary in — because then the profile data just... won't be found during the optimized build 🙈. In those setups you use -fprofile-prefix-path=path with path pointing at the base directory of the build, which strips off the irrelevant part of the path and keeps all file names relative to the main build directory. iconic.
  • -fprofile-prefix-map=old=new — when you're compiling files living in directory old, record the profiling info (with --coverage) as if those files lived in directory new instead 🎀. See also -ffile-prefix-map.
  • -fprofile-update=method — changes the update method for an app instrumented for profile-feedback-based optimization. method has to be one of single, atomic, or prefer-atomic ⭐. The first one is your girl for single-threaded apps, while the second one keeps profile corruption away by emitting thread-safe code 🔥.
⚠️ Warning: when an application doesn't properly join all threads (or creates a detached thread), the profile file can still get corrupted. fr fr, no instrumenting your way out of that one.

Using prefer-atomic gets transformed into either atomic — when the target supports it — or into single otherwise 🦋. And the GCC driver automatically picks prefer-atomic whenever -pthread shows up on the command line. main character behavior.

  • -fprofile-filter-files=regex — only instruments functions from files whose name matches any of the regular expressions (separated by semi-colons 🍓).

Like, for example: -fprofile-filter-files=main\.c;module.*\.c will instrument only main.c and all C files starting with 'module'. cute and specific.

  • -fprofile-exclude-files=regex — the inverse vibe check: only instruments functions from files whose name does not match any of the regular expressions (again, separated by semi-colons 🌸).

Example time: -fprofile-exclude-files=/usr/.* keeps the instrumentation off every file sitting in the /usr/ folder 🙅‍♀️.

  • -fprofile-reproducible=[multithreaded|parallel-runs|serial] — controls how reproducible the profile gathered by -fprofile-generate is 🎯. This is what makes it possible to rebuild a program with the same outcome, which is genuinely useful — for distribution packages, for instance 👑

With -fprofile-reproducible=serial the profile gathered by -fprofile-generate is reproducible provided the trained program behaves the same at each invocation of the train run, is not multi-threaded, and profile data streaming is always done in the same order ✨. Note that profile streaming happens at the end of the program run, but also before the fork function is invoked. iykyk.

Note also that it's pretty common for execution counts of some parts of programs to depend on stuff like the length of temporary file names or memory space randomization (which can affect hash-table collision rate) 😭. Any such non-reproducible part can be annotated with the no_instrument_function function attribute. And gcov-dump with -l can dump the gathered data so you can verify they're genuinely reproducible 🧚.

With -fprofile-reproducible=parallel-runs the collected profile stays reproducible regardless of the order the data gets streamed into the gcda files 💅. This setting lets you run multiple instances of the instrumented program in parallel (like with make -j). Trade-off, though: it reduces the quality of the gathered data — in particular of indirect call profiling 💀.

🚫 This option cannot be combined with -fsanitize=thread or -fsanitize=hwaddress. And note that the only target -fsanitize=hwaddress is currently supported on is AArch64.
  • -fsanitize=kernel-address — enables AddressSanitizer for the Linux kernel 🐧. Details at https://github.com/google/kasan.
  • -fsanitize=hwaddress — enables Hardware-assisted AddressSanitizer, which uses a hardware ability to ignore the top byte of a pointer so it can detect memory errors with low memory overhead ✨. Memory access instructions get instrumented to detect out-of-bounds and use-after-free bugs, and the option enables -fsanitize-address-use-after-scope too 🦋. More at https://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html.

The run-time behavior can be influenced using the HWASAN_OPTIONS environment variable; set it to help=1 and the available options are shown at startup of the instrumented program 👑.

🚫 Cannot be combined with -fsanitize=thread or -fsanitize=address, and it's currently only available on AArch64.
  • -fsanitize=kernel-hwaddress — Hardware-assisted AddressSanitizer, but for compiling the Linux kernel 🐧💜. Similar to -fsanitize=kernel-address but using an alternate instrumentation method, and similar to -fsanitize=hwaddress but with the instrumentation differences needed to compile the Linux kernel. Those differences exist to avoid hwasan library initialization calls, and to account for the stack pointer having a different value in its top byte 🙈.
📌 Note: this option has different defaults than -fsanitize=hwaddress. Instrumenting the stack and alloca calls are not on by default, but you can still get them by specifying the command-line options --param hwasan-instrument-stack=1 and --param hwasan-instrument-allocas=1 respectively ✨. And using a random frame tag is not implemented for kernel instrumentation, periodt.
  • -fsanitize=pointer-compare — instruments the comparison operations (<, <=, >, >=) with pointer operands 💅. This option must be combined with either -fsanitize=kernel-address or -fsanitize=address, and it cannot be combined with -fsanitize=thread 🚫.
📌 Note: by default the check is disabled at run time. To enable it, add detect_invalid_pointer_pairs=2 to the environment variable ASAN_OPTIONS. Using detect_invalid_pointer_pairs=1 detects an invalid operation only when both pointers are non-null 🍓.
  • -fsanitize=pointer-subtract — instruments subtraction with pointer operands ✨. Same rules, bestie: it must be combined with either -fsanitize=kernel-address or -fsanitize=address, and it cannot be combined with -fsanitize=thread 🚫.
📌 Note: by default the check is disabled at run time. To enable it, add detect_invalid_pointer_pairs=2 to the environment variable ASAN_OPTIONS. Using detect_invalid_pointer_pairs=1 detects an invalid operation only when both pointers are non-null 🌸.
  • -fsanitize=shadow-call-stack — enables ShadowCallStack, a security enhancement mechanism that protects programs against return address overwrites (e.g. stack buffer overflows 🫣). How it works: it saves a function's return address to a separately allocated shadow call stack in the function prologue, then restores the return address from that shadow call stack in the function epilogue 🎀. Instrumentation only happens in functions that actually need to save the return address to the stack. so tidy.

Right now it only supports the aarch64 platform ⭐. It's specifically designed for linux kernels that enable the CONFIG_SHADOW_CALL_STACK option. For user space programs, runtime support is not currently provided in libc and libgcc 💀 — anyone who wants this feature in user space has to bring their own runtime support. And it should be noted that this may cause the ABI rules to be broken 😭.

On aarch64, the instrumentation makes use of the platform register x18. This generally means any code that may run on the same thread as code compiled with ShadowCallStack must be compiled with the flag -ffixed-x18 — otherwise functions compiled without -ffixed-x18 might clobber x18 and so corrupt the shadow stack pointer 🙈.

Also, because there's no userspace runtime support, code compiled with ShadowCallStack cannot use exception handling. Use -fno-exceptions to turn exceptions off 🚫.

More details at https://clang.llvm.org/docs/ShadowCallStack.html 💜


Also lowkey important: sanitized atomic builtins cannot throw exceptions when they're operating on invalid memory addresses with non-call exceptions (-fnon-call-exceptions) 💀.

  • -fsanitize=leak — this one enables LeakSanitizer, the memory leak detector 🎀. Ngl it only matters for the linking of executables, and the executable gets linked against a library that overrides malloc and other allocator functions. See <https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer> for more. Run-time behavior is influenced using the LSAN_OPTIONS environment variable. And same deal — this option cannot be combined with -fsanitize=thread 🙈.
  • -fsanitize=undefined — enables UndefinedBehaviorSanitizer, a fast undefined behavior detector, and honestly it's giving main character energy 🔥. Various computations get instrumented to detect undefined behavior at runtime. More details at <https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html>. Run-time behavior is influenced via the UBSAN_OPTIONS environment variable. Current suboptions are:
    • -fsanitize=shift — enables checking that the result of a shift operation isn't undefined 🌀. Note that what exactly counts as undefined differs slightly between C and C++, and between ISO C90 and C99, etc. This option has two suboptions: -fsanitize=shift-base and -fsanitize=shift-exponent.
    • -fsanitize=shift-exponent — checks that the second argument of a shift operation is not negative and is smaller than the precision of the promoted first argument ✨.
    • -fsanitize=shift-base — if the second argument of a shift operation is within range, it checks that the result of the shift operation is not undefined. Again, what exactly is considered undefined differs slightly between C and C++, as well as between ISO C90 and C99, etc. 😌
    • -fsanitize=integer-divide-by-zero — detects integer division by zero 🚨.
    • -fsanitize=unreachable — with this option the compiler turns the __builtin_unreachable call into a diagnostics message call instead. When you actually reach that __builtin_unreachable call, the behavior is undefined 💀.
    • -fsanitize=vla-bound — instructs the compiler to check that the size of a variable length array is positive 🎀.
    • -fsanitize=null — enables pointer checking 👀. Specifically, an application built with this turned on will issue an error message when it tries to dereference a NULL pointer, or if a reference (possibly an rvalue reference) is bound to a NULL pointer, or if a method is invoked on an object pointed to by a NULL pointer.
    • -fsanitize=return — enables return statement checking 🫶. Programs built with this turned on will issue an error message when the end of a non-void function is reached without actually returning a value. Heads up: this option works in C++ only.
    • -fsanitize=signed-integer-overflow — enables signed integer overflow checking. We check that the result of +, *, and both unary and binary - doesn't overflow in signed arithmetics. It also detects INT_MIN / -1 signed division 🔥. Note that integer promotion rules have to be taken into account — meaning the following is not an overflow:
signed char a = SCHAR_MAX;
a++;
  • -fsanitize=bounds — enables instrumentation of array bounds, so various out of bounds accesses get detected 🦋. Flexible array members, flexible array member-like arrays, and initializers of variables with static storage are not instrumented.
  • -fsanitize=bounds-strict — enables strict instrumentation of array bounds, so most out of bounds accesses get detected, including flexible array members and flexible array member-like arrays 🌈. Initializers of variables with static storage are still not instrumented.
  • -fsanitize=alignment — enables checking of alignment of pointers when they're dereferenced, or when a reference is bound to an insufficiently aligned target, or when a method or constructor is invoked on an insufficiently aligned object 📐.
  • -fsanitize=object-size — enables instrumentation of memory references using the __builtin_object_size function, so various out of bounds pointer accesses get detected 🔍.
  • -fsanitize=float-divide-by-zero — detects floating-point division by zero. Unlike other similar options, -fsanitize=float-divide-by-zero is not enabled by -fsanitize=undefined, because floating-point division by zero can be a legitimate way of obtaining infinities and NaNs 💅.
  • -fsanitize=float-cast-overflow — enables floating-point type to integer conversion checking, so we check that the result of the conversion doesn't overflow 🎀. Unlike other similar options, -fsanitize=float-cast-overflow is not enabled by -fsanitize=undefined. Also this option does not work well with FE_INVALID exceptions enabled 😭.
  • -fsanitize=nonnull-attribute — enables instrumentation of calls, checking whether null values are not passed to arguments marked as requiring a non-null value by the nonnull function attribute ✨.
  • -fsanitize=returns-nonnull-attribute — enables instrumentation of return statements in functions marked with the returns_nonnull function attribute, to detect returning of null values from such functions 🚨.
  • -fsanitize=bool — enables instrumentation of loads from bool. If a value other than 0/1 is loaded, a run-time error is issued 👑.
  • -fsanitize=enum — enables instrumentation of loads from an enum type. If a value outside the range of values for the enum type is loaded, a run-time error is issued 💜.
  • -fsanitize=vptr — enables instrumentation of C++ member function calls, member accesses, and some conversions between pointers to base and derived classes, to verify that the referenced object has the correct dynamic type 🧚.
  • -fsanitize=pointer-overflow — enables instrumentation of pointer arithmetics. If the pointer arithmetics overflows, a run-time error is issued 🔥.
  • -fsanitize=builtin — enables instrumentation of arguments to selected builtin functions. If an invalid value is passed to such arguments, a run-time error is issued. E.g. passing 0 as the argument to __builtin_ctz or __builtin_clz invokes undefined behavior and is diagnosed by this option 💀.

Ok so real talk: while -ftrapv causes traps for signed overflows to be emitted, -fsanitize=undefined gives you a diagnostic message instead 🫶. This currently works only for the C family of languages.

  • -fno-sanitize=all — disables all previously enabled sanitizers 🙈. And no, -fsanitize=all is not allowed — because some sanitizers literally cannot be used together, bestie.
  • -fasan-shadow-offset=number — forces GCC to use a custom shadow offset in AddressSanitizer checks 🌸. Super useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer.
  • -fsanitize-sections=s1,s2,... — sanitize global variables in selected user-defined sections. And guess what, si may contain wildcards ✨.
  • -fsanitize-recover[=opts] — -fsanitize-recover= controls error recovery mode for the sanitizers mentioned in the comma-separated list of opts 🎀. Enabling this option for a sanitizer component makes it try to keep running the program as if no error happened. Which means multiple runtime errors can be reported in a single program run, and the exit code of the program may indicate success even when errors have been reported 😭. The -fno-sanitize-recover= option can alter this behavior: only the first detected error is reported and then the program exits with a non-zero exit code.

Currently this feature only works for -fsanitize=undefined (and its suboptions except for -fsanitize=unreachable and -fsanitize=return), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero, -fsanitize=bounds-strict, -fsanitize=kernel-address and -fsanitize=address 🌈. For these sanitizers error recovery is turned on by default — except -fsanitize=address, for which this feature is experimental 👀. -fsanitize-recover=all and -fno-sanitize-recover=all are also accepted: the former enables recovery for all sanitizers that support it, the latter disables recovery for all sanitizers that support it.

Even if recovery mode is turned on the compiler side, it needs to also be enabled on the runtime library side, otherwise the failures are still fatal 💀. The runtime library defaults to halt_on_error=0 for ThreadSanitizer and UndefinedBehaviorSanitizer, while the default value for AddressSanitizer is halt_on_error=1. You can override this through setting the halt_on_error flag in the corresponding environment variable.

Deprecated alert 🚨: the syntax without an explicit opts parameter is deprecated. It's equivalent to specifying an opts list of:
undefined,float-cast-overflow,float-divide-by-zero,bounds-strict
  • -fsanitize-address-use-after-scope — enables sanitization of local variables to detect use-after-scope bugs 🦋. This option sets -fstack-reuse to none.
  • -fsanitize-undefined-trap-on-error — instructs the compiler to report undefined behavior using __builtin_trap rather than a libubsan library routine 🔥. The advantage? The libubsan library isn't needed and isn't linked in, so this is usable even in freestanding environments 👑.

  • -fsanitize-coverage=trace-pc — bestie, this one turns on coverage-guided fuzzing instrumentation ✨ It literally inserts a call to __sanitizer_cov_trace_pc into every single basic block. Every one. No skipping. 💅
  • -fsanitize-coverage=trace-cmp — okay so this is the dataflow-guided fuzzing instrumentation, and the way it works is it plants a whole little family of calls depending on what you're comparing 🫶
    • __sanitizer_cov_trace_cmp1, __sanitizer_cov_trace_cmp2, __sanitizer_cov_trace_cmp4 or __sanitizer_cov_trace_cmp8 — for integral comparison when both operands are variable
    • __sanitizer_cov_trace_const_cmp1, __sanitizer_cov_trace_const_cmp2, __sanitizer_cov_trace_const_cmp4 or __sanitizer_cov_trace_const_cmp8 — for integral comparison when one operand is a constant
    • __sanitizer_cov_trace_cmpf or __sanitizer_cov_trace_cmpd — for float or double comparisons respectively 💖
    • __sanitizer_cov_trace_switch — for switch statements, iconic behavior tbh
  • -fcf-protection=[full|branch|return|none|check] — this is the security-girlie option 🔥 It instruments control-flow transfers so the compiler can check that the target addresses of control-flow transfer instructions — think indirect function call, function return, indirect jump — are actually valid. Which means nobody can divert your control flow to some unexpected target. It's giving "protect me from Return-oriented Programming (ROP)", and also from the similarly-named call/jmp-oriented programming (COP/JOP) 😭

Here's the breakdown of the values, iykyk:

  • branch — tells the compiler to check validity of control-flow transfer at the point of indirect branch instructions, aka call/jmp instructions
  • return — checks validity at the point of returning from a function
  • full — this is just an alias for specifying both branch and return together, slay
  • none — turns the instrumentation off entirely 🎀
  • check — this one's for the final link with link-time optimization (LTO). An error gets issued if LTO object files were compiled with different -fcf-protection values. And heads up: check is ignored at compile time

Also important: the macro __CET__ is defined when -fcf-protection is used. The first bit of __CET__ is set to 1 for the value branch, and the second bit of __CET__ is set to 1 for return. 🧚

You can also use the nocf_check attribute to mark which functions and calls should be skipped from instrumentation.

Currently the x86 GNU/Linux target provides an implementation based on Intel Control-flow Enforcement Technology (CET), and it works for i686 processor or newer 💜

  • -fharden-compares — for every logical test that survives gimple optimizations and is not the condition in a conditional branch (like, conditions tested for conditional moves, or ones stored in boolean variables), it emits extra code to compute and verify the reversed condition, and calls __builtin_trap if the results don't match 💀 Pair it with -fharden-conditional-branches to cover all conditionals, fr fr.
  • -fharden-conditional-branches — for every non-vectorized conditional branch that survives gimple optimizations, it emits extra code to compute and verify the reversed condition, and calls __builtin_trap if the result is unexpected 😳 Use it with -fharden-compares to cover all the conditionals.
  • -fstack-protector — emits extra code to catch buffer overflows, like stack smashing attacks 🛡️ It does this by adding a guard variable to functions that have vulnerable objects. That includes functions that call alloca, and functions with buffers larger than or equal to 8 bytes. The guards get initialized when a function is entered and then checked when it exits. If a guard check fails? An error message is printed and the program exits, periodt. Also note: only variables that are actually allocated on the stack count — optimized-away variables or variables allocated in registers don't count 🙈
  • -fstack-protector-all — literally just like -fstack-protector except all functions are protected. All of them. No exceptions 💅
  • -fstack-protector-strong — like -fstack-protector but it includes additional functions to be protected — specifically those that have local array definitions, or have references to local frame addresses 🌸 Same caveat as before: only variables actually allocated on the stack are considered; optimized-away variables or variables allocated in registers don't count.
  • -fstack-protector-explicit — like -fstack-protector, but it only protects those functions which have the stack_protect attribute 🎀
  • -fstack-check — generates code to verify that you don't go beyond the boundary of the stack. You should specify this flag if you're running in an environment with multiple threads, but you only rarely need to specify it in a single-threaded environment, since stack overflow is automatically detected on nearly all systems if there's only one stack 🦋

Big note: this switch does not actually cause checking to be done — the operating system or the language runtime has to do that. The switch just causes generation of code to ensure that they see the stack being extended.

You can additionally specify a string parameter:

  • no — means no checking
  • generic — forces the use of old-style checking
  • specific — uses the best checking method, and is equivalent to bare -fstack-check

Old-style checking is a generic mechanism that requires no specific target support in the compiler, but bestie, it comes with these drawbacks 😭

  1. Modified allocation strategy for large objects: they are always allocated dynamically if their size exceeds a fixed threshold. Note this may change the semantics of some code.
  2. Fixed limit on the size of the static frame of functions: when it is topped by a particular function, stack checking is not reliable and a warning is issued by the compiler.
  3. Inefficiency: because of both the modified allocation strategy and the generic implementation, code performance is hampered.

Note that old-style stack checking is also the fallback method for specific if no target support has been added in the compiler.

-fstack-check= is designed for Ada's needs to detect infinite recursion and stack overflows. specific is an excellent choice when compiling Ada code ✨ But it is not generally sufficient to protect against stack-clash attacks. To protect against those, you want -fstack-clash-protection instead 👑

  • -fstack-clash-protection — generates code to prevent stack clash style attacks 🔥 When this option is enabled, the compiler will only allocate one page of stack space at a time, and each page is accessed immediately after allocation. So it prevents allocations from jumping over any stack guard page provided by the operating system. Iconic.

Most targets do not fully support stack clash protection. However, on those targets -fstack-clash-protection will protect dynamic stack allocations. It may also provide limited protection for static stack allocations if the target supports -fstack-check=specific 🌈

  • -fstack-limit-register=reg
  • -fstack-limit-symbol=sym
  • -fno-stack-limit

These three generate code to ensure the stack does not grow beyond a certain value — either the value of a register or the address of a symbol 💖 If a larger stack is required, a signal is raised at run time. For most targets, the signal is raised before the stack overruns the boundary, so you can actually catch the signal without taking special precautions 🫶

For instance, if the stack starts at absolute address 0x80000000 and grows downwards, you can use the flags -fstack-limit-symbol=__stack_limit and -Wl,--defsym,__stack_limit=0x7ffe0000 to enforce a stack limit of 128KB. Note that this may only work with the GNU linker 🌸

You can locally override stack limit checking by using the no_stack_limit function attribute.

  • -fsplit-stack — generates code to automatically split the stack before it overflows 😌 The resulting program has a discontiguous stack which can only overflow if the program is unable to allocate any more memory. This is most useful when running threaded programs, since it's no longer necessary to calculate a good stack size to use for each thread. Currently this is only implemented for the x86 targets running GNU/Linux.

Heads up though: when code compiled with -fsplit-stack calls code compiled without -fsplit-stack, there may not be much stack space available for the latter code to run 😭 If compiling all code — including library code — with -fsplit-stack isn't an option, then the linker can fix up these calls so that the code compiled without -fsplit-stack always has a large stack. Support for this is implemented in the gold linker in GNU binutils release 2.21 and later 💜

  • -fvtable-verify=[std|preinit|none] — this option is only available when compiling C++ code 🎀 It turns on (or off, if you're using -fvtable-verify=none) the security feature that verifies at run time, for every virtual call, that the vtable pointer through which the call is made is valid for the type of the object, and hasn't been corrupted or overwritten. If an invalid vtable pointer is detected at run time, an error is reported and execution of the program is immediately halted 💀

This option causes run-time data structures to be built at program startup, which are used for verifying the vtable pointers. The options std and preinit control the timing of when these data structures get built. In both cases the data structures are built before execution reaches main. Using -fvtable-verify=std causes the data structures to be built after shared libraries have been loaded and initialized. -fvtable-verify=preinit causes them to be built before shared libraries have been loaded and initialized ✨

If this option appears multiple times in the command line with different values specified, none takes highest priority over both std and preinit; and preinit takes priority over std 👑

  • -fvtv-debug — when used in conjunction with -fvtable-verify=std or -fvtable-verify=preinit, it causes debug versions of the runtime functions for the vtable verification feature to be called 🦋 This flag also causes the compiler to log information about which vtable pointers it finds for each class. That info gets written to a file named vtv_set_ptr_data.log in the directory named by the environment variable VTV_LOGS_DIR if that's defined, or the current working directory otherwise 🌸
Note: this feature appends data to the log file. If you want a fresh log file, be sure to delete any existing one first, bestie 🙈
  • -fvtv-counts — okay so this one is a debugging flag, ngl. When you pair it with -fvtable-verify=std or -fvtable-verify=preinit, the compiler starts keeping track of the total number of virtual calls it runs into, plus how many verifications it inserts. It also counts the calls to certain run-time library functions that it inserts, and logs all of that for each compilation unit.

Where does it write it? To a file named vtv_count_data.log, in the directory named by the environment variable VTV_LOGS_DIR if that's defined — otherwise the current working directory. It also counts the size of the vtable pointer sets for each class and writes that to vtv_class_set_sizes.log in the same directory.

Heads up bestie: this feature appends data to the log files 💀 so if you want fresh ones, delete the existing files first. No cap.
  • -finstrument-functions — generates instrumentation calls for entry and exit to functions ✨. Just after a function is entered and just before it exits, these profiling functions get called with the address of the current function and its call site. (On some platforms, "__builtin_return_address" doesn't work beyond the current function, so the call site info might not be available to the profiling functions otherwise — lowkey important.)
void __cyg_profile_func_enter (void *this_fn,
                               void *call_site);
void __cyg_profile_func_exit  (void *this_fn,
                               void *call_site);

The first argument is the address of the start of the current function, which you can look up exactly in the symbol table 🔍.

This instrumentation also happens for functions expanded inline in other functions. The profiling calls indicate where, conceptually, the inline function is entered and exited. Which means addressable versions of such functions must be available. If all your uses of a function are expanded inline, that can mean an additional expansion of code size 😭. And if you use "extern inline" in your C code, an addressable version of such functions must be provided. (Normally that's the case anyway, but if you get lucky and the optimizer always expands the functions inline, you might have gotten away without providing static copies.)

A function can be given the attribute "no_instrument_function", and then this instrumentation isn't done — super useful, for example, for the profiling functions listed above, high-priority interrupt routines, and any functions from which the profiling functions can't safely be called (maybe signal handlers, if the profiling routines generate output or allocate memory 👀).

  • -finstrument-functions-exclude-file-list=file,file,... — sets the list of functions excluded from instrumentation (see -finstrument-functions above 🫶). If the file that contains a function definition matches with one of file, then that function is not instrumented. The match is done on *substrings: if the *file parameter is a substring of the file name, it counts as a match ✨.

For example:

-finstrument-functions-exclude-file-list=/bits/stl,include/sys

excludes any inline function defined in files whose pathnames contain /bits/stl or include/sys.

If, for some reason, you want to include letter , in one of sym, write ,. For example, -finstrument-functions-exclude-file-list=',,tmp' (note the single quote surrounding the option 🎀).

  • -finstrument-functions-exclude-function-list=sym,sym,... — basically the same vibe as -finstrument-functions-exclude-file-list, except this option sets the list of *function names to be excluded from instrumentation. The function name matched is its user-visible name, like "vector<int> blah(const vector<int> &)", not the internal mangled name (e.g., "_Z4blahRSt6vectorIiSaIiEE"). Match is on substrings: if the *sym parameter is a substring of the function name, it's a match 💅. For C99 and C++ extended identifiers, the function name must be given in UTF-8, not using universal character names.
  • *-fpatchable-function-entry=N[,M] — generates *N NOPs right at the beginning of each function, with the function entry point before the Mth NOP. If M is omitted, it defaults to 0, so the function entry points to the address just at the first NOP ✨. Those NOP instructions reserve extra space that can be used to patch in whatever instrumentation you want at run time — provided the code segment is writable 👀. The amount of space is controllable indirectly via the number of NOPs; the NOP instruction used corresponds to the instruction emitted by the internal GCC back-end interface "gen_nop". This behavior is target-specific and may also depend on the architecture variant and/or other compilation options.

For run-time identification, the starting addresses of these areas — which correspond to their respective function entries minus M — are additionally collected in the "__patchable_function_entries" section of the resulting binary 🔥.

Note that the value of "__attribute__ ((patchable_function_entry (N,M)))" takes precedence over the command-line option -fpatchable-function-entry=N,M. You can use this to increase the area size or to remove it completely on a single function. If "N=0", no pad location is recorded.

The NOP instructions are inserted at — and maybe before, depending on M — the function entry address, even before the prologue 💖.

The maximum value of N and M is 65535.


🌸 Options Controlling the Preprocessor 🌸

So these options control the C preprocessor, which runs on each C source file before actual compilation 🧚.

If you use the -E option, nothing is done except preprocessing — that's it, that's the whole job 💅. Some of these options only make sense together with -E, because they cause the preprocessor output to be unsuitable for actual compilation 😭.

In addition to the options listed here, there are a number of options to control search paths for include files documented in Directory Options. Options to control preprocessor diagnostics are listed in Warning Options.

  • -D name — predefines name as a macro, with definition 1 ✨.
  • -D name=definition — the contents of definition are tokenized and processed as if they appeared during translation phase three in a #define directive. In particular, the definition is truncated by embedded newline characters 👀.

If you're invoking the preprocessor from a shell or shell-like program, you may need the shell's quoting syntax to protect characters such as spaces that mean something in shell syntax 🫶.

Want a function-like macro on the command line? Write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so quote the option. With sh and csh, -D'name(args...)=definition' works 💖.

-D and -U options are processed in the order they're given on the command line. All -imacros file and -include file options are processed after all -D and -U options 🔥.

  • -U name — cancels any previous definition of name, whether it was built in or provided with a -D option 💅.
  • -include file — processes file as if "#include "file"" appeared as the first line of the primary source file. However, the first directory searched for file is the preprocessor's working directory instead of the directory containing the main source file 👀. If it's not found there, it's searched for in the remainder of the "#include "..."" search chain as normal.

If multiple -include options are given, the files are included in the order they appear on the command line ✨.

  • -imacros file — exactly like -include, except that any output produced by scanning file is thrown away 🗑️. Macros it defines stay defined though. This lets you grab all the macros from a header without also processing its declarations — iconic, honestly 👑.

All files specified by -imacros are processed before all files specified by -include.

  • -undef — do not predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined 🎀.
  • -pthread — defines additional macros required for using the POSIX threads library 🧵. Use this option consistently for both compilation and linking — that part matters, fr fr. This option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets ✨.
  • -M — instead of outputting the result of preprocessing, output a rule suitable for make describing the dependencies of the main source file 🛠️. The preprocessor outputs one make rule containing the object file name for that source file, a colon, and the names of all the included files — including those coming from -include or -imacros command-line options.

Unless specified explicitly (with -MT or -MQ), the object file name consists of the name of the source file with any suffix replaced with the object file suffix, and with any leading directory parts removed. If there are many included files, the rule gets split into several lines using \-newline. The rule has no commands.

This option does not suppress the preprocessor's debug output, such as -dM. To avoid mixing that debug output with the dependency rules, explicitly specify the dependency output file with -MF, or use an environment variable like DEPENDENCIES_OUTPUT. Debug output still goes to the regular output stream as normal 💅.

Passing -M to the driver implies -E, and suppresses warnings with an implicit -w.

  • -MM — like -M, but doesn't mention header files found in system header directories, nor header files included — directly or indirectly — from such a header 🙈.

This implies that the choice of angle brackets or double quotes in an #include directive does not by itself determine whether that header appears in -MM dependency output 👀.

  • -MF file — when used with -M or -MM, specifies a file to write the dependencies to ✨. If no -MF switch is given, the preprocessor sends the rules to the same place it would send preprocessed output.

When used with the driver options -MD or -MMD, -MF overrides the default dependency output file 💅.

If file is -, then the dependencies are written to stdout 🎀.

  • -MG — okay so when you pair this with a dep-generation option like -M, -MG is like "bestie, if a header's missing, assume it's a generated file" — it adds the missing header to the dependency list without throwing an error at you. The dependency filename is taken straight from the #include directive, no path prepended, no questions asked. -MG also suppresses preprocessed output, because honestly a missing header file renders that whole thing useless anyway 💀

Where's this used? Automatic updating of makefiles. That's the whole vibe. 🎀

  • -Mno-modules — disable dependency generation for compiled module interfaces. That's it, that's the whole thing. ✨
  • -MP — this one tells CPP to add a phony target for each dependency other than the main file, so each of them depends on nothing. Iconic. These dummy rules work around the errors make throws at you when you delete header files without updating the Makefile to match. Very "not me breaking the build again" energy 🙈

Typical output, bestie:

        test.o: test.c test.h

        test.h:
  • -MT target — change the target of the rule that dependency generation emits. By default CPP grabs the name of the main input file, yeets any directory components and any file suffix like .c, then appends the platform's usual object suffix. That result is the target.

An -MT option sets the target to be exactly the string you specify, no notes, no edits. Want multiple targets? Pass them as a single argument to -MT, or just use multiple -MT options. Your call, queen 👑

For example, -MT '$(objpfx)foo.o' might give

        $(objpfx)foo.o: foo.c
  • -MQ target — same as -MT, but it quotes any characters that are special to Make. So -MQ '$(objpfx)foo.o' gives
        $$(objpfx)foo.o: foo.c

Also, the default target is automatically quoted, as if it were given with -MQ. It said what it said. 💅

  • -MD — -MD is equivalent to -M -MF file, except that -E is not implied. The driver determines file based on whether an -o option is given. If it is, the driver uses its argument but with a suffix of .d; otherwise it takes the name of the input file, removes any directory components and suffix, and applies a .d suffix.

If -MD is used in conjunction with -E, any -o switch is understood to specify the dependency output file — but if used without -E, each -o is understood to specify a target object file. Context is everything, babes ✨

Since -E is not implied, -MD can be used to generate a dependency output file as a side effect of the compilation process. Sneaky but legal 🦋

  • -MMD — like -MD except it mentions only user header files, not system header files. Keep it to your own business, basically 💜
  • -fpreprocessed — tells the preprocessor the input file has already been preprocessed. This suppresses things like macro expansion, trigraph conversion, escaped newline splicing, and processing of most directives. The preprocessor still recognizes and removes comments though, so you can pass a file preprocessed with -C to the compiler without problems. In this mode the integrated preprocessor is little more than a tokenizer for the front ends. A glorified tokenizer. She's doing her best 😭

-fpreprocessed is implicit if the input file has one of the extensions .i, .ii or .mi. These are the extensions GCC uses for preprocessed files created by -save-temps.

  • -fdirectives-only — when preprocessing, handle directives, but do not expand macros. The option's behavior depends on the -E and -fpreprocessed options, so pay attention bestie:

With -E, preprocessing is limited to the handling of directives such as #define, #ifdef, and #error. Other preprocessor operations, such as macro expansion and trigraph conversion, are not performed. In addition, the -dD option is implicitly enabled.

With -fpreprocessed, predefinition of command line and most builtin macros is disabled. Macros such as __LINE__, which are contextually dependent, are handled normally. This enables compilation of files previously preprocessed with -E -fdirectives-only.

With both -E and -fpreprocessed, the rules for -fpreprocessed take precedence. This enables full preprocessing of files previously preprocessed with -E -fdirectives-only. Rules are rules, periodt 🌸

  • -fdollars-in-identifiers — accept $ in identifiers. Chaotic. Love it. 💅
  • -fextended-identifiers — accept universal character names and extended characters in identifiers. This option is enabled by default for C99 (and later C standard versions) and C++. Slay, standards compliance 🎀
  • -fno-canonical-system-headers — when preprocessing, do not shorten system header paths with canonicalization. Leave those paths long, honestly. 🌈
  • -fmax-include-depth=depth — set the maximum depth of the nested #include. The default is 200. Don't go deeper than 200, bestie, that's an order 🫶
  • -ftabstop=width — set the distance between tab stops. This helps the preprocessor report correct column numbers in warnings or errors, even if tabs appear on the line. If the value is less than 1 or greater than 100, the option is ignored. The default is 8. Respect the tabstop ✨
  • -ftrack-macro-expansion[=level] — track locations of tokens across macro expansions. This allows the compiler to emit diagnostics about the current macro expansion stack when a compilation error occurs in a macro expansion. Using this option makes the preprocessor and the compiler consume more memory — yes, the cost of being thorough 😮‍💨

The level parameter can be used to choose the level of precision of token location tracking, thus decreasing the memory consumption if necessary. Value 0 of level de-activates this option. Value 1 tracks token locations in a degraded mode for the sake of minimal memory overhead — in this mode all tokens resulting from the expansion of an argument of a function-like macro have the same location. Value 2 tracks token locations completely, and this value is the most memory hungry. When this option is given no argument, the default parameter value is 2.

Note that -ftrack-macro-expansion=2 is activated by default. She comes pre-installed, babe 💖

  • -fmacro-prefix-map=old=new — when preprocessing files residing in directory old, expand the __FILE__ and __BASE_FILE__ macros as if the files resided in directory new instead. This can be used to change an absolute path to a relative path by using . for new, which can result in more reproducible builds that are location independent. This option also affects __builtin_FILE() during compilation. See also -ffile-prefix-map. 🔥
  • -fexec-charset=charset — set the execution character set, used for string and character constants. The default is UTF-8. charset can be any encoding supported by the system's iconv library routine. Encoding queen 👑
  • -fwide-exec-charset=charset — set the wide execution character set, used for wide string and character constants. The default is UTF-32 or UTF-16, whichever corresponds to the width of wchar_t. As with -fexec-charset, charset can be any encoding supported by the system's iconv library routine — however, you will have problems with encodings that do not fit exactly in wchar_t. Big "this will bite you" energy, be warned 💀
  • -finput-charset=charset — set the input character set, used for translation from the character set of the input file to the source character set used by GCC. If the locale does not specify, or GCC cannot get this information from the locale, the default is UTF-8. This can be overridden by either the locale or this command-line option. Currently the command-line option takes precedence if there's a conflict. charset can be any encoding supported by the system's iconv library routine. Locale drama, resolved 📎
  • -fpch-deps — when using precompiled headers, this flag causes the dependency-output flags to also list the files from the precompiled header's dependencies. If not specified, only the precompiled header is listed, and not the files that were used to create it — because those files are not consulted when a precompiled header is used. Make it make sense 🦋
  • -fpch-preprocess — this option allows use of a precompiled header together with -E. It inserts a special #pragma, #pragma GCC pch_preprocess "filename", in the output to mark the place where the precompiled header was found, and its filename. When -fpreprocessed is in use, GCC recognizes this #pragma and loads the PCH.

This option is off by default, because the resulting preprocessed output is only really suitable as input to GCC. It is switched on by -save-temps.

You should not write this #pragma in your own code — but it is safe to edit the filename if the PCH file is available in a different location. The filename may be absolute or it may be relative to GCC's current directory. Don't be weird about it 🙈
  • -fworking-directory — enable generation of linemarkers in the preprocessor output that let the compiler know the current working directory at the time of preprocessing. When this option is enabled, the preprocessor emits, after the initial linemarker, a second linemarker with the current working directory followed by two slashes. GCC uses this directory, when it's present in the preprocessed input, as the directory emitted as the current working directory in some debugging information formats.

This option is implicitly enabled if debugging information is enabled, but this can be inhibited with the negated form -fno-working-directory. If the -P flag is present in the command line, this option has no effect, since no #line directives are emitted whatsoever. Nothing to see here, moving on ✨

  • -A predicate=answer — make an assertion with the predicate predicate and answer answer. This form is preferred to the older form -A predicate(answer), which is still supported, because it does not use shell special characters. New form ate, honestly 💅
  • -A -predicate=answer — cancel an assertion with the predicate predicate and answer answer. The little minus sign doing the un-asserting, we love a negation icon 🎀
  • -C — do not discard comments. All comments are passed through to the output file, except for comments in processed directives, which are deleted along with the directive.
You should be prepared for side effects when using -C — it causes the preprocessor to treat comments as tokens in their own right. For example, comments appearing at the start of what would be a directive line have the effect of turning that line into an ordinary source line, since the first token on the line is no longer a #. The audacity 😭
  • -CC — do not discard comments, including during macro expansion. This is like -C, except that comments contained within macros are also passed through to the output file where the macro is expanded.

In addition to the side effects of the -C option, the -CC option causes all C++-style comments inside a macro to be converted to C-style comments. This is to prevent later use of that macro from inadvertently commenting out the remainder of the source line. Safety first, babes 🫶

The -CC option is generally used to support lint comments.

  • -P — bestie, this one inhibits generation of linemarkers in the output from the preprocessor 💅. It might be useful when you're running the preprocessor on something that is not C code, and it's gonna be sent to a program that might get confused by the linemarkers. Lowkey a niche save, but iconic.
  • -traditional, -traditional-cpp — these try to imitate the behavior of pre-standard C preprocessors, as opposed to ISO C preprocessors. See the GNU CPP manual for details. Note that GCC does not otherwise attempt to emulate a pre-standard C compiler, and these options are only supported with the -E switch, or when invoking CPP explicitly. So don't just sprinkle them anywhere, okay? 🫶
  • -trigraphs — support ISO C trigraphs. These are three-character sequences, all starting with ??, that are defined by ISO C to stand for single characters. For example, ??/ stands for \, so '??/n' is a character constant for a newline. The nine trigraphs and their replacements are:
Trigraph:       ??(  ??)  ??<  ??>  ??=  ??/  ??'  ??!  ??-
Replacement:      [    ]    {    }    #    \    ^    |    ~

By default, GCC ignores trigraphs, but in standard-conforming modes it converts them. See the -std and -ansi options. ✨

  • -remap — enable special code to work around file systems which only permit very short file names, such as MS-DOS. It's giving "vintage filesystem survival mode" 💀.
  • -H — print the name of each header file used, in addition to other normal activities. Each name is indented to show how deep in the #include stack it is. Precompiled header files are also printed, even if they are found to be invalid; an invalid precompiled header file is printed with ...x and a valid one with ...!. Obsessed with the little depth visuals, ngl 🌸.
  • -dletters — says to make debugging dumps during compilation as specified by letters. The flags documented here are those relevant to the preprocessor. Other letters are interpreted by the compiler proper, or reserved for future versions of GCC, and so are silently ignored. If you specify letters whose behavior conflicts, the result is undefined — so yeah, don't do chaotic combos and expect a cute answer 🫠.
    • -dM — instead of the normal output, generate a list of #define directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor. Assuming you have no file foo.h, the command
touch foo.h; cpp -dM foo.h

shows all the predefined macros. If you use -dM without the -E option, -dM is interpreted as a synonym for -fdump-rtl-mach. Not me finding that plot twist kinda iconic 😭.

  • -dD — like -dM except in two respects: it does not include the predefined macros, and it outputs both the #define directives and the result of preprocessing. Both kinds of output go to the standard output file. Two-for-one behavior, slay 💅.
  • -dN — like -dD, but emit only the macro names, not their expansions. Minimalist queen 🎀.
  • -dI — output #include directives in addition to the result of preprocessing. It's giving "show me the receipts" 🔥.
  • -dU — like -dD except that only macros that are expanded, or whose definedness is tested in preprocessor directives, are output; the output is delayed until the use or test of the macro; and #undef directives are also output for macros tested but undefined at the time. Very "wait for the moment" energy, fr fr ✨.
  • -fdebug-cpp — this option is only useful for debugging GCC. When used from CPP or with -E, it dumps debugging information about location maps. Every token in the output is preceded by the dump of the map its location belongs to. When used from GCC without -E, this option has no effect. So yeah, it's a debug-mode main character only 🧚.
  • -Wp,option — you can use -Wp,option to bypass the compiler driver and pass option directly through to the preprocessor. If option contains commas, it is split into multiple options at the commas. However, many options are modified, translated or interpreted by the compiler driver before being passed to the preprocessor, and -Wp forcibly bypasses this phase. The preprocessor's direct interface is undocumented and subject to change, so whenever possible you should avoid using -Wp and let the driver handle the options instead. > Heads up bestie: this is the "sneak past the driver" route, and it is lowkey risky 😭.
  • -Xpreprocessor option — pass option as an option to the preprocessor. You can use this to supply system-specific preprocessor options that GCC does not recognize. If you want to pass an option that takes an argument, you must use -Xpreprocessor twice, once for the option and once for the argument. Two passes, no cap 🫶.
  • -no-integrated-cpp — perform preprocessing as a separate pass before compilation. By default, GCC performs preprocessing as an integrated part of input tokenization and parsing. If this option is provided, the appropriate language front end (cc1, cc1plus, or cc1obj for C, C++, and Objective-C, respectively) is instead invoked twice, once for preprocessing only and once for actual compilation of the preprocessed input. This option may be useful in conjunction with the -B or -wrapper options to specify an alternate preprocessor or perform additional processing of the program source between normal preprocessing and compilation. It's giving "split the routine into two looks" 💅.
  • -flarge-source-files — adjust GCC to expect large source files, at the expense of slower compilation and higher memory usage. Specifically, GCC normally tracks both column numbers and line numbers within source files and it normally prints both of these numbers in diagnostics. However, once it has processed a certain number of source lines, it stops tracking column numbers and only tracks line numbers. This means that diagnostics for later lines do not include column numbers. It also means that options like -Wmisleading-indentation cease to work at that point, although the compiler prints a note if this happens. Passing -flarge-source-files significantly increases the number of source lines that GCC can process before it stops tracking columns. Big-file energy, but with a memory bill attached 🌈.

🛠️ Passing Options to the Assembler 🛠️

You can pass options to the assembler. Yes bestie, the assembler gets its own little group chat 💖.

  • -Wa,option — pass option as an option to the assembler. If option contains commas, it is split into multiple options at the commas. Comma-separated chaos, but make it useful 🎀.
  • -Xassembler option — pass option as an option to the assembler. You can use this to supply system-specific assembler options that GCC does not recognize. If you want to pass an option that takes an argument, you must use -Xassembler twice, once for the option and once for the argument. Same two-step rule as before, iykyk ✨.

🔗 Options for Linking 🔗

These options come into play when the compiler links object files into an executable output file. They are meaningless if the compiler is not doing a link step. So if there's no linking happening, these are literally just vibes 👑.

  • object-file-name — a file name that does not end in a special recognized suffix is considered to name an object file or library. (Object files are distinguished from libraries by the linker according to the file contents.) If linking is done, these object files are used as input to the linker. File-name detective work, lowkey 🔍.
  • -c, -S, -E — if any of these options is used, then the linker is not run, and object file names should not be used as arguments. No linker, no object-file-name arguments, periodt 💅.
  • -flinker-output=type — this option controls code generation of the link-time optimizer. By default the linker output is automatically determined by the linker plugin. For debugging the compiler and if incremental linking with a non-LTO object file is desired, it may be useful to control the type manually. This one is highkey the "manual override" option 🦋.
    • If type is exec, code generation produces a static binary. In this case -fpic and -fpie are both disabled.
    • If type is dyn, code generation produces a shared library. In this case -fpic or -fPIC is preserved, but not enabled automatically. This allows to build shared libraries without position-independent code on architectures where this is possible, i.e. on x86.
    • If type is pie, code generation produces an -fpie executable. This results in similar optimizations as exec except that -fpie is not disabled if specified at compilation time.
    • If type is rel, the compiler assumes that incremental linking is done. The sections containing intermediate code for link-time optimization are merged, pre-optimized, and output to the resulting object file. In addition, if -ffat-lto-objects is specified, binary code is produced for future non-LTO linking. The object file produced by incremental linking is smaller than a static library produced from the same object files. At link time the result of incremental linking also loads faster than a static library assuming that the majority of objects in the library are used.
    • Finally nolto-rel configures the compiler for incremental linking where code generation is forced, a final binary is produced, and the intermediate code for later link-time optimization is stripped. When multiple object files are linked together the resulting code is better optimized than with link-time optimizations disabled (for example, cross-module inlining happens), but most of benefits of whole program optimizations are lost.

During the incremental link (by -r) the linker plugin defaults to rel. With current interfaces to GNU Binutils it is however not possible to incrementally link LTO objects and non-LTO objects into a single mixed object file. If any of object files in incremental link cannot be used for link-time optimization, the linker plugin issues a warning and uses nolto-rel. To maintain whole program optimization, it is recommended to link such objects into static library instead. Alternatively it is possible to use H.J. Lu's binutils with support for mixed objects. Big optimizer lore, ngl 😭🔥.

  • -fuse-ld=bfd — use the bfd linker instead of the default linker. Linker choice, slay 🎀.
  • -fuse-ld=gold — use the gold linker instead of the default linker. Another linker, another vibe ✨.
  • -fuse-ld=lld — use the LLVM lld linker instead of the default linker. LLVM bestie has entered the chat 💜.
  • -fuse-ld=mold — use the Modern Linker (mold) instead of the default linker. Modern linker, modern energy 🌈.
  • -llibrary, -l library — search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.) The -l option is passed directly to the linker by GCC. Refer to your linker documentation for exact details. The general description below applies to the GNU linker. The linker searches a standard list of directories for the library. The directories searched include several standard system directories plus any that you specify with -L. Library-hunting era, and -L is how you add your own spots to the map 🗺️💖.

Okay so bestie, quick recap of what -l is actually doing: static libraries are literally archives of object files, and their names look like liblibrary.a. Some targets also support shared libraries, which typically have names like liblibrary.so. If both static and shared libraries are found, the linker gives preference to linking with the shared library — unless you're using -static, bestie. Periodt. 💅

And the placement? It genuinely matters where in the command you write this option. The linker searches and processes libraries and object files in the order they are specified. So foo.o -lz bar.o searches library z after file foo.o but before bar.o. And if bar.o refers to functions in z, those functions may not be loaded. 😭 Order is the whole vibe check here, iykyk.


  • -lobjc — you need this special case of the -l option in order to link an Objective-C or Objective-C++ program. that's it, that's the whole thing ✨
  • -nostartfiles — do not use the standard system startup files when linking. the standard system libraries are used normally though, unless -nostdlib, -nolibc, or -nodefaultlibs is used. 🎀
  • -nodefaultlibs — do not use the standard system libraries when linking. only the libraries you specify get passed to the linker, and options specifying linkage of the system libraries — like -static-libgcc or -shared-libgcc — are straight up ignored. the standard startup files are used normally, unless -nostartfiles is used.

Heads up bestie: the compiler may generate calls to "memcmp", "memset", "memcpy" and "memmove". These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified. 👀

  • -nolibc — do not use the C library or system libraries tightly coupled with it when linking. it still links with the startup files, libgcc, or toolchain provided language support libraries such as libgnat, libgfortran or libstdc++ — unless options preventing their inclusion are used as well. this typically removes -lc from the link command line, as well as system libraries that normally go with it and become meaningless when absence of a C library is assumed — for example -lpthread or -lm in some configurations. this is intended for bare-board targets when there is indeed no C library available. living that bare-metal life fr fr 🧚
  • -nostdlib — do not use the standard system startup files or libraries when linking. no startup files and only the libraries you specify are passed to the linker, and options specifying linkage of the system libraries, such as -static-libgcc or -shared-libgcc, are ignored.

The compiler may generate calls to "memcmp", "memset", "memcpy" and "memmove". These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified.

okay so here's the tea ☕ — one of the standard libraries bypassed by -nostdlib and -nodefaultlibs is libgcc.a, a library of internal subroutines which GCC uses to overcome shortcomings of particular machines, or special needs for some languages.

In most cases, you need libgcc.a even when you want to avoid other standard libraries. In other words, when you specify -nostdlib or -nodefaultlibs you should usually specify -lgcc as well. This ensures that you have no unresolved references to internal GCC library subroutines. (An example of such an internal subroutine is "__main", used to ensure C++ constructors are called.) 👑

  • -e entry, --entry=entry — specify that the program entry point is entry. the argument is interpreted by the linker; the GNU linker accepts either a symbol name or an address. ✨
  • -pie — produce a dynamically linked position independent executable on targets that support it. for predictable results, you must also specify the same set of options used for compilation (-fpie, -fPIE, or model suboptions) when you specify this linker option. don't skip the matching flags or it'll be giving chaos 🌀
  • -no-pie — don't produce a dynamically linked position independent executable. simple as that 💅
  • -static-pie — produce a static position independent executable on targets that support it. a static position independent executable is similar to a static executable, but can be loaded at any address without a dynamic linker. for predictable results, you must also specify the same set of options used for compilation (-fpie, -fPIE, or model suboptions) when you specify this linker option.
  • -pthread — link with the POSIX threads library. this option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets. on some targets this option also sets flags for the preprocessor, so it should be used consistently for both compilation and linking. no halfsies, bestie 🫶
  • -r — produce a relocatable object as output. this is also known as partial linking. iconic little shortcut ⭐
  • -rdynamic — pass the flag -export-dynamic to the ELF linker, on targets that support it. this instructs the linker to add all symbols, not only used ones, to the dynamic symbol table. this option is needed for some uses of "dlopen" or to allow obtaining backtraces from within a program. 🔥
  • -s — remove all symbol table and relocation information from the executable. stripped and slaying 💀
  • -static — on systems that support dynamic linking, this overrides -pie and prevents linking with the shared libraries. on other systems, this option has no effect. lowkey just does nothing there, no cap.
  • -shared — produce a shared object which can then be linked with other objects to form an executable. not all systems support this option. for predictable results, you must also specify the same set of options used for compilation (-fpic, -fPIC, or model suboptions) when you specify this linker option.[1] 🦋
  • -shared-libgcc, -static-libgcc — on systems that provide libgcc as a shared library, these options force the use of either the shared or static version, respectively. if no shared version of libgcc was built when the compiler was configured, these options have no effect.

There are several situations in which an application should use the shared libgcc instead of the static version. The most common of these is when the application wishes to throw and catch exceptions across different shared libraries. In that case, each of the libraries as well as the application itself should use the shared libgcc.

Therefore, the G++ driver automatically adds -shared-libgcc whenever you build a shared library or a main executable, because C++ programs typically use exceptions, so this is the right thing to do. 💖

If, instead, you use the GCC driver to create shared libraries, you may find that they are not always linked with the shared libgcc. If GCC finds, at its configuration time, that you have a non-GNU linker or a GNU linker that does not support option --eh-frame-hdr, it links the shared version of libgcc into shared libraries by default. Otherwise, it takes advantage of the linker and optimizes away the linking with the shared version of libgcc, linking with the static version of libgcc by default. This allows exceptions to propagate through such shared libraries, without incurring relocation costs at library load time.

However — and this is the important bit, bestie 🙈 — if a library or main executable is supposed to throw or catch exceptions, you must link it using the G++ driver, or using the option -shared-libgcc, such that it is linked with the shared libgcc.

  • -static-libasan — when the -fsanitize=address option is used to link a program, the GCC driver automatically links against libasan. if libasan is available as a shared library, and the -static option is not used, then this links against the shared version of libasan. the -static-libasan option directs the GCC driver to link libasan statically, without necessarily linking other libraries statically. 🎀
  • -static-libtsan — when the -fsanitize=thread option is used to link a program, the GCC driver automatically links against libtsan. if libtsan is available as a shared library, and the -static option is not used, then this links against the shared version of libtsan. the -static-libtsan option directs the GCC driver to link libtsan statically, without necessarily linking other libraries statically. 🧵
  • -static-liblsan — when the -fsanitize=leak option is used to link a program, the GCC driver automatically links against liblsan. if liblsan is available as a shared library, and the -static option is not used, then this links against the shared version of liblsan. the -static-liblsan option directs the GCC driver to link liblsan statically, without necessarily linking other libraries statically. 💧
  • -static-libubsan — when the -fsanitize=undefined option is used to link a program, the GCC driver automatically links against libubsan. if libubsan is available as a shared library, and the -static option is not used, then this links against the shared version of libubsan. the -static-libubsan option directs the GCC driver to link libubsan statically, without necessarily linking other libraries statically. 🌈
  • -static-libstdc++ — when the g++ program is used to link a C++ program, it normally automatically links against libstdc++. if libstdc++ is available as a shared library, and the -static option is not used, then this links against the shared version of libstdc++. that is normally fine. however, it is sometimes useful to freeze the version of libstdc++ used by the program without going all the way to a fully static link. the -static-libstdc++ option directs the g++ driver to link libstdc++ statically, without necessarily linking other libraries statically. 🧊
  • -symbolic — bind references to global symbols when building a shared object. warn about any unresolved references (unless overridden by the link editor option -Xlinker -z -Xlinker defs). only a few systems support this option. 🤏
  • -T script — use script as the linker script. this option is supported by most systems using the GNU linker. on some targets, such as bare-board targets without an operating system, the -T option may be required when linking to avoid references to undefined symbols. 📜
  • -Xlinker option — pass option as an option to the linker. you can use this to supply system-specific linker options that GCC does not recognize. the escape hatch for when you know things GCC doesn't 👑

okay so continuing from where we left off with -Xlinker — bestie, this next bit matters fr fr:

if you gotta pass an option that takes a separate argument, you need to use -Xlinker twice — once for the option, once for the argument. like, to pass -assert definitions you literally write -Xlinker -assert -Xlinker definitions. and do not write -Xlinker "-assert definitions" because that hands the whole string over as one single argument, which the linker is not expecting. 🫠

when you're using the GNU linker, it's usually way comfier to pass arguments to linker options with the option=value syntax instead of as separate arguments. so like, -Xlinker -Map=output.map instead of -Xlinker -Map -Xlinker output.map. other linkers might not support that syntax for command-line options though, so watch out. 💅


  • -Wl,option — passes option as an option to the linker, periodt. if option contains commas, it gets split into multiple options at the commas — that's the whole trick. you can use this syntax to pass an argument to the option. for example, -Wl,-Map,output.map passes -Map output.map to the linker. and with the GNU linker you can get the same effect with -Wl,-Map=output.map. slay. ✨
  • -u symbol — pretends the symbol symbol is undefined, so the linker is forced to pull in library modules that define it. you can use -u multiple times with different symbols to force loading of extra library modules. 💖
  • -z keyword — -z gets passed straight on through to the linker along with the keyword keyword. for the permitted values and what they actually mean, go read the section in your linker's documentation. iykyk. 👑

these options tell the compiler which directories to search — for header files, for libraries, and for parts of the compiler itself:

  • -I dir, -iquote dir, -isystem dir, -idirafter dir — adds the directory dir to the list of directories searched for header files during preprocessing. if dir begins with = or $SYSROOT, then that = or $SYSROOT gets replaced by the sysroot prefix — see --sysroot and -isysroot for the deets.

directories specified with -iquote apply only to the quote form of the directive, #include "file". directories specified with -I, -isystem, or -idirafter apply to lookup for both the #include "file" and #include <file> directives. 🦋

you can specify any number or combination of these options on the command line to search for header files in several directories. the lookup order is, in order:

  1. For the quote form of the include directive, the directory of the current file is searched first.
  2. For the quote form of the include directive, the directories specified by -iquote options are searched in left-to-right order, as they appear on the command line.
  3. Directories specified with -I options are scanned in left-to-right order.
  4. Directories specified with -isystem options are scanned in left-to-right order.
  5. Standard system directories are scanned.
  6. Directories specified with -idirafter options are scanned in left-to-right order.

you can use -I to override a system header file by substituting your own version, since these directories get searched before the standard system header file directories. but — and this is important — you should not use this option to add directories containing vendor-supplied system header files; use -isystem for that. 🙈

the -isystem and -idirafter options also mark the directory as a system directory, so it gets the same special treatment that's applied to the standard system directories.

if a standard system include directory, or a directory specified with -isystem, is also specified with -I, the -I option gets ignored. the directory is still searched, but as a system directory at its normal position in the system include chain. this is to make sure GCC's procedure for fixing buggy system headers and the ordering for the #include_next directive don't get inadvertently changed. if you genuinely need to change the search order for system directories, use the -nostdinc and/or -isystem options. 💀

  • -I- — split the include path. ⚠️ this option has been deprecated. please use -iquote instead for -I directories before the -I-, and remove the -I- option.

any directories specified with -I options before -I- are searched only for headers requested with #include "file"; they are not searched for #include <file>. if additional directories are specified with -I options after the -I-, those directories are searched for all #include directives.

in addition, -I- inhibits the use of the directory of the current file directory as the first search directory for #include "file". and there's literally no way to override this effect of -I-. 😭

  • -iprefix prefix — specifies prefix as the prefix for subsequent -iwithprefix options. if the prefix represents a directory, you should include the final /.
  • -iwithprefix dir, -iwithprefixbefore dir — appends dir to the prefix specified previously with -iprefix, and adds the resulting directory to the include search path. -iwithprefixbefore puts it in the same place -I would; -iwithprefix puts it where -idirafter would. 🧚
  • -isysroot dir — this one is like the --sysroot option, but it applies only to header files (except for Darwin targets, where it applies to both header files and libraries). see the --sysroot option for more info.
  • -imultilib dir — uses dir as a subdirectory of the directory containing target-specific C++ headers.
  • -nostdinc — do not search the standard system directories for header files. only the directories explicitly specified with -I, -iquote, -isystem, and/or -idirafter options (and the directory of the current file, if appropriate) are searched. 🌸
  • -nostdinc++ — do not search for header files in the C++-specific standard directories, but do still search the other standard directories. (this option is used when building the C++ library.)
  • -iplugindir=dir — sets the directory to search for plugins that are passed by -fplugin=name instead of -fplugin=path/name.so. this option is not meant to be used by the user, but only passed by the driver. noted. 📝
  • -Ldir — adds directory dir to the list of directories to be searched for -l.
  • -Bprefix — this option specifies where to find the executables, libraries, include files, and data files of the compiler itself. iconic, honestly. 👑

the compiler driver program runs one or more of the subprograms cpp, cc1, as and ld. it tries prefix as a prefix for each program it tries to run, both with and without machine/version/ for the corresponding target machine and compiler version.

for each subprogram to be run, the compiler driver first tries the -B prefix, if any. if that name isn't found, or if -B isn't specified, the driver tries two standard prefixes, /usr/lib/gcc/ and /usr/local/lib/gcc/. if neither of those results in a file name that's found, the unmodified program name is searched for using the directories specified in your PATH environment variable.

the compiler checks whether the path provided by -B refers to a directory, and if necessary it adds a directory separator character at the end of the path.

-B prefixes that effectively specify directory names also apply to libraries in the linker, because the compiler translates these options into -L options for the linker. they also apply to include files in the preprocessor, because the compiler translates these options into -isystem options for the preprocessor. in this case, the compiler appends include to the prefix. 💜

the runtime support file libgcc.a can also be searched for using the -B prefix, if needed. if it's not found there, the two standard prefixes above are tried, and that's it — that's all. the file is left out of the link if it's not found by those means. 😬

another way to specify a prefix much like the -B prefix is to use the environment variable GCC_EXEC_PREFIX.

as a special kludge, if the path provided by -B is [dir/]stageN/, where N is a number in the range 0 to 9, then it's replaced by [dir/]include. this is to help with boot-strapping the compiler. silly but valid. 🎀

  • -no-canonical-prefixes — do not expand any symbolic links, resolve references to /../ or /./, or make the path absolute when generating a relative prefix.
  • --sysroot=dir — use dir as the logical root directory for headers and libraries. for example, if the compiler normally searches for headers in /usr/include and libraries in /usr/lib, it instead searches dir/usr/include and dir/usr/lib. 🦋

if you use both this option and the -isysroot option, then the --sysroot option applies to libraries, but the -isysroot option applies to header files.

the GNU linker (beginning with version 2.16) has the necessary support for this option. if your linker doesn't support it, the header file aspect of --sysroot still works, but the library aspect does not. 💀

  • --no-sysroot-suffix — for some targets, a suffix gets added to the root directory specified with --sysroot, depending on the other options used, so headers may for example be found in dir/suffix/usr/include instead of dir/usr/include. this option disables the addition of such a suffix.

🌈 Options for Code Generation Conventions 🌈

these machine-independent options control the interface conventions used in code generation. 🔥

most of them have both positive and negative forms; the negative form of -ffoo is -fno-foo. in the table below, only one of the forms is listed — the one that is not the default. you can figure out the other form by either removing no- or adding it. easy. 💅

  • -fstack-reuse=reuse-level — bestie, this one's the stack-space landlord 🏠 it controls whether the compiler can reuse stack space from your user-declared local/auto variables and the temporaries it generates itself. And reuse_level can be exactly one of these three:
    • all — reuse for everything, all locals and all temporaries. very "share the aux cord" of it.
    • named_vars — reuse only for user-defined local variables that actually have names.
    • none — no stack reuse at all, absolutely not, we're closed 🚫

The default value is all. You need this option when your program stretches the lifetime of a scoped local variable (or a compiler-generated temporary) past the end point the language says it ends at. Like, when a variable's lifetime ends and it lives in memory, the optimizing compiler is fully within its rights to hand that stack space to other temporaries or scoped locals whose live range doesn't overlap it. And legacy code that extends local lifetimes? yeah that's gonna break with the stack reuse optimization, ngl 💀

For example:

int *p;
{
  int local1;

  p = &local1;
  local1 = 10;
  ....
}
{
   int local2;
   local2 = 20;
   ...
}

if (*p == 10)  // out of scope use of local1
  {

  }

Another example:

struct A
{
    A(int k) : i(k), j(k) { }
    int i;
    int j;
};

A *ap;

void foo(const A& ar)
{
   ap = &ar;
}

void bar()
{
   foo(A(10)); // temp object's lifetime ends when foo returns

   {
     A a(20);
     ....
   }
   ap->i+= 10;  // ap references out of scope temp whose space
                // is reused with a. What is the value of ap->i?
}

The lifetime of a compiler-generated temporary is well defined by the C++ standard, okay? When a temporary's lifetime ends and it lives in memory, the optimizing compiler is allowed to reuse that stack space with other temporaries or scoped locals whose live range doesn't overlap. But some legacy code relies on the behavior of older compilers where temporaries' stack space was never reused — and the aggressive stack reuse can lead to runtime errors 😭. So this option exists to control the temporary stack reuse optimization. slay for that.

  • -ftrapv — generates traps for signed overflow on addition, subtraction, and multiplication. just traps. catches it in the act 🔥. The options -ftrapv and -fwrapv override each other, so using -ftrapv -fwrapv on the command-line results in -fwrapv being effective. Note that only active options override, so using -ftrapv -fwrapv -fno-wrapv on the command-line results in -ftrapv being effective. iykyk, order of operations is real.
  • -fwrapv — instructs the compiler to assume that signed arithmetic overflow of addition, subtraction, and multiplication wraps around using twos-complement representation. This flag enables some optimizations and disables others — it's giving balance ✨. The options -ftrapv and -fwrapv override each other, so using -ftrapv -fwrapv on the command-line results in -fwrapv being effective. Note that only active options override, so using -ftrapv -fwrapv -fno-wrapv on the command-line results in -ftrapv being effective.
  • -fwrapv-pointer — instructs the compiler to assume that pointer arithmetic overflow on addition and subtraction wraps around using twos-complement representation. This flag disables some optimizations which assume pointer overflow is invalid. no cap.
  • -fstrict-overflow — implies -fno-wrapv -fno-wrapv-pointer, and when negated implies -fwrapv -fwrapv-pointer. it's basically the vibes of the whole overflow situation in one flag 👑
  • -fexceptions — enable exception handling 💅 generates the extra code needed to propagate exceptions. For some targets, this implies GCC generates frame unwind information for all functions, which can produce significant data size overhead, although it does not affect execution. If you don't specify this option, GCC enables it by default for languages like C++ that normally require exception handling, and disables it for languages like C that don't normally require it. But you may need to enable it when compiling C code that needs to interoperate properly with exception handlers written in C++. You may also wish to disable it if you're compiling older C++ programs that don't use exception handling. considerate king behavior.
  • -fnon-call-exceptions — generate code that allows trapping instructions to throw exceptions. Note that this requires platform-specific runtime support that does not exist everywhere 🙈. Moreover, it only allows trapping instructions to throw exceptions, i.e. memory references or floating-point instructions. It does not allow exceptions to be thrown from arbitrary signal handlers such as "SIGALRM". This enables -fexceptions.
  • -fdelete-dead-exceptions — consider that instructions that may throw exceptions but don't otherwise contribute to the execution of the program can be optimized away. This does not affect calls to functions except those with the "pure" or "const" attributes. This option is enabled by default for the Ada and C++ compilers, as permitted by the language specifications. Optimization passes that cause dead exceptions to be removed are enabled independently at different optimization levels.
  • -funwind-tables — similar to -fexceptions, except it just generates any needed static data and doesn't affect the generated code in any other way. You normally don't need to enable this option; instead, a language processor that needs this handling enables it on your behalf 🫶 like let the professionals handle it.
  • -fasynchronous-unwind-tables — generate an unwind table in DWARF format, if supported by the target machine. The table is exact at each instruction boundary, so it can be used for stack unwinding from asynchronous events (such as debugger or garbage collector). iconic 💜
  • -fno-gnu-unique — on systems with a recent GNU assembler and C library, the C++ compiler uses the "STB_GNU_UNIQUE" binding to make sure that definitions of template static data members and static local variables in inline functions are unique even in the presence of "RTLD_LOCAL". this is necessary to avoid problems with a library used by two different "RTLD_LOCAL" plugins depending on a definition in one of them and therefore disagreeing with the other one about the binding of the symbol. BUT — and this is the plot twist 😭 — this causes "dlclose" to be ignored for affected DSOs. So if your program relies on reinitialization of a DSO via "dlclose" and "dlopen", you can use -fno-gnu-unique.
  • -fpcc-struct-return — return "short" "struct" and "union" values in memory like longer ones, rather than in registers. This convention is less efficient, but it has the advantage of allowing intercallability between GCC-compiled files and files compiled with other compilers, particularly the Portable C Compiler (pcc). friendship bracelets between compilers 🤝

The precise convention for returning structures in memory depends on the target configuration macros.

Short structures and unions are those whose size and alignment match that of some integer type.

⚠️ Warning: code compiled with the -fpcc-struct-return switch is not binary compatible with code compiled with the -freg-struct-return switch. Use it to conform to a non-default application binary interface.
  • -freg-struct-return — return "struct" and "union" values in registers when possible. This is more efficient for small structures than -fpcc-struct-return ⚡

If you specify neither -fpcc-struct-return nor -freg-struct-return, GCC defaults to whichever convention is standard for the target. If there's no standard convention, GCC defaults to -fpcc-struct-return, except on targets where GCC is the principal compiler. In those cases, we can choose the standard, and we chose the more efficient register return alternative. slay, we picked the fast one 💅

⚠️ Warning: code compiled with the -freg-struct-return switch is not binary compatible with code compiled with the -fpcc-struct-return switch. Use it to conform to a non-default application binary interface.
  • -fshort-enums — allocate to an "enum" type only as many bytes as it needs for the declared range of possible values. Specifically, the "enum" type is equivalent to the smallest integer type that has enough room. so efficient ✨
⚠️ Warning: the -fshort-enums switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface.
  • -fshort-wchar — override the underlying type for "wchar_t" to be "short unsigned int" instead of the default for the target. This option is useful for building programs to run under WINE.
⚠️ Warning: the -fshort-wchar switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface.
  • -fcommon — in C code, this option controls the placement of global variables defined without an initializer, known as tentative definitions in the C standard. Tentative definitions are distinct from declarations of a variable with the "extern" keyword, which do not allocate storage. don't mix them up bestie 🙈

The default is -fno-common, which specifies that the compiler places uninitialized global variables in the BSS section of the object file. This inhibits the merging of tentative definitions by the linker so you get a multiple-definition error if the same variable is accidentally defined in more than one compilation unit. yep, you get yelled at 💀

The -fcommon places uninitialized global variables in a common block. This allows the linker to resolve all tentative definitions of the same variable in different compilation units to the same object, or to a non-tentative definition. This behavior is inconsistent with C++, and on many targets implies a speed and code size penalty on global variable references. It's mainly useful to enable legacy code to link without errors. legacy code stays winning ig 😭

  • -fno-ident — ignore the "#ident" directive. that's it. that's the whole thing. short queen 🎀
  • -finhibit-size-directive — pls don't emit a .size assembler directive, or literally anything else that'd cause trouble if the function gets split down the middle and the two halves end up living far apart in memory 🫠. This one's used when compiling crtstuff.c; you should not need it for anything else, bestie.
  • -fverbose-asm — drops extra commentary info into the generated assembly so it's actually readable 💖. Honestly this one's only for the people who genuinely need to read the generated assembly (maybe while debugging the compiler itself, iykyk).

-fno-verbose-asm, the default, omits that extra info and is useful when you're comparing two assembler files.

The added comments include:

  • info on the compiler version and command-line options,
  • the source code lines associated with the assembly instructions, in the form FILENAME:LINENUMBER:CONTENT OF LINE,
  • hints on which high-level expressions correspond to the various assembly instruction operands.

For example, given this C source file:

        int test (int n)
        {
          int i;
          int total = 0;

          for (i = 0; i < n; i++)
            total += i * i;

          return total;
        }

compiling to (x86_64) assembly via -S and emitting the result direct to stdout via -o -

        gcc -S test.c -fverbose-asm -Os -o -

gives output similar to this:

                .file   "test.c"
        # GNU C11 (GCC) version 7.0.0 20160809 (experimental) (x86_64-pc-linux-gnu)
          [...snip...]
        # options passed:
          [...snip...]

                .text
                .globl  test
                .type   test, @function
        test:
        .LFB0:
                .cfi_startproc
        # test.c:4:   int total = 0;
                xorl    %eax, %eax      # <retval>
        # test.c:6:   for (i = 0; i < n; i++)
                xorl    %edx, %edx      # i
        .L2:
        # test.c:6:   for (i = 0; i < n; i++)
                cmpl    %edi, %edx      # n, i
                jge     .L5     #,
        # test.c:7:     total += i * i;
                movl    %edx, %ecx      # i, tmp92
                imull   %edx, %ecx      # i, tmp92
        # test.c:6:   for (i = 0; i < n; i++)
                incl    %edx    # i
        # test.c:7:     total += i * i;
                addl    %ecx, %eax      # tmp92, <retval>
                jmp     .L2     #
        .L5:
        # test.c:10: }
                ret
                .cfi_endproc
        .LFE0:
                .size   test, .-test
                .ident  "GCC: (GNU) 7.0.0 20160809 (experimental)"
                .section        .note.GNU-stack,"",@progbits

These comments are for humans, not machines, so the precise format of them is subject to change 👀 (don't build your whole toolchain around the exact wording, fr).

  • -frecord-gcc-switches — this switch makes the command line used to invoke the compiler get recorded into the object file being created 📝. It's only implemented on some targets, and the exact format of the recording depends on the target and binary file format, but it usually takes the form of a section containing ASCII text. Related to -fverbose-asm, except that one only records info in the assembler output file as comments, so it never reaches the object file. Also peep -grecord-gcc-switches for another way of stashing compiler options into the object file 💅.
  • -fpic — generate position-independent code (PIC) suitable for use in a shared library, if the target machine supports it ✨. Code like this accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts (the dynamic loader is not part of GCC — it's part of the operating system, fyi). If the GOT size for the linked executable blows past a machine-specific maximum size, you get an error message from the linker saying -fpic doesn't work; in that case, recompile with -fPIC instead. (These maximums are 8k on the SPARC, 28k on AArch64 and 32k on the m68k and RS/6000. The x86 has no such limit, slay.)

Position-independent code requires special support, so it only works on certain machines. For the x86, GCC supports PIC for System V but not for the Sun 386i. Code generated for the IBM RS/6000 is always position-independent.

When this flag is set, the macros __pic__ and __PIC__ are defined to 1.

  • -fPIC — if the target machine supports it, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table 🌈. This option actually makes a difference on AArch64, m68k, PowerPC and SPARC.

Position-independent code requires special support, so it only works on certain machines.

When this flag is set, the macros __pic__ and __PIC__ are defined to 2.

  • -fpie, -fPIE — these are similar to -fpic and -fPIC, but the generated position-independent code can only be linked into executables 🎀. Usually you use these to compile code that'll be linked using the -pie GCC option.

-fpie and -fPIE both define the macros __pie__ and __PIE__. Those macros have the value 1 for -fpie and 2 for -fPIE.

  • -fno-plt — do not use the PLT for external function calls in position-independent code 💀. Instead, load the callee address at call sites from the GOT and branch to it. This gives more efficient code by eliminating PLT stubs and exposing GOT loads to optimizations. On architectures like 32-bit x86 where PLT stubs expect the GOT pointer in a specific register, this gives the compiler more register allocation freedom. Lazy binding requires the PLT; with -fno-plt all external symbols are resolved at load time.

Alternatively, the function attribute noplt can be used to avoid calls through the PLT for specific external functions.

In position-dependent code, a few targets also convert calls to functions marked to not use the PLT to use the GOT instead.

  • -fno-jump-tables — do not use jump tables for switch statements even where it'd be more efficient than other code generation strategies 🙈. Useful alongside -fpic or -fPIC for building code that forms part of a dynamic linker and can't reference the address of a jump table. On some targets, jump tables don't require a GOT and this option isn't needed.
  • -fno-bit-tests — do not use bit tests for switch statements even where it'd be more efficient than other code generation strategies. Periodt.
  • -ffixed-reg — treat the register named reg as a fixed register; generated code should never refer to it (except maybe as a stack pointer, frame pointer, or in some other fixed role) 🔒.

reg must be the name of a register. The register names accepted are machine-specific and are defined in the REGISTER_NAMES macro in the machine description macro file.

This flag does not have a negative form, because it specifies a three-way choice. (No -fno-fixed-reg bestie, that's not a thing.)

  • -fcall-used-reg — treat the register named reg as an allocable register that gets clobbered by function calls 💥. It may be allocated for temporaries or variables that don't live across a call. Functions compiled this way do not save and restore the register reg.
It is an error to use this flag with the frame pointer or stack pointer. Using this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results 😭.

This flag does not have a negative form, because it specifies a three-way choice.

  • -fcall-saved-reg — treat the register named reg as an allocable register saved by functions 🫶. It may be allocated even for temporaries or variables that live across a call. Functions compiled this way save and restore the register reg if they use it.
It is an error to use this flag with the frame pointer or stack pointer. Using this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results.

And a different sort of disaster results from using this flag for a register in which function values may be returned 💀.

This flag does not have a negative form, because it specifies a three-way choice.

  • -fpack-struct[=n] — without a value specified, pack all structure members together without holes 🍓. When a value n is specified (which must be a small power of two), pack structure members according to that value, representing the maximum alignment (that is, objects with default alignment requirements larger than this are output potentially unaligned at the next fitting location).
Warning: the -fpack-struct switch causes GCC to generate code that is not binary compatible with code generated without that switch. It also makes the code suboptimal. Use it to conform to a non-default application binary interface, k?
  • -fleading-underscore — this option and its counterpart, -fno-leading-underscore, forcibly change the way C symbols are represented in the object file 🦋. One use is to help link with legacy assembly code.
Warning: the -fleading-underscore switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface. Not all targets provide complete support for this switch, ngl.
  • -ftls-model=model — alters the thread-local storage model to be used 🧚. The model argument should be one of global-dynamic, local-dynamic, initial-exec or local-exec. Note that the choice is subject to optimization: the compiler may use a more efficient model for symbols not visible outside of the translation unit, or if -fpic isn't given on the command line.

The default without -fpic is initial-exec; with -fpic the default is global-dynamic. 💅


  • -ftrampolines — okay so for targets that normally need trampolines for nested functions, this makes GCC always generate them instead of using descriptors. For targets that don't need them — like HP-PA or IA-64, bestie — it does literally nothing.

Quick vibe check on what a trampoline even is: it's a tiny piece of code created at run time on the stack when the address of a nested function gets taken, and it's used to call that nested function indirectly. Which means… yeah, it requires the stack to be made executable for the program to work properly. 🫠

-fno-trampolines is enabled by default on a language-by-language basis, letting the compiler dodge generating them if it computes that this is safe, and swap in descriptors instead. Descriptors are made up of data only, but the generated code has to be prepared to deal with them. As of this writing, -fno-trampolines is enabled by default only for Ada.

Also — and this is the serious part — code compiled with -ftrampolines and code compiled with -fno-trampolines are not binary compatible if nested functions are present. So this option must be used on a program-wide basis and be manipulated with extreme care. 🚨

For languages other than Ada, the -ftrampolines and -fno-trampolines options currently have no effect, and trampolines are always generated on platforms that need them for nested functions.

  • -fvisibility=[default|internal|hidden|protected] — sets the default ELF image symbol visibility to whatever you picked: all symbols get marked with it unless overridden inside the code. Using this can very substantially improve linking and load times of shared object libraries, produce more optimized code, provide near-perfect API export, and prevent symbol clashes. Honestly? It is strongly recommended that you use this in any shared objects you distribute. Periodt. 💅

Despite the nomenclature, default always means public — i.e. available to be linked against from outside the shared object. protected and internal are pretty useless in real-world usage, so the only other commonly used option is hidden. The default if -fvisibility isn't specified is default, i.e. make every symbol public.

A good explanation of the benefits of ensuring ELF symbols have the correct visibility is given by "How To Write Shared Libraries" by Ulrich Drepper (which can be found at <https://www.akkadia.org/drepper/>) — however a superior solution made possible by this option to marking things hidden when the default is public is to make the default hidden and mark things public. That's the norm with DLLs on Windows, and with -fvisibility=hidden and "__attribute__ ((visibility("default")))" instead of "__declspec(dllexport)" you get almost identical semantics with identical syntax. Total win for anyone working with cross-platform projects. ✨

For those adding visibility support to existing code, you may find "#pragma GCC visibility" of use. It works by you enclosing the declarations you wish to set visibility for with (for example) "#pragma GCC visibility push(hidden)" and "#pragma GCC visibility pop". Bear in mind that symbol visibility should be viewed as part of the API interface contract, so all new code should always specify visibility when it is not the default — i.e., declarations only for use within the local DSO should always be marked explicitly as hidden so as to avoid PLT indirection overheads. Making this abundantly clear also aids readability and self-documentation of the code. Note that due to ISO C++ specification requirements, "operator new" and "operator delete" must always be of default visibility.

Be aware that headers from outside your project — in particular system headers and headers from any other library you use — may not be expecting to be compiled with visibility other than the default. You may need to explicitly say "#pragma GCC visibility push(default)" before including any such headers. 🙈

"extern" declarations are not affected by -fvisibility, so a lot of code can be recompiled with -fvisibility=hidden with no modifications. However, this means that calls to "extern" functions with no explicit visibility use the PLT, so it is more effective to use "__attribute ((visibility))" and/or "#pragma GCC visibility" to tell the compiler which "extern" declarations should be treated as hidden.

Note that -fvisibility does affect C++ vague linkage entities. This means that, for instance, an exception class that is thrown between DSOs must be explicitly marked with default visibility so that the type_info nodes are unified between the DSOs.

An overview of these techniques, their benefits and how to use them is at <https://gcc.gnu.org/wiki/Visibility>. 🦋

  • -fstrict-volatile-bitfields — use this if accesses to volatile bit-fields (or other structure fields, although the compiler usually honors those types anyway) should use a single access of the width of the field's type, aligned to natural alignment if possible. For example, targets with memory-mapped peripheral registers might require all such accesses to be 16 bits wide; with this flag you can declare all peripheral bit-fields as "unsigned short" (assuming short is 16 bits on these targets) to force GCC to use 16-bit accesses instead of, perhaps, a more efficient 32-bit access.

If this option is disabled, the compiler uses the most efficient instruction. In the previous example, that might be a 32-bit load instruction, even though that accesses bytes that do not contain any portion of the bit-field, or memory-mapped registers unrelated to the one being updated. 💀

In some cases, such as when the "packed" attribute is applied to a structure field, it may not be possible to access the field with a single read or write that is correctly aligned for the target machine. In this case GCC falls back to generating multiple accesses rather than code that will fault or truncate the result at run time.

Note: Due to restrictions of the C/C++11 memory model, write accesses are not allowed to touch non bit-field members. It is therefore recommended to define all bits of the field's type as bit-field members.

The default value of this option is determined by the application binary interface for the target processor.

  • -fsync-libcalls — controls whether any out-of-line instance of the "__sync" family of functions may be used to implement the C++11 "__atomic" family of functions.

The default value of this option is enabled, so the only useful form of the option is -fno-sync-libcalls. This option is used in the implementation of the libatomic runtime library. 🧚


🛠️ GCC Developer Options 🛠️

This section describes command-line options that are primarily of interest to GCC developers — including options to support compiler testing and investigation of compiler bugs and compile-time performance problems. That includes options that produce debug dumps at various points in the compilation, options that print statistics such as memory use and execution time, and options that print information about GCC's configuration, such as where it searches for libraries. You should rarely need to use any of these options for ordinary compilation and linking tasks. Like, fr fr, this is dev-hours territory. 👑

Many developer options that cause GCC to dump output to a file take an optional =filename suffix. You can specify stdout or - to dump to standard output, and stderr for standard error. 🌈

If =filename is omitted, a default dump file name is constructed by concatenating the base dump file name, a pass number, phase letter, and pass name. The base dump file name is the name of the output file produced by the compiler if explicitly specified and not an executable; otherwise it is the source file name. The pass number is determined by the order passes are registered with the compiler's pass manager. This is generally the same as the order of execution, but passes registered by plugins, target-specific passes, or passes that are otherwise registered late are numbered higher than the pass named final, even if they are executed earlier. The phase letter is one of i (inter-procedural analysis), l (language-specific), r (RTL), or t (tree). The files are created in the directory of the output file.

  • -fcallgraph-info
  • -fcallgraph-info=MARKERS — makes the compiler output callgraph information for the program, on a per-object-file basis. The info is generated in the common VCG format. It can be decorated with additional, per-node and/or per-edge information if you also specify a list of comma-separated markers. When the "su" marker is specified, the callgraph is decorated with stack usage information; it's equivalent to -fstack-usage. When the "da" marker is specified, the callgraph is decorated with information about dynamically allocated objects.

When compiling with -flto, no callgraph information is output along with the object file. At LTO link time, -fcallgraph-info may generate multiple callgraph information files next to intermediate LTO output files.

  • -dletters
  • -fdump-rtl-pass
  • -fdump-rtl-pass=filename — says to make debugging dumps during compilation at times specified by letters. This is used for debugging the RTL-based passes of the compiler.

Some -dletters switches have different meaning when -E is used for preprocessing.

Debug dumps can be enabled with a -fdump-rtl switch or some -d option letters. Here are the possible letters for use in pass and letters, and their meanings: 🎀

  • -fdump-rtl-alignments — dump after branch alignments have been computed.
  • -fdump-rtl-asmcons — dump after fixing rtl statements that have unsatisfied in/out constraints.
  • -fdump-rtl-auto_inc_dec — dump after auto-inc-dec discovery. This pass is only run on architectures that have auto inc or auto dec instructions.
  • -fdump-rtl-barriers — dump after cleaning up the barrier instructions.
  • -fdump-rtl-bbpart — dump after partitioning hot and cold basic blocks.
  • -fdump-rtl-bbro — dump after block reordering.
  • -fdump-rtl-btl1
  • -fdump-rtl-btl2 — -fdump-rtl-btl1 and -fdump-rtl-btl2 enable dumping after the two branch target load optimization passes.
  • -fdump-rtl-bypass — dump after jump bypassing and control flow optimizations.
  • -fdump-rtl-combine — dump after the RTL instruction combination pass 💅
  • -fdump-rtl-compgotos — dump after duplicating the computed gotos.
  • -fdump-rtl-ce1, -fdump-rtl-ce2, -fdump-rtl-ce3 — these three enable dumping after the three if conversion passes ✨
  • -fdump-rtl-cprop_hardreg — dump after hard register copy propagation.
  • -fdump-rtl-csa — dump after combining stack adjustments.
  • -fdump-rtl-cse1, -fdump-rtl-cse2 — enable dumping after the two common subexpression elimination passes.
  • -fdump-rtl-dce — dump after the standalone dead code elimination passes.
  • -fdump-rtl-dbr — dump after delayed branch scheduling.
  • -fdump-rtl-dce1, -fdump-rtl-dce2 — enable dumping after the two dead store elimination passes.
  • -fdump-rtl-eh — dump after finalization of EH handling code.
  • -fdump-rtl-eh_ranges — dump after conversion of EH handling range regions.
  • -fdump-rtl-expand — dump after RTL generation.
  • -fdump-rtl-fwprop1, -fdump-rtl-fwprop2 — enable dumping after the two forward propagation passes.
  • -fdump-rtl-gcse1, -fdump-rtl-gcse2 — enable dumping after global common subexpression elimination.
  • -fdump-rtl-init-regs — dump after the initialization of the registers.
  • -fdump-rtl-initvals — dump after the computation of the initial value sets.
  • -fdump-rtl-into_cfglayout — dump after converting to cfglayout mode.
  • -fdump-rtl-ira — dump after iterated register allocation.
  • -fdump-rtl-jump — dump after the second jump optimization.
  • -fdump-rtl-loop2 — enables dumping after the rtl loop optimization passes 🔁
  • -fdump-rtl-mach — dump after performing the machine dependent reorganization pass, if that pass exists (yes, the "if" is doing heavy lifting there 🙈).
  • -fdump-rtl-mode_sw — dump after removing redundant mode switches.
  • -fdump-rtl-rnreg — dump after register renumbering.
  • -fdump-rtl-outof_cfglayout — dump after converting from cfglayout mode.
  • -fdump-rtl-peephole2 — dump after the peephole pass.
  • -fdump-rtl-postreload — dump after post-reload optimizations.
  • -fdump-rtl-pro_and_epilogue — dump after generating the function prologues and epilogues.
  • -fdump-rtl-sched1, -fdump-rtl-sched2 — enable dumping after the basic block scheduling passes.
  • -fdump-rtl-ree — dump after sign/zero extension elimination.
  • -fdump-rtl-seqabstr — dump after common sequence discovery.
  • -fdump-rtl-shorten — dump after shortening branches.
  • -fdump-rtl-sibling — dump after sibling call optimizations.
  • -fdump-rtl-split1, -fdump-rtl-split2, -fdump-rtl-split3, -fdump-rtl-split4, -fdump-rtl-split5 — these enable dumping after five rounds of instruction splitting. five. 🫠
  • -fdump-rtl-sms — dump after modulo scheduling. this pass is only run on some architectures, so don't come for it if it's quiet on yours 🤷‍♀️
  • -fdump-rtl-stack — dump after conversion from GCC's "flat register file" registers to the x87's stack-like registers. this pass only runs on x86 variants, bestie 🖥️
  • -fdump-rtl-subreg1, -fdump-rtl-subreg2 — enable dumping after the two subreg expansion passes.
  • -fdump-rtl-unshare — dump after all rtl has been unshared.
  • -fdump-rtl-vartrack — dump after variable tracking.
  • -fdump-rtl-vregs — dump after converting virtual registers to hard registers.
  • -fdump-rtl-web — dump after live range splitting.
  • -fdump-rtl-regclass, -fdump-rtl-subregs_of_mode_init, -fdump-rtl-subregs_of_mode_finish, -fdump-rtl-dfinit, -fdump-rtl-dfinish — okay so these dumps are defined but always produce empty files 💀 iconic behavior honestly
  • -da, -fdump-rtl-all — produce all the dumps listed above. all of them. every last one 👑
  • -dA — annotate the assembler output with miscellaneous debugging information.
  • -dD — dump all macro definitions, at the end of preprocessing, in addition to normal output.
  • -dH — produce a core dump whenever an error occurs.
  • -dp — annotate the assembler output with a comment indicating which pattern and alternative is used. the length and cost of each instruction are also printed 📏
  • -dP — dump the RTL in the assembler output as a comment before each instruction. also turns on -dp annotation.
  • -dx — just generate RTL for a function instead of compiling it. usually used with -fdump-rtl-expand.

  • -fdump-debug — dump debugging information generated during the debug generation phase 🐛
  • -fdump-earlydebug — dump debugging information generated during the early debug generation phase.
  • -fdump-noaddr — when doing debugging dumps, suppress address output. this makes it more feasible to use diff on debugging dumps for compiler invocations with different compiler binaries and/or different text / bss / data / heap / stack / dso start locations. fr fr it's a diff-friendly era ✨
  • -freport-bug — collect and dump debug information into a temporary file if an internal compiler error (ICE) occurs. yes bestie, when it crashes it saves the receipts 🧾
  • -fdump-unnumbered — when doing debugging dumps, suppress instruction numbers and address output. this makes it more feasible to use diff on debugging dumps for compiler invocations with different options, in particular with and without -g.
  • -fdump-unnumbered-links — when doing debugging dumps (see -d option above), suppress instruction numbers for the links to the previous and next instructions in a sequence.

💅 -fdump-ipa era

  • -fdump-ipa-switch, -fdump-ipa-switch-options — control the dumping at various stages of inter-procedural analysis language tree to a file. the file name is generated by appending a switch specific suffix to the source file name, and the file is created in the same directory as the output file. the following dumps are possible:
    • all — enables all inter-procedural analysis dumps.
    • cgraph — dumps information about call-graph optimization, unused function removal, and inlining decisions.
    • inline — dump after function inlining.

additionally, the options -optimized, -missed, -note, and -all can be provided, with the same meaning as for -fopt-info, defaulting to -optimized 🎀

for example, -fdump-ipa-inline-optimized-missed will emit information on callsites that were inlined, along with callsites that were not inlined. the girls who get it, get it 😌

by default, the dump will contain messages about successful optimizations (equivalent to -optimized) together with low-level details about the analysis.


  • -fdump-lang — dump language-specific information. the file name is made by appending .lang to the source file name.
  • -fdump-lang-all, -fdump-lang-switch, -fdump-lang-switch-options, -fdump-lang-switch-options=filename — control the dumping of language-specific information. the options and filename portions behave as described in the -fdump-tree option. the following switch values are accepted:
    • all — enable all language-specific dumps.
    • class — dump class hierarchy information. virtual table information is emitted unless 'slim' is specified. this option is applicable to C++ only.
    • module — dump module information. options lineno (locations), graph (reachability), blocks (clusters), uid (serialization), alias (mergeable), asmname (Elrond), eh (mapper) & vops (macros) may provide additional information. this option is applicable to C++ only. (yes, "Elrond". we don't ask questions 🧝‍♂️)
    • raw — dump the raw internal tree data. this option is applicable to C++ only.
  • -fdump-passes — print on stderr the list of optimization passes that are turned on and off by the current command-line options. a whole vibe check for your passes ✅
  • -fdump-statistics-option — enable and control dumping of pass statistics in a separate file. the file name is generated by appending a suffix ending in .statistics to the source file name, and the file is created in the same directory as the output file. if the -option form is used, -stats causes counters to be summed over the whole compilation unit while -details dumps every event as the passes generate them. the default with no option is to sum counters for each function compiled 📊

🌸 the -fdump-tree section

  • -fdump-tree-all, -fdump-tree-switch, -fdump-tree-switch-options, -fdump-tree-switch-options=filename — control the dumping at various stages of processing the intermediate language tree to a file. if the -options form is used, options is a list of - separated options which control the details of the dump. not all options are applicable to all dumps; those that are not meaningful are ignored (no drama, they just chill). the following options are available:
    • address — print the address of each node. usually this is not meaningful as it changes according to the environment and source file. its primary use is for tying up a dump file with a debug environment.
    • asmname — if "DECL_ASSEMBLER_NAME" has been set for a given decl, use that in the dump instead of "DECL_NAME". its primary use is ease of use working backward from mangled names in the assembly file.
    • slim — when dumping front-end intermediate representations, inhibit dumping of members of a scope or body of a function merely because that scope has been reached. only dump such items when they are directly reachable by some other path.

when dumping pretty-printed trees, this option inhibits dumping the bodies of control structures.

when dumping RTL, print the RTL in slim (condensed) form instead of the default LISP-like representation.

  • raw — print a raw representation of the tree. by default, trees are pretty-printed into a C-like representation.

Okay so these next bits are the sub-options you can tack onto the dump flags — they’re like the little accessories that make your dump look extra 💅

  • details — Enable more detailed dumps (but lowkey not every dump option honors it, no cap). It also pulls in information from the optimization passes. ✨
  • stats — Enable dumping various statistics about the pass (again, not every dump option honors this one either).
  • blocks — Enable showing basic block boundaries (disabled in raw dumps).
  • graph — For each of the other indicated dump files (-fdump-rtl-pass), dump a representation of the control flow graph suitable for viewing with GraphViz to file.passid.pass.dot. Each function in the file is pretty-printed as a subgraph, so that GraphViz can render them all in a single plot. 🎀 Heads up: this option currently only works for RTL dumps, and the RTL is always dumped in slim form.
  • vops — Enable showing virtual operands for every statement.
  • lineno — Enable showing line numbers for statements.
  • uid — Enable showing the unique ID ("DECL_UID") for each variable.
  • verbose — Enable showing the tree dump for each statement.
  • eh — Enable showing the EH region number holding each statement.
  • scev — Enable showing scalar evolution analysis details.
  • optimized — Enable showing optimization information (only available in certain passes).
  • missed — Enable showing missed optimization information (only available in certain passes).
  • note — Enable other detailed optimization information (only available in certain passes).
  • all — Turn on all options, except raw, slim, verbose and lineno.
  • optall — Turn on all optimization options, i.e., optimized, missed, and note.

So to figure out what tree dumps are available or to find the dump for a pass you care about, follow these steps, bestie:

  1. Invoke GCC with -fdump-passes and in the stderr output look for a code that corresponds to the pass you are interested in. For example, the codes "tree-evrp", "tree-vrp1", and "tree-vrp2" correspond to the three Value Range Propagation passes. The number at the end distinguishes distinct invocations of the same pass. 👑
  2. To enable the creation of the dump file, append the pass code to the -fdump- option prefix and invoke GCC with it. For example, to enable the dump from the Early Value Range Propagation pass, invoke GCC with the -fdump-tree-evrp option. Optionally, you may specify the name of the dump file. If you don’t specify one, GCC creates as described below. ✨
  3. Find the pass dump in a file whose name is composed of three components separated by a period: the name of the source file GCC was invoked to compile, a numeric suffix indicating the pass number followed by the letter t for tree passes (and the letter r for RTL passes), and finally the pass code. For example, the Early VRP pass dump might be in a file named myfile.c.038t.evrp in the current working directory. Note that the numeric codes are not stable and may change from one version of GCC to another. 🫶

💬 -fopt-info, -fopt-info-options, -fopt-info-options=filename 💬

Controls optimization dumps from various optimization passes. If the -options form is used, options is a list of - separated option keywords to select the dump details and optimizations.

The options can be divided into three groups:

  1. options describing what kinds of messages should be emitted,
  2. options describing the verbosity of the dump, and
  3. options describing which optimizations should be included.

The options from each group can be freely mixed as they are non-overlapping. However, in case of any conflicts, the later options override the earlier options on the command line.

The following options control which kinds of messages should be emitted:

  • optimized — Print information when an optimization is successfully applied. It is up to a pass to decide which information is relevant. For example, the vectorizer passes print the source location of loops which are successfully vectorized. 🔥
  • missed — Print information about missed optimizations. Individual passes control which information to include in the output.
  • note — Print verbose information about optimizations, such as certain transformations, more detailed messages about decisions etc.
  • all — Print detailed optimization information. This includes optimized, missed, and note.

The following option controls the dump verbosity:

  • internals — By default, only “high-level” messages are emitted. This option enables additional, more detailed, messages, which are likely to only be of interest to GCC developers. 🤓

One or more of the following option keywords can be used to describe a group of optimizations:

  • ipa — Enable dumps from all interprocedural optimizations.
  • loop — Enable dumps from all loop optimizations.
  • inline — Enable dumps from all inlining optimizations.
  • omp — Enable dumps from all OMP (Offloading and Multi Processing) optimizations.
  • vec — Enable dumps from all vectorization optimizations.
  • optall — Enable dumps from all optimizations. This is a superset of the optimization groups listed above.

If options is omitted, it defaults to optimized-optall, which means to dump messages about successful optimizations from all the passes, omitting messages that are treated as “internals”.

If the filename is provided, then the dumps from all the applicable optimizations are concatenated into the filename. Otherwise the dump is output onto stderr. Though multiple -fopt-info options are accepted, only one of them can include a filename. If other filenames are provided then all but the first such option are ignored.

Note that the output filename is overwritten in case of multiple translation units. If a combined output from multiple translation units is desired, stderr should be used instead. 😭

In the following example, the optimization info is output to stderr:

gcc -O3 -fopt-info

This example:

gcc -O3 -fopt-info-missed=missed.all

outputs missed optimization report from all the passes into missed.all, and this one:

gcc -O2 -ftree-vectorize -fopt-info-vec-missed

prints information about missed optimization opportunities from vectorization passes on stderr. Note that -fopt-info-vec-missed is equivalent to -fopt-info-missed-vec. The order of the optimization group names and message types listed after -fopt-info does not matter. 🌈

As another example,

gcc -O3 -fopt-info-inline-optimized-missed=inline.txt

outputs information about missed optimizations as well as optimized locations from all the inlining passes into inline.txt.

Finally, consider:

gcc -fopt-info-vec-missed=vec.miss -fopt-info-loop-optimized=loop.opt

Here the two output filenames vec.miss and loop.opt are in conflict since only one output file is allowed. In this case, only the first option takes effect and the subsequent options are ignored. Thus only vec.miss is produced which contains dumps from the vectorizer about missed opportunities. 💀

📝 -fsave-optimization-record 📝

Write a SRCFILE.opt-record.json.gz file detailing what optimizations were performed, for those optimizations that support -fopt-info.

This option is experimental and the format of the data within the compressed JSON file is subject to change. 🙈

It is roughly equivalent to a machine-readable version of -fopt-info-all, as a collection of messages with source file, line number and column number, with the following additional data for each message:

  • the execution count of the code being optimized, along with metadata about whether this was from actual profile data, or just an estimate, allowing consumers to prioritize messages by code hotness,
  • the function name of the code being optimized, where applicable,
  • the “inlining chain” for the code being optimized, so that when a function is inlined into several different places (which might themselves be inlined), the reader can distinguish between the copies,
  • objects identifying those parts of the message that refer to expressions, statements or symbol-table nodes, which of these categories they are, and, when available, their source code location,
  • the GCC pass that emitted the message, and
  • the location in GCC’s own code from which the message was emitted

Additionally, some messages are logically nested within other messages, reflecting implementation details of the optimization passes.

⏱️ -fsched-verbose=n ⏱️

On targets that use instruction scheduling, this option controls the amount of debugging output the scheduler prints to the dump files.

For n greater than zero, -fsched-verbose outputs the same information as -fdump-rtl-sched1 and -fdump-rtl-sched2. For n greater than one, it also outputs basic block probabilities, detailed ready list information and unit/insn info. For n greater than two, it includes RTL at abort point, control-flow and regions info. And for n over four, -fsched-verbose also includes dependence info. 🎯

🎛️ -fenable-kind-pass, -fdisable-kind-pass=range-list 🎛️

This is a set of options that are used to explicitly disable/enable optimization passes. These options are intended for use for debugging GCC. Compiler users should use regular options for enabling/disabling passes instead. 🧚

  • -fdisable-ipa-pass — Disable IPA pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended with a sequential number starting from 1.

okay bestie, these next flags are the compiler’s little diagnostic knobs and pass-controllers, and they are so specific — let’s keep every detail exactly where it belongs 💅

  • -fdisable-rtl-pass, -fdisable-rtl-pass=range-list — Disable RTL pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended with a sequential number starting from 1. range-list is a comma-separated list of function ranges or assembler names. Each range is a number pair separated by a colon. The range is inclusive in both ends. If the range is trivial, the number pair can be simplified as a single number. If the function’s call graph node’s uid falls within one of the specified ranges, the pass is disabled for that function. The uid is shown in the function header of a dump file, and the pass names can be dumped by using option -fdump-passes.
  • -fdisable-tree-pass, -fdisable-tree-pass=range-list — Disable tree pass pass. See -fdisable-rtl for the description of option arguments.
  • -fenable-ipa-pass — Enable IPA pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended with a sequential number starting from 1.
  • -fenable-rtl-pass, -fenable-rtl-pass=range-list — Enable RTL pass pass. See -fdisable-rtl for option argument description and examples.
  • -fenable-tree-pass, -fenable-tree-pass=range-list — Enable tree pass pass. See -fdisable-rtl for the description of option arguments.

Here are some examples showing uses of these options.

# disable ccp1 for all functions
   -fdisable-tree-ccp1
# disable complete unroll for function whose cgraph node uid is 1
   -fenable-tree-cunroll=1
# disable gcse2 for functions at the following ranges [1,1],
# [300,400], and [400,1000]
# disable gcse2 for functions foo and foo2
   -fdisable-rtl-gcse2=foo,foo2
# disable early inlining
   -fdisable-tree-einline
# disable ipa inlining
   -fdisable-ipa-inline
# enable tree full unroll
   -fenable-tree-unroll
  • -fchecking, -fchecking=n — Enable internal consistency checking. The default depends on the compiler configuration. -fchecking=2 enables further internal consistency checking that might affect code generation.
  • -frandom-seed=string — This option provides a seed that GCC uses in place of random numbers in generating certain symbol names that have to be different in every compiled file. It is also used to place unique stamps in coverage data files and the object files that produce them. You can use the -frandom-seed option to produce reproducibly identical object files.

The string can either be a number (decimal, octal or hex) or an arbitrary string (in which case it’s converted to a number by computing CRC32).

The string should be different for every file you compile. 🫶
  • -save-temps — Store the usual “temporary” intermediate files permanently; name them as auxiliary output files, as specified described under -dumpbase and -dumpdir.

When used in combination with the -x command-line option, -save-temps is sensible enough to avoid overwriting an input source file with the same extension as an intermediate file. The corresponding intermediate file may be obtained by renaming the source file before using -save-temps.

  • -save-temps=cwd — Equivalent to -save-temps -dumpdir ./..
  • -save-temps=obj — Equivalent to -save-temps -dumpdir outdir/, where outdir/ is the directory of the output file specified after the -o option, including any directory separators. If the -o option is not used, the -save-temps=obj switch behaves like -save-temps=cwd.
  • -time[=file] — Report the CPU time taken by each subprocess in the compilation sequence. For C source files, this is the compiler proper and assembler (plus the linker if linking is done).

Without the specification of an output file, the output looks like this:

# cc1 0.12 0.01
# as 0.00 0.01

The first number on each line is the “user time”, that is time spent executing the program itself. The second number is “system time”, time spent executing operating system routines on behalf of the program. Both numbers are in seconds.

With the specification of an output file, the output is appended to the named file, and it looks like this:

0.12 0.01 cc1 <options>
0.00 0.01 as <options>

The “user time” and the “system time” are moved before the program name, and the options passed to the program are displayed, so that one can later tell what file was being compiled, and with which options.

  • -fdump-final-insns[=file] — Dump the final internal representation (RTL) to file. If the optional argument is omitted (or if file is .), the name of the dump file is determined by appending .gkd to the dump base name, see -dumpbase.
  • -fcompare-debug[=opts] — If no error occurs during compilation, run the compiler a second time, adding opts and -fcompare-debug-second to the arguments passed to the second compilation. Dump the final internal representation in both compilations, and print an error if they differ.

If the equal sign is omitted, the default -gtoggle is used.

The environment variable GCC_COMPARE_DEBUG, if defined, non-empty and nonzero, implicitly enables -fcompare-debug. If GCC_COMPARE_DEBUG is defined to a string starting with a dash, then it is used for opts, otherwise the default -gtoggle is used.

-fcompare-debug= (with the equal sign but without opts) is equivalent to -fno-compare-debug, which disables the dumping of the final representation and the second compilation, preventing even GCC_COMPARE_DEBUG from taking effect.

To verify full coverage during -fcompare-debug testing, set GCC_COMPARE_DEBUG to say -fcompare-debug-not-overridden, which GCC rejects as an invalid option in any actual compilation (rather than preprocessing, assembly or linking). To get just a warning, setting GCC_COMPARE_DEBUG to -w%n-fcompare-debug not overridden will do.

  • -fcompare-debug-second — This option is implicitly passed to the compiler for the second compilation requested by -fcompare-debug, along with options to silence warnings, and omitting other options that would cause the compiler to produce output to files or to standard output as a side effect. Dump files and preserved temporary files are renamed so as to contain the .gk additional extension during the second compilation, to avoid overwriting those generated by the first.

When this option is passed to the compiler driver, it causes the first compilation to be skipped, which makes it useful for little other than debugging the compiler proper.

  • -gtoggle — Turn off generation of debug info, if leaving out this option generates it, or turn it on at level 2 otherwise. The position of this argument in the command line does not matter; it takes effect after all other options are processed, and it does so only once, no matter how many times it is given. This is mainly intended to be used with -fcompare-debug.
  • -fvar-tracking-assignments-toggle — Toggle -fvar-tracking-assignments, in the same way that -gtoggle toggles -g.
  • -Q — Makes the compiler print out each function name as it is compiled, and print some statistics about each pass when it finishes.
  • -ftime-report — Makes the compiler print some statistics about the time consumed by each pass when it finishes.
  • -ftime-report-details — Record the time consumed by infrastructure parts separately for each pass.
  • -fira-verbose=n — Control the verbosity of the dump file for the integrated register allocator. The default value is 5. If the value n is greater or equal to 10, the dump output is sent to stderr using the same format as n minus 10.
  • -flto-report — Prints a report with internal details on the workings of the link-time optimizer. The contents of this report vary from version to version. It is meant to be useful to GCC developers when processing object files in LTO mode (via -flto).

Disabled by default.

  • -flto-report-wpa — Like -flto-report, but only print for the WPA phase of link-time optimization.
  • -fmem-report — Makes the compiler print some statistics about permanent memory allocation when it finishes.
  • -fmem-report-wpa — Makes the compiler print some statistics about permanent memory allocation for the WPA phase only.
  • -fpre-ipa-mem-report, -fpost-ipa-mem-report — Makes the compiler print some statistics about permanent memory allocation before or after interprocedural optimization.
  • -fprofile-report — Makes the compiler print some statistics about consistency of the (estimated) profile and effect of individual passes.
  • -fstack-usage — Makes the compiler output stack usage information for the program, on a per-function basis. The filename for the dump is made by appending .su to the auxname. auxname is generated from the name of the output file, if explicitly specified and it is not an executable, otherwise it is the basename of the source file. An entry is made up of three fields:
    • The name of the function.
    • A number of bytes.
    • One or more qualifiers: static, dynamic, bounded.

The qualifier static means that the function manipulates the stack statically: a fixed number of bytes are allocated for the frame on function entry and released on function exit; no stack adjustments are otherwise made in the function. The second field is this fixed number of bytes.

Okay so, the qualifier "dynamic" means the function messes with the stack dynamically: on top of the static allocation we literally just talked about, stack adjustments get made inside the body of the function — like, for example, to push/pop arguments around function calls. And if the qualifier "bounded" is also there, the amount of those adjustments is bounded at compile time, and the second field is an upper bound of the total amount of stack the function uses. If "bounded" is not there, the amount of those adjustments is not bounded at compile time, and the second field only represents the bounded part. Bestie, that's the whole tea. 🫖

  • -fstats — emit statistics about front-end processing at the end of the compilation. Ngl, this one's only supported by the C++ front end, and the info is generally only useful to the G++ development team. Iconic but niche. 💅
  • -fdbg-cnt-list — print the name and the counter upper bound for all debug counters.
  • *-fdbg-cnt=counter-value-list* — set the internal debug counter lower and upper bound. The counter-value-list is a comma-separated list of name:lower_bound1-upper_bound1 [:lower_bound2-upper_bound2...] tuples, which sets the name of the counter and the list of closed intervals. The lower_bound is optional and is zero-initialized if not set. For example, with -fdbg-cnt=dce:2-4:10-11,tail_call:10, dbg_cnt(dce) returns true only for the second, third, fourth, tenth and eleventh invocation. For dbg_cnt(tail_call) true is returned for the first 10 invocations. Math girlie behaviour fr fr. 🧮
  • *-print-file-name=library* — print the full absolute name of the library file library that would be used when linking — and don't do anything else. With this option, GCC doesn't compile or link anything; it just prints the file name. Just the name. That's it. That's the whole job. ✨
  • -print-multi-directory — print the directory name corresponding to the multilib selected by any other switches present in the command line. This directory is supposed to exist in GCC_EXEC_PREFIX.
  • -print-multi-lib — print the mapping from multilib directory names to compiler switches that enable them. The directory name is separated from the switches by ;, and each switch starts with an @ instead of the -, with no spaces between multiple switches. This is supposed to ease shell processing. Very demure, very shell-friendly. 🐚
  • -print-multi-os-directory — print the path to OS libraries for the selected multilib, relative to some lib subdirectory. If OS libraries are present in the lib subdirectory and no multilibs are used, this is usually just .; if OS libraries are present in libsuffix sibling directories this prints e.g. ../lib64, ../lib or ../lib32; or if OS libraries are present in lib/subdir subdirectories it prints e.g. amd64, sparcv9 or ev6.
  • -print-multiarch — print the path to OS libraries for the selected multiarch, relative to some lib subdirectory.
  • *-print-prog-name=program* — like -print-file-name, but it searches for a program such as cpp. 🕵️‍♀️
  • -print-libgcc-file-name — same as -print-file-name=libgcc.a.

This one is actually so useful when you use -nostdlib or -nodefaultlibs but you do want to link with libgcc.a. You can literally do:

gcc -nostdlib <files>... `gcc -print-libgcc-file-name`
  • -print-search-dirs — print the name of the configured installation directory and a list of program and library directories gcc searches — and don't do anything else. 💫

This is a lifesaver when gcc prints the error message installation problem, cannot exec cpp0: No such file or directory. To resolve this you either need to put cpp0 and the other compiler components where gcc expects to find them, or you can set the environment variable GCC_EXEC_PREFIX to the directory where you installed them. Don't forget the trailing / — genuinely, don't, it will not work. 😭

  • -print-sysroot — print the target sysroot directory that's used during compilation. This is the target sysroot specified either at configure time or using the --sysroot option, possibly with an extra suffix that depends on compilation options. If no target sysroot is specified, the option prints nothing. Silence. Iconic, honestly. 🤫
  • -print-sysroot-headers-suffix — print the suffix added to the target sysroot when searching for headers, or give an error if the compiler isn't configured with such a suffix — and don't do anything else.
  • -dumpmachine — print the compiler's target machine (for example, i686-pc-linux-gnu) — and don't do anything else.
  • -dumpversion — print the compiler version (for example, 3.0, 6.3.0 or 7) — and don't do anything else. This is the compiler version used in filesystem paths and specs. Depending on how the compiler has been configured, it can be just a single number (major version), two numbers separated by a dot (major and minor version), or three numbers separated by dots (major, minor and patchlevel version). She contains multitudes. 🌈
  • -dumpfullversion — print the full compiler version — and don't do anything else. The output is always three numbers separated by dots: major, minor and patchlevel version. No ambiguity, no games. 💯
  • -dumpspecs — print the compiler's built-in specs — and don't do anything else. (This is used when GCC itself is being built. Inception vibes, lowkey. 🌀)

🛠️ Machine-Dependent Options — the per-machine edition

So like, each target machine supported by GCC can have its own options — for example, to let you compile for a particular processor variant or ABI, or to control optimizations specific to that machine. By convention, the names of machine-specific options start with -m. Cute little naming scheme, we love consistency. 🎀

Some configurations of the compiler also support additional target-specific options, usually for compatibility with other compilers on the same platform. Friendly neighbours energy. 🫶

🌸 AArch64 Options

These options are defined for AArch64 implementations:

  • *-mabi=name* — generate code for the specified data model. Permissible values are ilp32 for the SysV-like data model where int, long int and pointers are 32 bits, and lp64 for the SysV-like data model where int is 32 bits but long int and pointers are 64 bits.

The default depends on the specific target configuration. Note that the LP64 and ILP32 ABIs are not link-compatible — you must compile your entire program with the same ABI, and link with a compatible set of libraries. No mixing, bestie, it will not slay. 💀

  • -mbig-endian — generate big-endian code. This is the default when GCC is configured for an aarch64_be-*-* target.
  • -mgeneral-regs-only — generate code which uses only the general-purpose registers. This prevents the compiler from using floating-point and Advanced SIMD registers, but it won't impose any restrictions on the assembler. Compiler says no, assembler says yes. 🙈
  • -mlittle-endian — generate little-endian code. This is the default when GCC is configured for an aarch64-*-* but not an aarch64_be-*-* target.
  • -mcmodel=tiny — generate code for the tiny code model. The program and its statically defined symbols must be within 1MB of each other. Programs can be statically or dynamically linked. Tiny but mighty. ✨
  • -mcmodel=small — generate code for the small code model. The program and its statically defined symbols must be within 4GB of each other. Programs can be statically or dynamically linked. This is the default code model. Main character default behaviour. 👑
  • -mcmodel=large — generate code for the large code model. This makes no assumptions about addresses and sizes of sections. Programs can be statically linked only. And heads up: the -mcmodel=large option is incompatible with -mabi=ilp32, -fpic and -fPIC. Do not try it. I'm serious. 🚫
  • -mstrict-align
  • -mno-strict-align — avoid or allow generating memory accesses that may not be aligned on a natural object boundary as described in the architecture specification.
  • -momit-leaf-frame-pointer
  • -mno-omit-leaf-frame-pointer — omit or keep the frame pointer in leaf functions. The former behavior is the default.
  • *-mstack-protector-guard=guard*
  • *-mstack-protector-guard-reg=reg*
  • *-mstack-protector-guard-offset=offset* — generate stack protection code using a canary at guard. Supported locations are global for a global canary or sysreg for a canary in an appropriate system register.

With the latter choice, the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which system register to use as the base register for reading the canary, and from what offset from that base register. There is no default register or offset — this is entirely for use within the Linux kernel. Kernel girlies, this one's for you. 🐧

  • -mtls-dialect=desc — use TLS descriptors as the thread-local storage mechanism for dynamic accesses of TLS variables. This is the default.
  • -mtls-dialect=traditional — use traditional TLS as the thread-local storage mechanism for dynamic accesses of TLS variables. Retro. Vintage. Respect the classics. 🎞️
  • *-mtls-size=size* — specify the bit size of immediate TLS offsets. Valid values are 12, 24, 32, 48. This option requires binutils 2.26 or newer — so check that before you come for her. 💅
  • -mfix-cortex-a53-835769
  • -mno-fix-cortex-a53-835769 — enable or disable the workaround for the ARM Cortex-A53 erratum number 835769. This involves inserting a NOP instruction between memory instructions and 64-bit integer multiply-accumulate instructions.
  • -mfix-cortex-a53-843419
  • -mno-fix-cortex-a53-843419 — enable or disable the workaround for the ARM Cortex-A53 erratum number 843419. This erratum workaround is made at link time, and this will only pass the corresponding flag to the linker. Middleman behaviour ngl. 🫡
  • -mlow-precision-recip-sqrt
  • -mno-low-precision-recip-sqrt — enable or disable the reciprocal square root approximation. This option only has an effect if -ffast-math or -funsafe-math-optimizations is used as well. Enabling this reduces the precision of reciprocal square root results to about 16 bits for single precision and to 32 bits for double precision. Fast, but at what cost 😭
  • -mlow-precision-sqrt
  • -mno-low-precision-sqrt — enable or disable the square root approximation. This option only has an effect if -ffast-math or -funsafe-math-optimizations is used as well. Enabling this reduces the precision of square root results to about 16 bits for single precision and to 32 bits for double precision. If enabled, it implies -mlow-precision-recip-sqrt. Package deal. 🎁
  • -mlow-precision-div
  • -mno-low-precision-div — enable or disable the division approximation. This option only has an effect if -ffast-math or -funsafe-math-optimizations is used as well. Enabling this reduces the precision of division results to about 16 bits for single precision and to 32 bits for double precision. Same deal, same rules, same little precision glow-down. 🦋
  • -mtrack-speculation, -mno-track-speculation — toggle whether GCC generates the extra code that tracks speculative execution through conditional branches 🕵️‍♀️ The tracking state can then be used by the compiler when expanding calls to __builtin_speculation_safe_copy, which is what lets it emit a more efficient code sequence. Slay, but it's extra instructions, so you decide bestie.
  • -moutline-atomics, -mno-outline-atomics — toggle calls out to out-of-line helpers that implement atomic operations 🧚 At runtime those helpers figure out whether the LSE instructions from ARMv8.1-A are available; if they're not, the helpers fall back to the load/store-exclusive instructions that exist in the base ARMv8.0 ISA. Best of both worlds, no cap.
    • Heads up: this option is only applicable when you're compiling for the base ARMv8.0 instruction set. If you're on a later revision — like -march=armv8.1-a or -march=armv8-a+lse — the ARMv8.1-Atomics instructions get used directly. Same story when you use -mcpu= and the selected cpu supports the lse feature.
    • This option is on by default ✅
  • -march=name — tells GCC the name of the target architecture, plus optionally one or more feature modifiers. The form is literally:
-march=arch{+[no]feature}*

The table below summarizes the permissible values for arch and the features they enable by default 👇

  • armv8-a — Architecture: Armv8-A — includes by default: +fp, +simd
  • armv8.1-a — Architecture: Armv8.1-A — includes by default: armv8-a, +crc, +lse, +rdma
  • armv8.2-a — Architecture: Armv8.2-A — includes by default: armv8.1-a
  • armv8.3-a — Architecture: Armv8.3-A — includes by default: armv8.2-a, +pauth
  • armv8.4-a — Architecture: Armv8.4-A — includes by default: armv8.3-a, +flagm, +fp16fml, +dotprod
  • armv8.5-a — Architecture: Armv8.5-A — includes by default: armv8.4-a, +sb, +ssbs, +predres
  • armv8.6-a — Architecture: Armv8.6-A — includes by default: armv8.5-a, +bf16, +i8mm
  • armv8.7-a — Architecture: Armv8.7-A — includes by default: armv8.6-a, +ls64
  • armv8.8-a — Architecture: Armv8.8-a — includes by default: armv8.7-a, +mops
  • armv9-a — Architecture: Armv9-A — includes by default: armv8.5-a, +sve, +sve2
  • armv8-r — Architecture: Armv8-R — includes by default: armv8-r

The value native is available on native AArch64 GNU/Linux, and it makes the compiler pick the architecture of the host system 💻 Fair warning though: this option has no effect if the compiler can't recognize the architecture of the host system.

The permissible values for feature are listed in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. If you specify conflicting feature modifiers, the right-most feature wins — last one standing, periodt.

GCC uses name to determine what kind of instructions it can emit when generating assembly code. And if -march is specified without either -mtune or -mcpu also being specified, the code gets tuned to perform well across a range of target processors implementing the target architecture 🌈

  • -mtune=name — names the target processor that GCC should tune the performance of the code for 🎯 Permissible values for this option are:
generic, cortex-a35, cortex-a53, cortex-a55, cortex-a57,
cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae,
cortex-a77, cortex-a65, cortex-a65ae, cortex-a34, cortex-a78,
cortex-a78ae, cortex-a78c, ares, exynos-m1, emag, falkor,
neoverse-512tvb, neoverse-e1, neoverse-n1, neoverse-n2, neoverse-v1,
qdf24xx, saphira, phecda, xgene1, vulcan, octeontx, octeontx81,
octeontx83, octeontx2, octeontx2t98, octeontx2t96 octeontx2t93,
octeontx2f95, octeontx2f95n, octeontx2f95mm, a64fx, thunderx,
thunderxt88, thunderxt88p1, thunderxt81, tsv110, thunderxt83,
thunderx2t99, thunderx3t110, zeus, cortex-a57.cortex-a53,
cortex-a72.cortex-a53, cortex-a73.cortex-a35, cortex-a73.cortex-a53,
cortex-a75.cortex-a55, cortex-a76.cortex-a55, cortex-r82, cortex-x1,
cortex-x2, cortex-a510, cortex-a710, ampere1, native

The values cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a73.cortex-a35, cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55 mean GCC should tune for a big.LITTLE system 👯‍♀️

The value neoverse-512tvb means GCC should tune for Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits per cycle. In other words, it tells GCC to tune for Neoverse cores that can execute 4 128-bit Advanced SIMD arithmetic instructions a cycle, and can execute an equivalent number of SVE arithmetic instructions per cycle (2 for 256-bit SVE, 4 for 128-bit SVE) 💫 That's more general than tuning for one specific core like Neoverse V1, but more specific than the default tuning described below.

Also, on native AArch64 GNU/Linux systems, the value native tunes performance to the host system. This option has no effect if the compiler can't recognize the processor of the host system 🙈

Where none of -mtune=, -mcpu= or -march= are specified, the code is tuned to perform well across a range of target processors.

Ngl bestie, this option cannot be suffixed by feature modifiers. Don't try it 💀
  • -mcpu=name — names the target processor, optionally suffixed by one or more feature modifiers ✨ The form is:
-mcpu=cpu{+[no]feature}*

where the permissible values for cpu are the same ones available for -mtune. The permissible values for feature are documented in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. If conflicting feature modifiers are specified, the right-most feature is used, same as always 👑

GCC uses name to determine what kind of instructions it can emit when generating assembly code (as if by -march) and to determine the target processor to tune for performance (as if by -mtune). Where this option is used together with -march or -mtune, those options take precedence over the appropriate part of this option — they're the main characters here.

-mcpu=neoverse-512tvb is special: it doesn't refer to a specific core, it refers to all Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits a cycle 🌀 Unless overridden by -march, -mcpu=neoverse-512tvb generates code that can run on a Neoverse V1 core, since Neoverse V1 is the first Neoverse core with these properties. And unless overridden by -mtune, -mcpu=neoverse-512tvb tunes code in the same way as -mtune=neoverse-512tvb.

  • -moverride=string — overrides tuning decisions made by the back-end in response to a -mtune= switch 🎛️ The syntax, semantics, and accepted values for string are not guaranteed to be consistent across releases.
This option is only intended to be useful when developing GCC. It's a compiler-dev thing, not a you thing 🫶
  • -mverbose-cost-dump — enables verbose cost model dumping in the debug dump files 📊 This option is provided for use in debugging the compiler.
  • -mpc-relative-literal-loads, -mno-pc-relative-literal-loads — toggle PC-relative literal loads 🔥 With this option, literal pools are accessed using a single instruction and emitted after each function. That limits the maximum size of functions to 1MB. It's enabled by default for -mcmodel=tiny.
  • -msign-return-address=scope — selects the function scope on which return address signing gets applied ✍️ Permissible values:
    • none — disables return address signing
    • non-leaf — enables pointer signing for functions which are not leaf functions
    • all — enables pointer signing for all functions

The default value is none. Heads up: this option has been deprecated by -mbranch-protection 💀

  • -mbranch-protection=none|standard|pac-ret[+leaf+b-key]|bti — selects the branch protection features to use 🛡️
    • none is the default and turns off all types of branch protection.
    • standard turns on all types of branch protection features. If a feature has additional tuning options, standard sets it to its standard level.
    • pac-ret[+leaf] turns on return address signing to its standard level: signing functions that save the return address to memory (non-leaf functions will practically always do this) using the a-key. The optional argument leaf can be used to extend the signing to include leaf functions. The optional argument b-key can be used to sign the functions with the B-key instead of the A-key.
    • bti turns on branch target identification mechanism.
  • -mharden-sls=opts — enables compiler hardening against straight line speculation (SLS) ⚔️ opts is a comma-separated list of the following options:
retbr
blr

In addition, -mharden-sls=all enables all SLS hardening, while -mharden-sls=none disables all SLS hardening. Easy.

  • -msve-vector-bits=bits — specifies the number of bits in an SVE vector register 🧮 This option only has an effect when SVE is enabled.

GCC supports two forms of SVE code generation: "vector-length agnostic" output that works with any size of vector register, and "vector-length specific" output that lets GCC make assumptions about the vector length when it's useful for optimization reasons. The possible values of bits are: scalable, 128, 256, 512, 1024 and 2048. Specifying scalable selects vector-length agnostic output. At present -msve-vector-bits=128 also generates vector-length agnostic output for big-endian targets. All other values generate vector-length specific code 🎀

The behavior of these values may change in future releases, and no value except scalable should be relied on for producing code that is portable across different hardware SVE vector lengths. Save yourself the pain, bestie 😭

The default is -msve-vector-bits=scalable, which produces vector-length agnostic code.


🌸 -march and -mcpu Feature Modifiers 🌸

Feature modifiers used with -march and -mcpu can be any of the following, and their inverses nofeature 💅

  • crc — Enable CRC extension. This is on by default for -march=armv8.1-a.
  • crypto — Enable Crypto extension. This also enables Advanced SIMD and floating-point instructions.
  • fp — Enable floating-point instructions. This is on by default for all possible values for options -march and -mcpu.
  • simd — Enable Advanced SIMD instructions. This also enables floating-point instructions. This is on by default for all possible values for options -march and -mcpu.
  • sve — Enable Scalable Vector Extension instructions. This also enables Advanced SIMD and floating-point instructions.
  • lse — Enable Large System Extension instructions. This is on by default for -march=armv8.1-a.
  • rdma — Enable Round Double Multiply Accumulate instructions. This is on by default for -march=armv8.1-a.
  • fp16 — Enable FP16 extension. This also enables floating-point instructions.
  • fp16fml — turns on the FP16 fmla extension ✨ and it also flips on the FP16 extensions plus the floating-point instructions. It's on by default for -march=armv8.4-a. ⚠️ Using it with any architecture before Armv8.2-A is not supported, periodt.
  • rcpc — turns on the RcPc extension. Fun fact: this one doesn't change code generation from GCC at all, it just gets passed along to the assembler so your inline asm statements can use RcPc instructions 💅
  • dotprod — turns on the Dot Product extension, and that also brings Advanced SIMD instructions along for the ride 🫶
  • aes — turns on the Armv8-a aes and pmull crypto extension. Also enables Advanced SIMD instructions. 👑
  • sha2 — turns on the Armv8-a sha2 crypto extension. Also enables Advanced SIMD instructions.
  • sha3 — turns on the sha512 and sha3 crypto extension. Also enables Advanced SIMD instructions. ⚠️ Not supported with architectures prior to Armv8.2-A, no cap.
  • sm4 — turns on the sm3 and sm4 crypto extension. Also enables Advanced SIMD instructions. ⚠️ Again: architectures prior to Armv8.2-A? Not supported.
  • profile — turns on the Statistical Profiling extension. Heads up though: this one is only for enabling the extension at the assembler level and does not affect code generation. 🙈
  • rng — turns on the Armv8.5-a Random Number instructions. Same deal — assembler level only, does not affect code generation.
  • memtag — turns on the Armv8.5-a Memory Tagging Extensions. ⚠️ Using this with architectures prior to Armv8.5-A is not supported.
  • sb — turns on the Armv8-a Speculation Barrier instruction. Assembler level only, does not affect code generation. It's enabled by default for -march=armv8.5-a 💖
  • ssbs — turns on the Armv8-a Speculative Store Bypass Safe instruction. Assembler level only, does not affect code generation. Enabled by default for -march=armv8.5-a.
  • predres — turns on the Armv8-a Execution and Data Prediction Restriction instructions. Assembler level only, does not affect code generation. Enabled by default for -march=armv8.5-a. ✨
  • sve2 — turns on the Armv8-a Scalable Vector Extension 2, and that also enables SVE instructions.
  • sve2-bitperm — turns on SVE2 bitperm instructions, which also enables SVE2 instructions.
  • sve2-sm4 — turns on SVE2 sm4 instructions, which also enables SVE2 instructions.
  • sve2-aes — turns on SVE2 aes instructions, which also enables SVE2 instructions.
  • sve2-sha3 — turns on SVE2 sha3 instructions, which also enables SVE2 instructions. 🌸
  • tme — turns on the Transactional Memory Extension.
  • i8mm — turns on 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. Enabled by default for -march=armv8.6-a. ⚠️ Architectures prior to Armv8.2-A? Not supported.
  • f32mm — turns on 32-bit Floating point Matrix Multiply instructions. Also enables SVE instructions. ⚠️ Not supported with architectures prior to Armv8.2-A.
  • f64mm — turns on 64-bit Floating point Matrix Multiply instructions. Also enables SVE instructions. ⚠️ Not supported with architectures prior to Armv8.2-A.
  • bf16 — turns on brain half-precision floating-point instructions 🧠 (that's literally what it's called, iykyk). Also enables Advanced SIMD and floating-point instructions. Enabled by default for -march=armv8.6-a. ⚠️ Not supported with architectures prior to Armv8.2-A.
  • ls64 — turns on the 64-byte atomic load and store instructions for accelerators. Enabled by default for -march=armv8.7-a.
  • mops — turns on the instructions that accelerate memory operations like memcpy, memmove, and memset 🔥 Enabled by default for -march=armv8.8-a
  • flagm — turns on the Flag Manipulation instructions Extension.
  • pauth — turns on the Pointer Authentication Extension. 🎀
Okay so the dependency tea ☕: feature crypto implies aes, sha2, and simd, which implies fp. And conversely, nofp implies nosimd, which implies nocrypto, noaes and nosha2. It all cascades, bestie.

🌈 Adapteva Epiphany Options 🌈

These -m options are defined for Adapteva Epiphany:

  • -mhalf-reg-file — don't allocate any register in the range r32…r63. That's what lets your code run on hardware variants that just don't have those registers 💅
  • -mprefer-short-insn-regs — preferentially allocate registers that allow short instruction generation. Side effect: this can bump up the instruction count, so it may either reduce or increase overall code size. It's giving chaos, honestly.
  • -mbranch-cost=num — set the cost of branches to roughly num "simple" instructions. Ngl this cost is only a heuristic and is not guaranteed to produce consistent results across releases 🙈
  • -mcmove — enable the generation of conditional moves ✨
  • -mnops=num — emit num NOPs before every other generated instruction.
  • -mno-soft-cmpsf — for single-precision floating-point comparisons, emit an fsub instruction and test the flags. Faster than a software comparison, yes, but it can get incorrect results in the presence of NaNs, or when two different small numbers are compared such that their difference is calculated as zero 💀 The default is -msoft-cmpsf, which uses slower but IEEE-compliant software comparisons.
  • -mstack-offset=num — set the offset between the top of the stack and the stack pointer. So like, a value of 8 means the eight bytes in the range sp+0...sp+7 can be used by leaf functions without stack allocation. Values other than 8 or 16 are untested and unlikely to work ⚠️ Also note: this option changes the ABI. Compiling a program with a different stack offset than the libraries were compiled with generally does not work. It's useful if you wanna evaluate whether a different stack offset would give you better code, but to actually use a different stack offset to build working programs, it's recommended to configure the toolchain with the appropriate --with-stack-offset=num option 🫶
  • -mno-round-nearest — make the scheduler assume the rounding mode has been set to truncating. The default is -mround-nearest.
  • -mlong-calls — if not otherwise specified by an attribute, assume all calls might be beyond the offset range of the b / bl instructions, and therefore load the function address into a register before performing a (otherwise direct) call. This is the default. 👑
  • -mshort-calls — if not otherwise specified by an attribute, assume all direct calls are in the range of the b / bl instructions, so use these instructions for direct calls. The default is -mlong-calls.
  • -msmall16 — assume addresses can be loaded as 16-bit unsigned values. This does not apply to function addresses, for which -mlong-calls semantics are in effect.
  • -mfp-mode=mode — set the prevailing mode of the floating-point unit. This determines the floating-point mode that's provided and expected at function call and return time. Matching this mode to the mode you predominantly need at function start can make your programs smaller and faster by avoiding unnecessary mode switches ✨

mode can be set to one of the following values:

  • caller — any mode at function entry is valid, and it's retained or restored when the function returns, and when it calls other functions. Super useful for compiling libraries or other compilation units you might want to drop into different programs with different prevailing FPU modes — the convenience of using a single object file outweighs the size and speed overhead of any extra mode switching that might be needed, compared with what a more specific choice of prevailing FPU mode would need.
  • truncate — the mode used for floating-point calculations with truncating (i.e. round towards zero) rounding mode. That includes conversion from floating point to integer.
  • round-nearest — the mode used for floating-point calculations with round-to-nearest-or-even rounding mode.
  • int — the mode used to perform integer calculations in the FPU, e.g. integer multiply, or integer multiply-and-accumulate.

The default is -mfp-mode=caller 💖

  • -mno-split-lohi
  • -mno-postinc
  • -mno-postmodify — code generation tweaks that disable, respectively, splitting of 32-bit loads, generation of post-increment addresses, and generation of post-modify addresses. The defaults are msplit-lohi, -mpost-inc, and -mpost-modify. 🎀
  • -mnovect-double — change the preferred SIMD mode to SImode. The default is -mvect-double, which uses DImode as preferred SIMD mode.
  • -max-vect-align=num — the maximum alignment for SIMD vector mode types. num may be 4 or 8. The default is 8. ⚠️ Heads up: this is an ABI change, even though many library function interfaces are unaffected if they don't use SIMD vector modes in places that affect size and/or alignment of relevant types.
  • -msplit-vecmove-early — split vector moves into single word moves before reload. In theory this can give better register allocation, but so far the reverse seems to be generally the case 😭
  • -m1reg-reg — specify a register to hold the constant -1, which makes loading small negative constants and certain bitmasks faster. Allowable values for reg are r43 and r63, which specify use of that register as a fixed register, and none, which means that no register is used for this purpose. The default is -m1reg-none. 💅

🦋 AMD GCN Options 🦋

These options are defined specifically for the AMD GCN port:

  • -march=gpu
  • -mtune=gpu — set architecture type or tuning for gpu. Supported values for gpu are:
    • fiji — compile for GCN3 Fiji devices (gfx803).
    • gfx900 — compile for GCN5 Vega 10 devices (gfx900).
    • gfx906 — compile for GCN5 Vega 20 devices (gfx906). ⭐
  • -msram-ecc=on, -msram-ecc=off, -msram-ecc=any — builds your binaries for devices where the SRAM-ECC feature is turned on, turned off, or either way. Bestie, on some devices this thing can be flipped per-process, and the compiled code has to match whatever mode the device is in. Default is any, for the devices that support it. 🫶
  • -mstack-size=bytes — tells the compiler how many bytes of stack space to ask for per GPU thread (aka per wave-front). Heads up though: there can be a LOT of threads and only so much memory to go around 😭. Also, the size of that stack allocation can lowkey affect run-time performance. Default is 32KB when you're using OpenACC or OpenMP, and 1MB otherwise.
  • -mxnack — builds binaries for devices with the XNACK feature enabled. Some devices always need XNACK, and some let the user configure it — either way the compiled code must match the device mode. Default is -mno-xnack. RN this option is just a placeholder for support that isn't implemented yet, so don't get too excited 💀.

✨ ARC Options ✨

The following options control the architecture variant for which code is being compiled, iykyk:

  • -mbarrel-shifter — generates the instructions that a barrel shifter supports. This is the default unless -mcpu=ARC601 or -mcpu=ARCEM is in effect.
  • -mjli-always — forces a function call to go through the jli_s instruction. Only valid for ARCv2 architecture, no cap.
  • -mcpu=cpu — sets the architecture type, register usage, and instruction scheduling parameters for cpu. There are also shortcut alias options for backward compatibility and convenience (they really said "here, take the easy route" 💅). Supported values for cpu are:
    • arc600 — compile for ARC600. Aliases: -mA6, -mARC600.
    • arc601 — compile for ARC601. Alias: -mARC601.
    • arc700 — compile for ARC700. Aliases: -mA7, -mARC700. This is the default when configured with --with-cpu=arc700.
    • arcem — compile for ARC EM.
    • archs — compile for ARC HS.
    • em — compile for ARC EM CPU with no hardware extensions.
    • em4 — compile for ARC EM4 CPU.
    • em4_dmips — compile for ARC EM4 DMIPS CPU.
    • em4_fpus — compile for ARC EM4 DMIPS CPU with the single-precision floating-point extension.
    • em4_fpuda — compile for ARC EM4 DMIPS CPU with single-precision floating-point and double assist instructions.
    • hs — compile for ARC HS CPU with no hardware extensions except the atomic instructions.
    • hs34 — compile for ARC HS34 CPU.
    • hs38 — compile for ARC HS38 CPU.
    • hs38_linux — compile for ARC HS38 CPU with all hardware extensions on.
    • arc600_norm — compile for ARC 600 CPU with "norm" instructions enabled.
    • arc600_mul32x16 — compile for ARC 600 CPU with "norm" and 32x16-bit multiply instructions enabled.
    • arc600_mul64 — compile for ARC 600 CPU with "norm" and "mul64"-family instructions enabled.
    • arc601_norm — compile for ARC 601 CPU with "norm" instructions enabled.
    • arc601_mul32x16 — compile for ARC 601 CPU with "norm" and 32x16-bit multiply instructions enabled.
    • arc601_mul64 — compile for ARC 601 CPU with "norm" and "mul64"-family instructions enabled.
    • nps400 — compile for ARC 700 on NPS400 chip.
    • em_mini — compile for ARC EM minimalist configuration featuring reduced register set.
  • -mdpfp, -mdpfp-compact — generate double-precision FPX instructions, tuned for the compact implementation.
  • -mdpfp-fast — generate double-precision FPX instructions, tuned for the fast implementation.
  • -mno-dpfp-lrsr — disables the "lr" and "sr" instructions from using FPX extension aux registers.
  • -mea — generate extended arithmetic instructions. Currently only "divaw", "adds", "subs", and "sat16" are supported, and it's only valid for -mcpu=ARC700.
  • -mno-mpy — don't generate "mpy"-family instructions for ARC700. Heads up: this option is deprecated 🙈.
  • -mmul32x16 — generate 32x16-bit multiply and multiply-accumulate instructions.
  • -mmul64 — generate "mul64" and "mulu64" instructions. Only valid for -mcpu=ARC600.
  • -mnorm — generate "norm" instructions. This is the default if -mcpu=ARC700 is in effect.
  • -mspfp, -mspfp-compact — generate single-precision FPX instructions, tuned for the compact implementation.
  • -mspfp-fast — generate single-precision FPX instructions, tuned for the fast implementation.
  • -msimd — enables generation of ARC SIMD instructions via target-specific builtins. Only valid for -mcpu=ARC700.
  • -msoft-float — ngl this option is ignored; it's only here for compatibility purposes. Software floating-point code is emitted by default anyway, and that default can be overridden by the FPX options: -mspfp, -mspfp-compact, or -mspfp-fast for single precision, and -mdpfp, -mdpfp-compact, or -mdpfp-fast for double precision.
  • -mswap — generate "swap" instructions.
  • -matomic — enables use of the locked load/store conditional extension to implement atomic memory built-in functions. Not available for ARC 6xx or ARC EM cores, sorry bestie.
  • -mdiv-rem — enable "div" and "rem" instructions for ARCv2 cores.
  • -mcode-density — enable code density instructions for ARC EM. This one's on by default for ARC HS 💖.
  • -mll64 — enable double load/store operations for ARC HS cores.
  • -mtp-regno=regno — specify the thread pointer register number.
  • -mmpy-option=multo — compile ARCv2 code with a multiplier design option. You can pass multo as either a string or a numeric value, and wlh1 is the default. The recognized values are:
    • 0, none — no multiplier available.
    • 1, w — 16x16 multiplier, fully pipelined. Enables the following instructions: mpyw and mpyuw.
    • 2, wlh1 — 32x32 multiplier, fully pipelined (1 stage). Additionally enables: mpy, mpyu, mpym, mpymu, and mpy_s.
    • 3, wlh2 — 32x32 multiplier, fully pipelined (2 stages). Additionally enables: mpy, mpyu, mpym, mpymu, and mpy_s.
    • 4, wlh3 — two 16x16 multipliers, blocking, sequential. Additionally enables: mpy, mpyu, mpym, mpymu, and mpy_s.
    • 5, wlh4 — one 16x16 multiplier, blocking, sequential. Additionally enables: mpy, mpyu, mpym, mpymu, and mpy_s.
    • 6, wlh5 — one 32x4 multiplier, blocking, sequential. Additionally enables: mpy, mpyu, mpym, mpymu, and mpy_s.
    • 7, plus_dmpy — ARC HS SIMD support.
    • 8, plus_macd — ARC HS SIMD support.
    • 9, plus_qmacw — ARC HS SIMD support.

This option is only available for ARCv2 cores, periodt.

  • -mfpu=fpu — enables support for specific floating-point hardware extensions for ARCv2 cores. Supported values for fpu are:
    • fpus — enables support for single-precision floating-point hardware extensions.
    • fpud — enables support for double-precision floating-point hardware extensions. The single-precision floating-point extension is also enabled. Not available for ARC EM.
    • fpuda — enables support for double-precision floating-point hardware extensions using double-precision assist instructions. The single-precision floating-point extension is also enabled. Only available for ARC EM.
    • fpuda_div — enables support for double-precision floating-point hardware extensions using double-precision assist instructions. The single-precision floating-point, square-root, and divide extensions are also enabled. Only available for ARC EM.
    • fpuda_fma — enables support for double-precision floating-point hardware extensions using double-precision assist instructions. The single-precision floating-point and fused multiply and add hardware extensions are also enabled. Only available for ARC EM.
    • fpuda_all — enables support for double-precision floating-point hardware extensions using double-precision assist instructions. All single-precision floating-point hardware extensions are also enabled. Only available for ARC EM.
    • fpus_div — enables support for single-precision floating-point, square-root and divide hardware extensions.
    • fpud_div — enables support for double-precision floating-point, square-root and divide hardware extensions. This option includes option fpus_div. Not available for ARC EM.
    • fpus_fma — enables support for single-precision floating-point and fused multiply and add hardware extensions.
    • fpud_fma — enables support for double-precision floating-point and fused multiply and add hardware extensions. This option includes option fpus_fma. Not available for ARC EM.
    • fpus_all — enables support for all single-precision floating-point hardware extensions.
    • fpud_all — enables support for all single- and double-precision floating-point hardware extensions. Not available for ARC EM.
  • -mirq-ctrl-saved=register-range, blink, lp_count — specifies the general-purpose registers that the processor automatically saves/restores on interrupt entry and exit. register-range is given as two registers separated by a dash, and the range always starts with r0 — the upper limit is the fp register. blink and lp_count are optional. Only valid for ARC EM and ARC HS cores 🦋.
  • -mrgf-banked-regs=*number* — tells the compiler how many registers get replicated into the second register bank when a fast interrupt hits 🏃‍♀️💨. Fast interrupts are the ones with the highest priority level, P0 — they only bother saving PC and STATUS32 to dodge memory transactions during the interrupt entry/exit sequences (efficient queen behavior 👑). Reach for this option when you're using fast interrupts on an ARC V2 family processor. Permitted values? 4, 8, 16, and 32 — pick one, bestie ✨
  • -mlpc-width=*width* — sets the width of the lp_count register 🎯. Valid values for width are 8, 16, 20, 24, 28 and 32 bits. Default width is locked to 32 bits. If your width is less than 32, the compiler won't try to transform loops in your program to use the zero-delay loop mechanism unless it knows the lp_count register can hold the required loop-counter value (it's not out here guessing, iykyk 🙈). Depending on the width you specify, the compiler and run-time library might still use the loop mechanism for various needs. This option defines the macro __ARC_LPC_WIDTH__ with the value of width 💖
  • -mrf16 — instructs the compiler to generate code for a 16-entry register file 🗂️. This option defines the __ARC_RF16__ preprocessor macro ✨
  • -mbranch-index — enables the use of bi or bih instructions to implement jump tables 🔥

The following options get passed straight through to the assembler, and they also define preprocessor macro symbols — dual-purpose icons 💅

  • -mdsp-packa — passed down to the assembler to enable the DSP Pack A extensions. Also sets the preprocessor symbol __Xdsp_packa. This option is deprecated ⚠️
  • -mdvbf — passed down to the assembler to enable the dual Viterbi butterfly extension 🦋. Also sets the preprocessor symbol __Xdvbf. This option is deprecated ⚠️
  • -mlock — passed down to the assembler to enable the locked load/store conditional extension 🔒. Also sets the preprocessor symbol __Xlock
  • -mmac-d16 — passed down to the assembler. Also sets the preprocessor symbol __Xxmac_d16. This option is deprecated ⚠️
  • -mmac-24 — passed down to the assembler. Also sets the preprocessor symbol __Xxmac_24. This option is deprecated ⚠️
  • -mrtsc — passed down to the assembler to enable the 64-bit time-stamp counter extension instruction ⏱️. Also sets the preprocessor symbol __Xrtsc. This option is deprecated ⚠️
  • -mswape — passed down to the assembler to enable the swap byte ordering extension instruction 🔄. Also sets the preprocessor symbol __Xswape
  • -mtelephony — passed down to the assembler to enable dual- and single-operand instructions for telephony 📞. Also sets the preprocessor symbol __Xtelephony. This option is deprecated ⚠️
  • -mxy — passed down to the assembler to enable the XY memory extension 🧠. Also sets the preprocessor symbol __Xxy

The next crew controls how the assembly code gets annotated 📝:

  • -misize — annotate assembler instructions with estimated addresses 📍
  • -mannotate-align — spills the tea on what alignment considerations led to the decision to make an instruction short or long 📏

The following ones are passed through to the linker 🔗:

  • -marclinux — passed through to the linker, to specify use of the arclinux emulation. This option is enabled by default in tool chains built for arc-linux-uclibc and arceb-linux-uclibc targets when profiling is not requested 🎀
  • -marclinux_prof — passed through to the linker, to specify use of the arclinux_prof emulation. This option is enabled by default in tool chains built for arc-linux-uclibc and arceb-linux-uclibc targets when profiling is requested 📊

Okay now these next ones control the semantics of the generated code — the actual personality of your output, fr fr 💜:

  • -mlong-calls — generates calls as register indirect calls, which gives you access to the full 32-bit address range 🌈
  • -mmedium-calls — don't use less than a 25-bit addressing range for calls — that's the offset you get from an unconditional branch-and-link instruction. Conditional execution of function calls gets suppressed so the 25-bit range can be used instead of the 21-bit range that comes with conditional branch-and-link. This is the default for tool chains built for arc-linux-uclibc and arceb-linux-uclibc targets 💫
  • -G *num* — puts definitions of externally-visible data in a small data section if that data is no bigger than num bytes. Default value of num is 4 for any ARC configuration, or 8 when we have double load/store operations 🍓
  • -mno-sdata — nope, don't generate sdata references 🙅‍♀️. This is the default for tool chains built for arc-linux-uclibc and arceb-linux-uclibc targets
  • -mvolatile-cache — uses ordinarily cached memory accesses for volatile references. This is the default 💖
  • -mno-volatile-cache — enables cache bypass for volatile references 🚀

And these next ones fine-tune code generation — the little detail-oriented gremlins 🔧🧚:

  • -malign-call — literally does nothing. Preserved for backward compatibility 💀
  • -mauto-modify-reg — enables the use of pre/post modify with register displacement 🔁
  • -mbbit-peephole — enables bbit peephole2 🫣
  • -mno-brcc — disables a target-specific pass in arc_reorg that generates compare-and-branch (brcc) instructions. Heads up though — it has no effect on generation of these instructions when they're driven by the combiner pass ⚠️
  • -mcase-vector-pcrel — uses PC-relative switch case tables so case tables can be shortened ✂️. This is the default for -Os
  • -mcompact-casesi — enables the compact casesi pattern. This is the default for -Os, and it's only available for ARCv1 cores. This option is deprecated ⚠️
  • -mno-cond-exec — disables the ARCompact-specific pass that generates conditional execution instructions 🚫

Okay so real talk about this one 😭 — due to delay slot scheduling and the whole chaotic interaction between operand numbers, literal sizes, instruction lengths, and the support for conditional execution, the target-independent pass that generates conditional execution is often lacking. So the ARC port keeps a special pass around that tries to find more conditional execution generation opportunities after register allocation, branch shortening, and delay slot scheduling have all been done. This pass generally — but not always — improves performance and code size, at the cost of extra compilation time. Which is exactly why there's an option to switch it off, bestie 💅. And if you're having a problem with call instructions exceeding their allowable offset range because they got conditionalized, you should consider using -mmedium-calls instead 👑

  • -mearly-cbranchsi — enables pre-reload use of the cbranchsi pattern 🌱
  • -mexpand-adddi — expands adddi3 and subdi3 at RTL generation time into add.f, adc etc. This option is deprecated ⚠️
  • -mindexed-loads — enables the use of indexed loads. Ngl this can be problematic 😬 — some optimizers then assume that indexed stores exist, which is not the case 🙈
  • -mlra — enables Local Register Allocation. This is still experimental for ARC, so by default the compiler uses standard reload (i.e. -mno-lra) 🧪
  • -mlra-priority-none — doesn't indicate any priority for target registers 🙅‍♀️
  • -mlra-priority-compact — indicates target register priority for r0..r3 / r12..r15 🥇
  • -mlra-priority-noncompact — reduces target register priority for r0..r3 / r12..r15 📉
  • -mmillicode — when optimizing for size (using -Os), prologues and epilogues that have to save or restore a large number of registers often get shortened by using a call to a special function in libgcc — this is what's called a millicode call ✨. Since these calls can pose performance issues, and/or cause linking issues when linking in a nonstandard way, this option exists so you can turn millicode call generation on or off 🎛️
  • -mcode-density-frame — lets the compiler emit enter and leave instructions 🚪. These are only valid for CPUs with the code-density feature
  • -mmixed-code — does nothing. Preserved for backward compatibility 💀
  • -mq-class — this option is deprecated (yes, that typo is in the original, we respect the lore 🙏). Enables q instruction alternatives. This is the default for -Os
  • -mRcq — enables Rcq constraint handling. Most short code generation depends on this. This is the default 💖
  • -mRcw — enables Rcw constraint handling. Most ccfsm condexec mostly depends on this. This is the default 💖
  • -msize-level=*level* — fine-tunes size optimization with regards to instruction lengths and alignment 📐. The recognized values for level are:
    • 0 — no size optimization. This level is deprecated and treated like 1 ⚠️
    • 1 — short instructions are used opportunistically ✨
    • 2 — in addition, alignment of loops and of code after barriers are dropped 🔻
    • 3 — in addition, optional data alignment is dropped, and the option Os is enabled 🔥

This defaults to 3 when -Os is in effect. Otherwise, if this isn't set, the behavior is equivalent to level 1 🎀

  • -mtune=*cpu* — sets instruction scheduling parameters for cpu, overriding anything implied by -mcpu= 🎚️

Supported values for cpu are:

  • ARC600 — tune for ARC600 CPU.
  • ARC601 — tune for ARC601 CPU.
  • ARC700 — tune for ARC700 CPU with standard multiplier block.
  • ARC700-xmac — tune for ARC700 CPU with XMAC block.
  • ARC725D — tune for ARC725D CPU.
  • ARC750D — tune for ARC750D CPU.
  • -mmultcost=*num* — the cost to assume for a multiply instruction, with 4 being equal to a normal instruction 🧮
  • -munalign-prob-threshold=*probability* — does nothing. Preserved for backward compatibility 💀

The following options are kept around for backward compatibility, but they're now deprecated and will be removed in a future release 🫶 — so like, use them at your own risk, bestie:

  • -margonaut — obsolete FPX 🦕
  • -mbig-endian, -EB — compile code for big-endian targets. Use of these options is now deprecated ⚠️. Big-endian code is supported by configuring GCC to build arceb-elf32 and arceb-linux-uclibc targets, for which big endian is the default 🐘
  • -mlittle-endian, -EL — compile code for little-endian targets. Use of these options is now deprecated ⚠️. Little-endian code is supported by configuring GCC to build arc-elf32 and arc-linux-uclibc targets, for which little endian is the default 🐭
  • -mbarrel_shifter — replaced by -mbarrel-shifter 🔄
  • -mdpfp_compact — replaced by -mdpfp-compact 🔄
  • -mdpfp_fast — replaced by -mdpfp-fast 🔄
  • -mdsp_packa — nope, this one's been retired ✨ use -mdsp-packa instead, okay?
  • -mEA — also retired 💀 the new name is -mea.
  • -mmac_24 — replaced by -mmac-24, slay.
  • -mmac_d16 — replaced by -mmac-d16, mwah 💅
  • -mspfp_compact — replaced by -mspfp-compact, periodt.
  • -mspfp_fast — replaced by -mspfp-fast, iconic.
  • -mtune=cpu — the values arc600, arc601, arc700 and arc700-xmac for cpu got a glow-up and are now ARC600, ARC601, ARC700 and ARC700-xmac respectively 🎀
  • -multcost=num — replaced by -mmultcost, bestie.

🦾 ARM Options 🦾

okay so these -m options are the ones defined for the ARM port, and honestly? it's giving a whole personality 💜

  • -mabi=name — generate code for the ABI you name. the permissible values are: apcs-gnu, atpcs, aapcs, aapcs-linux and iwmmxt. pick your fighter 🌈
  • -mapcs-frame — generate a stack frame that's compliant with the ARM Procedure Call Standard for all functions, even when it's not strictly necessary for the code to actually execute correctly. lowkey extra but valid 💅 heads up: if you also specify -fomit-frame-pointer with this option, stack frames just won't be generated for leaf functions. the default is -mno-apcs-frame. oh and — this option is deprecated 🫠
  • -mapcs — this is a synonym for -mapcs-frame, and yes, it's deprecated too 😭
  • -mthumb-interwork — generate code that supports calling between the ARM and Thumb instruction sets. without this option, on pre-v5 architectures, you literally cannot reliably use the two instruction sets inside one program. the default is -mno-thumb-interwork, because specifying -mthumb-interwork makes slightly larger code. and in AAPCS configurations this option is meaningless — it's giving nothing, no cap 🙈
  • -mno-sched-prolog — prevent the reordering of instructions in the function prologue, or the merging of those instructions with the instructions in the function's body. this means all functions start with a recognizable set of instructions (or actually one of a choice from a small set of different function prologues), and that info can be used to locate the start of functions inside an executable piece of code 🔍 the default is -msched-prolog.
  • -mfloat-abi=name — specifies which floating-point ABI to use. permissible values are: soft, softfp and hard 🧚

specifying soft causes GCC to generate output containing library calls for floating-point operations. softfp allows the generation of code using hardware floating-point instructions, but still uses the soft-float calling conventions. hard allows generation of floating-point instructions and uses FPU-specific calling conventions. fr fr ✨

the default depends on the specific target configuration. note that the hard-float and soft-float ABIs are not link-compatible — you must compile your entire program with the same ABI, and link with a compatible set of libraries. no mix-and-matching, bestie, that's a whole disaster 😭

  • -mgeneral-regs-only — generate code which uses only the general-purpose registers. this prevents the compiler from using floating-point and Advanced SIMD registers, but will not impose any restrictions on the assembler 👑
  • -mlittle-endian — generate code for a processor running in little-endian mode. this is the default for all standard configurations, so it's basically the main character 🎀
  • -mbig-endian — generate code for a processor running in big-endian mode; the default is to compile code for a little-endian processor (so, not this one 💀).
  • -mbe8
  • -mbe32 — when linking a big-endian image, select between BE8 and BE32 formats. the option has no effect for little-endian images and is ignored. the default is dependent on the selected target architecture: for ARMv6 and later architectures the default is BE8, for older architectures the default is BE32. oh and — BE32 format has been deprecated by ARM 🫠
  • -march=name[+extension...] — this specifies the name of the target ARM architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. this option can be used in conjunction with, or instead of, the -mcpu= option 👯‍♀️

permissible names are: armv4t, armv5t, armv5te, armv6, armv6j, armv6k, armv6kz, armv6t2, armv6z, armv6zk, armv7, armv7-a, armv7ve, armv8-a, armv8.1-a, armv8.2-a, armv8.3-a, armv8.4-a, armv8.5-a, armv8.6-a, armv9-a, armv7-r, armv8-r, armv6-m, armv6s-m, armv7-m, armv7e-m, armv8-m.base, armv8-m.main, armv8.1-m.main, armv9-a, iwmmxt and iwmmxt2. (yes armv9-a is in there twice — that's the original, we don't touch it 💅)

additionally, the following architectures, which lack support for the Thumb execution state, are recognized but support is deprecated: armv4.

many of the architectures support extensions, and you add them by appending +extension to the architecture name 🌸 extension options are processed in order and capabilities accumulate. an extension will also enable any necessary base extensions upon which it depends — for example, the +crypto extension will always enable the +simd extension. the exception to the additive construction is for extensions that are prefixed with +no...: these extensions disable the specified option and any other extensions that may depend on the presence of that extension. got it? slay 🫶

for example, -march=armv7-a+simd+nofp+vfpv4 is equivalent to writing -march=armv7-a+vfpv4, since the +simd option is entirely disabled by the +nofp option that follows it. the way that works out is so satisfying ngl ✨

most extension names are generically named, but have an effect that is dependent upon the architecture to which it's applied. for example, the +simd option can be applied to both armv7-a and armv8-a architectures, but will enable the original ARMv7-A Advanced SIMD (Neon) extensions for armv7-a and the ARMv8-A variant for armv8-a. same name, different vibe check 💫

the table below lists the supported extensions for each architecture. architectures not mentioned do not support any extensions. periodt.

  • armv5te, armv6, armv6j, armv6k, armv6kz, armv6t2, armv6z, armv6zk
    • +fp — the VFPv2 floating-point instructions. the extension +vfpv2 can be used as an alias for this extension 🦋
    • +nofp — disable the floating-point instructions.
  • armv7
    • the common subset of the ARMv7-A, ARMv7-R and ARMv7-M architectures 👑
    • +fp — the VFPv3 floating-point instructions, with 16 double-precision registers. the extension +vfpv3-d16 can be used as an alias for this extension. note that floating-point is not supported by the base ARMv7-M architecture, but is compatible with both the ARMv7-A and ARMv7-R architectures.
    • +nofp — disable the floating-point instructions.
  • armv7-a
    • +mp — the multiprocessing extension.
    • +sec — the security extension.
    • +fp — the VFPv3 floating-point instructions, with 16 double-precision registers. the extension +vfpv3-d16 can be used as an alias for this extension.
    • +simd — the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. the extensions +neon and +neon-vfpv3 can be used as aliases for this extension 💖
    • +vfpv3 — the VFPv3 floating-point instructions, with 32 double-precision registers.
    • +vfpv3-d16-fp16 — the VFPv3 floating-point instructions, with 16 double-precision registers and the half-precision floating-point conversion operations.
    • +vfpv3-fp16 — the VFPv3 floating-point instructions, with 32 double-precision registers and the half-precision floating-point conversion operations.
    • +vfpv4-d16 — the VFPv4 floating-point instructions, with 16 double-precision registers.
    • +vfpv4 — the VFPv4 floating-point instructions, with 32 double-precision registers.
    • +neon-fp16 — the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations.
    • +neon-vfpv4 — the Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions 🔥
    • +nosimd — disable the Advanced SIMD instructions (does not disable floating point).
    • +nofp — disable the floating-point and Advanced SIMD instructions 💀
  • armv7ve
    • the extended version of the ARMv7-A architecture with support for virtualization 🌈
    • +fp — the VFPv4 floating-point instructions, with 16 double-precision registers. the extension +vfpv4-d16 can be used as an alias for this extension.
    • +simd — the Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions. the extension +neon-vfpv4 can be used as an alias for this extension.
    • +vfpv3-d16 — the VFPv3 floating-point instructions, with 16 double-precision registers.
    • +vfpv3 — the VFPv3 floating-point instructions, with 32 double-precision registers.
    • +vfpv3-d16-fp16 — the VFPv3 floating-point instructions, with 16 double-precision registers and the half-precision floating-point conversion operations.
    • +vfpv3-fp16 — the VFPv3 floating-point instructions, with 32 double-precision registers and the half-precision floating-point conversion operations.
    • +vfpv4-d16 — the VFPv4 floating-point instructions, with 16 double-precision registers.
    • +vfpv4 — the VFPv4 floating-point instructions, with 32 double-precision registers.
    • +neon — the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. the extension +neon-vfpv3 can be used as an alias for this extension 🎀
    • +neon-fp16 — the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations.
    • +nosimd — disable the Advanced SIMD instructions (does not disable floating point).
    • +nofp — disable the floating-point and Advanced SIMD instructions 😭
  • armv8-a
    • +crc — the Cyclic Redundancy Check (CRC) instructions.
    • +simd — the ARMv8-A Advanced SIMD and floating-point instructions ⭐
    • +crypto — the cryptographic instructions 🔐
  • armv8.1-a
    • +simd — the ARMv8.1-A Advanced SIMD and floating-point instructions ✨
    • +crypto — the cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions 🔐
    • +nocrypto — disable the cryptographic instructions 🙅
    • +nofp — disable the floating-point, Advanced SIMD and cryptographic instructions
    • +sb — Speculation Barrier Instruction
    • +predres — Execution and Data Prediction Restriction Instructions
  • armv8.2-a
  • armv8.3-a

Both of these share the exact same extension list, so here it is once, bestie 🫶

  • +fp16 — the half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions
  • +fp16fml — the half-precision floating-point fmla extension. This also enables the half-precision floating-point extension and Advanced SIMD and floating-point instructions
  • +simd — the ARMv8.1-A Advanced SIMD and floating-point instructions
  • +crypto — the cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions
  • +dotprod — enable the Dot Product extension. This also enables Advanced SIMD instructions
  • +nocrypto — disable the cryptographic extension
  • +nofp — disable the floating-point, Advanced SIMD and cryptographic instructions
  • +sb — Speculation Barrier Instruction
  • +predres — Execution and Data Prediction Restriction Instructions
  • +i8mm — 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions
  • +bf16 — Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions 🧠
  • armv8.4-a
    • +fp16 — the half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension
    • +simd — the ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension
    • +crypto — the cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension
    • +nocrypto — disable the cryptographic extension
    • +nofp — disable the floating-point, Advanced SIMD and cryptographic instructions
    • +sb — Speculation Barrier Instruction
    • +predres — Execution and Data Prediction Restriction Instructions
    • +i8mm — 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions
    • +bf16 — Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions
  • armv8.5-a
    • +fp16 — the half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension
    • +simd — the ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension
    • +crypto — the cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension
    • +nocrypto — disable the cryptographic extension
    • +nofp — disable the floating-point, Advanced SIMD and cryptographic instructions
    • +i8mm — 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions
    • +bf16 — Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions
  • armv8.6-a
    • +fp16 — the half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension
    • +simd — the ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension
    • +crypto — the cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension
    • +nocrypto — disable the cryptographic extension
    • +nofp — disable the floating-point, Advanced SIMD and cryptographic instructions
    • +i8mm — 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions
    • +bf16 — Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions

  • armv7-r
    • +fp.sp — the single-precision VFPv3 floating-point instructions. The extension +vfpv3xd can be used as an alias for this extension
    • +fp — the VFPv3 floating-point instructions with 16 double-precision registers. The extension +vfpv3-d16 can be used as an alias for this extension
    • +vfpv3xd-d16-fp16 — the single-precision VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations
    • +vfpv3-d16-fp16 — the VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations
    • +nofp — disable the floating-point extension
    • +idiv — the ARM-state integer division instructions
    • +noidiv — disable the ARM-state integer division extension
  • armv7e-m
    • +fp — the single-precision VFPv4 floating-point instructions
    • +fpv5 — the single-precision FPv5 floating-point instructions
    • +fp.dp — the single- and double-precision FPv5 floating-point instructions
    • +nofp — disable the floating-point extensions
  • armv8.1-m.main
    • +dsp — the DSP instructions
    • +mve — the M-Profile Vector Extension (MVE) integer instructions
    • +mve.fp — the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions
    • +fp — the single-precision floating-point instructions
    • +fp.dp — the single- and double-precision floating-point instructions
    • +nofp — disable the floating-point extension
    • +cdecp0, +cdecp1, ... , +cdecp7 — enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7 🎛️
  • armv8-m.main
    • +dsp — the DSP instructions
    • +nodsp — disable the DSP extension
    • +fp — the single-precision floating-point instructions
    • +fp.dp — the single- and double-precision floating-point instructions
    • +nofp — disable the floating-point extension
    • +cdecp0, +cdecp1, ... , +cdecp7 — enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7
  • armv8-r
    • +crc — the Cyclic Redundancy Check (CRC) instructions
    • +fp.sp — the single-precision FPv5 floating-point instructions
    • +simd — the ARMv8-A Advanced SIMD and floating-point instructions
    • +crypto — the cryptographic instructions
    • +nocrypto — disable the cryptographic instructions
    • +nofp — disable the floating-point, Advanced SIMD and cryptographic instructions

Okay and one more iconic little detail about the magic word native 👑

-march=native causes the compiler to auto-detect the architecture of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect.

ngl bestie, "has no effect" is the sneakiest outcome here 😭 — it doesn't error out and yell at you, it just quietly does nothing, so don't assume you got native magic just because you typed it 💀
  • -mtune=name — bestie, this one tells GCC which ARM processor it should vibe-tune the generated code for ✨. Some ARM implementations straight-up perform better when you hand it this option, no cap. Permissible names are:
arm7tdmi, arm7tdmi-s, arm710t, arm720t, arm740t, strongarm, strongarm110,
strongarm1100, strongarm1110, arm8, arm810, arm9, arm9e, arm920, arm920t,
arm922t, arm946e-s, arm966e-s, arm968e-s, arm926ej-s, arm940t, arm9tdmi,
arm10tdmi, arm1020t, arm1026ej-s, arm10e, arm1020e, arm1022e, arm1136j-s,
arm1136jf-s, mpcore, mpcorenovfp, arm1156t2-s, arm1156t2f-s, arm1176jz-s,
arm1176jzf-s, generic-armv7-a, cortex-a5, cortex-a7, cortex-a8, cortex-a9,
cortex-a12, cortex-a15, cortex-a17, cortex-a32, cortex-a35, cortex-a53,
cortex-a55, cortex-a57, cortex-a72, cortex-a73, cortex-a75, cortex-a76,
cortex-a76ae, cortex-a77, cortex-a78, cortex-a78ae, cortex-a78c, cortex-a710,
ares, cortex-r4, cortex-r4f, cortex-r5, cortex-r7, cortex-r8, cortex-r52,
cortex-r52plus, cortex-m0, cortex-m0plus, cortex-m1, cortex-m3, cortex-m4,
cortex-m7, cortex-m23, cortex-m33, cortex-m35p, cortex-m55, cortex-x1,
cortex-m1.small-multiply, cortex-m0.small-multiply,
cortex-m0plus.small-multiply, exynos-m1, marvell-pj4, neoverse-n1,
neoverse-n2, neoverse-v1, xscale, iwmmxt, iwmmxt2, ep9312, fa526, fa626,
fa606te, fa626te, fmp626, fa726te, xgene1.

It can also tune for a big.LITTLE system 🧚 — that's the whole "big cores, little cores, one iconic duo" situation. Permissible names there are: cortex-a15.cortex-a7, cortex-a17.cortex-a7, cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a72.cortex-a35, cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55.

And -mtune=generic-arch means "tune for a blend of processors inside architecture arch" 🫶. The goal is code that runs well on the current most popular processors — balancing the optimizations that benefit some CPUs in the range against dodging the performance pitfalls of the others. Heads up though: the effects of this option may change in future GCC versions as CPU models come and go. It's giving "trend cycle", honestly 💅.

-mtune permits the same extension options as -mcpu, but (and this is the plot twist) those extension options do not affect the tuning of the generated code.

-mtune=native makes the compiler auto-detect the CPU of the build computer 🔍. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect — so like, it just shrugs and moves on 😭.


  • -mcpu=name[+extension...] — this specifies the name of the target ARM processor 👑. GCC uses this name to derive the name of the target ARM architecture (as if you'd specified -march) and the ARM processor type to tune for performance (as if you'd specified -mtune). Where this option is used in conjunction with -march or -mtune, those options take precedence over the appropriate part of this option — so they win the argument, periodt.

Many of the supported CPUs implement optional architectural extensions. Where this is so, the architectural extensions are normally enabled by default. If implementations that lack the extension exist, then the extension syntax can be used to disable those extensions that have been omitted ✨. For floating-point and Advanced SIMD (Neon) instructions, the settings of the options -mfloat-abi and -mfpu must also be considered: floating-point and Advanced SIMD instructions will only be used if -mfloat-abi is not set to soft; and any setting of -mfpu other than auto will override the available floating-point and SIMD extension instructions.

For example, cortex-a9 can be found in three major configurations: integer only, with just a floating-point unit, or with floating-point and Advanced SIMD 🎀. The default is to enable all the instructions, but the extensions +nosimd and +nofp can be used to disable just the SIMD or both the SIMD and floating-point instructions respectively.

Permissible names for this option are the same as those for -mtune.

The following extension options are common to the listed CPUs:

  • +nodsp — disables the DSP instructions on cortex-m33, cortex-m35p.
  • +nofp — disables the floating-point instructions on arm9e, arm946e-s, arm966e-s, arm968e-s, arm10e, arm1020e, arm1022e, arm926ej-s, arm1026ej-s, cortex-r5, cortex-r7, cortex-r8, cortex-m4, cortex-m7, cortex-m33 and cortex-m35p. Also disables the floating-point and SIMD instructions on generic-armv7-a, cortex-a5, cortex-a7, cortex-a8, cortex-a9, cortex-a12, cortex-a15, cortex-a17, cortex-a15.cortex-a7, cortex-a17.cortex-a7, cortex-a32, cortex-a35, cortex-a53 and cortex-a55.
  • +nofp.dp — disables the double-precision component of the floating-point instructions on cortex-r5, cortex-r7, cortex-r8, cortex-r52, cortex-r52plus and cortex-m7.
  • +nosimd — disables the SIMD (but not floating-point) instructions on generic-armv7-a, cortex-a5, cortex-a7 and cortex-a9.
  • +crypto — enables the cryptographic instructions on cortex-a32, cortex-a35, cortex-a53, cortex-a55, cortex-a57, cortex-a72, cortex-a73, cortex-a75, exynos-m1, xgene1, cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a73.cortex-a35, cortex-a73.cortex-a53 and cortex-a75.cortex-a55. 🔐

Additionally the generic-armv7-a pseudo target defaults to VFPv3 with 16 double-precision registers. It supports the following extension options: mp, sec, vfpv3-d16, vfpv3, vfpv3-d16-fp16, vfpv3-fp16, vfpv4-d16, vfpv4, neon, neon-vfpv3, neon-fp16, neon-vfpv4. The meanings are the same as for the extensions to -march=armv7-a 💖.

-mcpu=generic-arch is also permissible, and is equivalent to -march=arch -mtune=generic-arch. See -mtune for more information.

-mcpu=native causes the compiler to auto-detect the CPU of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect. Same energy as -mtune=native, same "it's fine, we tried" 😭.


  • -mfpu=name — this one specifies what floating-point hardware (or hardware emulation) is available on the target 🌸. Permissible names are: auto, vfpv2, vfpv3, vfpv3-fp16, vfpv3-d16, vfpv3-d16-fp16, vfpv3xd, vfpv3xd-fp16, neon-vfpv3, neon-fp16, vfpv4, vfpv4-d16, fpv4-sp-d16, neon-vfpv4, fpv5-d16, fpv5-sp-d16, fp-armv8, neon-fp-armv8 and crypto-neon-fp-armv8. Note that neon is an alias for neon-vfpv3 and vfp is an alias for vfpv2 — they're literally the same girl, different name tags 💅.

The setting auto is the default and is special. It causes the compiler to select the floating-point and Advanced SIMD instructions based on the settings of -mcpu and -march.

If the selected floating-point hardware includes the NEON extension (e.g. -mfpu=neon), note that floating-point operations are not generated by GCC's auto-vectorization pass unless -funsafe-math-optimizations is also specified ⚠️. This is because NEON hardware does not fully implement the IEEE 754 standard for floating-point arithmetic (in particular denormal values are treated as zero), so the use of NEON instructions may lead to a loss of precision. Like, it's cute but it will fudge your numbers, so know what you're signing up for 🙈.

You can also set the fpu name at function level by using the target("fpu=") function attributes or pragmas ✨.


  • -mfp16-format=name — specify the format of the __fp16 half-precision floating-point type 🎀. Permissible names are none, ieee, and alternative; the default is none, in which case the __fp16 type is not defined. No format, no type — that's the deal.

  • -mstructure-size-boundary=n — the sizes of all structures and unions are rounded up to a multiple of the number of bits set by this option 📏. Permissible values are 8, 32 and 64. The default value varies for different toolchains. For the COFF targeted toolchain the default value is 8. A value of 64 is only allowed if the underlying ABI supports it — don't come at it with 64 if the ABI can't hold it 🫠.

Specifying a larger number can produce faster, more efficient code, but can also increase the size of the program. Different values are potentially incompatible. Code compiled with one value cannot necessarily expect to work with code or libraries compiled with another value, if they exchange information using structures or unions. That's a real "we don't match, bestie" situation 💀.

This option is deprecated.

  • -mabort-on-noreturn — generate a call to the function abort at the end of a noreturn function. It is executed if the function tries to return. So if the function said it wasn't gonna come back and then it does, things get loud 🔥.

  • -mlong-calls, -mno-long-calls — tells the compiler to perform function calls by first loading the address of the function into a register and then performing a subroutine call on this register 💖. This switch is needed if the target function lies outside of the 64-megabyte addressing range of the offset-based version of subroutine call instruction. It's the "address too far for the short reach" situation, iykyk.

Even if this switch is enabled, not all function calls are turned into long calls. The heuristic is that static functions, functions that have the short_call attribute, functions that are inside the scope of a #pragma no_long_calls directive, and functions whose definitions have already been compiled within the current compilation unit are not turned into long calls. The exceptions to this rule are that weak function definitions, functions with the long_call attribute or the section attribute, and functions that are within the scope of a #pragma long_calls directive are always turned into long calls ✨.

This feature is not enabled by default. Specifying -mno-long-calls restores the default behavior, as does placing the function calls within the scope of a #pragma long_calls_off directive. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers 👀.


  • -msingle-pic-base — treat the register used for PIC addressing as read-only, rather than loading it in the prologue for each function 🎀. The runtime system is responsible for initializing this register with an appropriate value before execution begins. So somebody's gotta set it up — and that somebody is not the compiler, bestie 🫶.

  • -mpic-register=reg — specify the register to be used for PIC addressing 🦋. For standard PIC base case, the default is any suitable register determined by compiler. For single PIC base case, the default is R9 if target is EABI based or stack-checking is enabled, otherwise the default is R10. Cute little defaults, very demure 💅.
  • -mpic-data-is-text-relative — okay so this one assumes the displacement between the text and data segments is locked in at static link time, periodt. That lets the compiler use PC-relative addressing ops to reach data it knows lives in the data segment. For non-VxWorks RTP targets it's on by default ✨ — and if you disable it on those targets, it'll turn on -msingle-pic-base by default instead. The way these two are besties, iykyk.
  • -mpoke-function-name — writes the name of every function into the text section, directly before the function prologue. The generated code is giving:
             t0
                 .ascii "arm_poke_function_name", 0
                 .align
             t1
                 .word 0xff000000 + (t1 - t0)
             arm_poke_function_name
                 mov     ip, sp
                 stmfd   sp!, {fp, ip, lr, pc}
                 sub     fp, ip, #4

When you're doing a stack backtrace, the code can peek at the value of pc stored at fp + 0. If the trace function then looks at location pc - 12 and the top 8 bits are set, then we know a function name is embedded immediately preceding that location, and it has length ((pc[-3]) & 0xff000000). Detective work honestly 💅

  • -mthumb, -marm — pick between generating code that runs in ARM state vs Thumb state, no cap. For most configurations the default is code that executes in ARM state, but that default can be changed by configuring GCC with the --with-mode=state configure option. You can also override ARM/Thumb mode per-function using the target("thumb") and target("arm") function attributes or pragmas 🫶
  • -mflip-thumb — switches ARM/Thumb modes on alternating functions like it's shuffling a playlist. This one exists purely for regression testing of mixed Thumb/ARM code generation, and is not intended for ordinary use in compiling code. It's a lab rat, not a pet 🐭
  • -mtpcs-frame — generates a stack frame compliant with the Thumb Procedure Call Standard for all non-leaf functions. (A leaf function is one that doesn't call any other functions, bless.) The default is -mno-tpcs-frame.
  • -mtpcs-leaf-frame — generates a stack frame compliant with the Thumb Procedure Call Standard for all leaf functions. (Yes, same parenthetical: a leaf function calls nothing else.) The default is -mno-apcs-leaf-frame.
  • -mcallee-super-interworking — gives every externally visible function in the file you're compiling an ARM instruction-set header that switches into Thumb mode before it runs the rest of the function. That lets these functions be called from non-interworking code. Heads up: this option is not valid in AAPCS configurations, because interworking is enabled by default there anyway 💀
  • -mcaller-super-interworking — lets calls via function pointers (virtual functions included 👀) execute correctly whether or not the target code was compiled for interworking. There's a small overhead in the cost of executing a function pointer if you enable this. Same warning: not valid in AAPCS configurations, since interworking is on by default there.
  • -mtp=name — specifies the access model for the thread local storage pointer. The valid models are soft, which generates calls to __aeabi_read_tp; cp15, which fetches the thread pointer from cp15 directly (supported in the arm6k architecture); and auto, which uses the best available method for the selected processor. Default setting is auto 👑
  • -mtls-dialect=dialect — picks the dialect for accessing thread local storage. Two dialects are supported: gnu and gnu2. The gnu dialect selects the original GNU scheme for supporting local and global dynamic TLS models. The gnu2 dialect selects the GNU descriptor scheme, which gives better performance for shared libraries. The GNU descriptor scheme is compatible with the original scheme, but it does require new assembler, linker and library support. Initial and local exec TLS models are unaffected by this option and always use the original scheme, not me making exceptions 🌸
  • -mword-relocations — only generate absolute relocations on word-sized values (i.e. R_ARM_ABS32). This is enabled by default on targets (uClinux, SymbianOS) where the runtime loader imposes that restriction, and also when -fpic or -fPIC is specified. Warning bestie: this option conflicts with -mslow-flash-data 🚨
  • -mfix-cortex-m3-ldrd — some Cortex-M3 cores can cause data corruption when ldrd instructions with overlapping destination and base registers are used 😭 This option avoids generating those instructions. Enabled by default when -mcpu=cortex-m3 is specified.
  • -mfix-cortex-a57-aes-1742098, -mno-fix-cortex-a57-aes-1742098, -mfix-cortex-a72-aes-1655431, -mno-fix-cortex-a72-aes-1655431 — enable (or disable) the mitigation for an erratum on Cortex-A57 and Cortex-A72 that affects the AES cryptographic instructions. This option is enabled by default when either -mcpu=cortex-a57 or -mcpu=cortex-a72 is specified 🔥
  • -munaligned-access, -mno-unaligned-access — enables (or disables) reading and writing of 16- and 32-bit values from addresses that aren't 16- or 32-bit aligned. By default unaligned access is disabled for all pre-ARMv6, all ARMv6-M and for ARMv8-M Baseline architectures, and enabled for all other architectures. If unaligned access isn't enabled, then words in packed data structures get accessed a byte at a time 🐌 The ARM attribute Tag_CPU_unaligned_access is set in the generated object file to either true or false, depending on this option's setting. And if unaligned access is enabled, the preprocessor symbol __ARM_FEATURE_UNALIGNED is also defined ✨
  • -mneon-for-64bits — this option is deprecated and has no effect. That's it, that's the whole tea ☕💀
  • -mslow-flash-data — assumes loading data from flash is slower than fetching an instruction. So literal load gets minimized for better performance. This option is only supported when compiling for ARMv7 M-profile, and it's off by default. It conflicts with -mword-relocations 🌈
  • -masm-syntax-unified — assumes inline assembler is using unified asm syntax. The default is currently off, which implies divided syntax. This option has no impact on Thumb2. However, this may change in future releases of GCC. Divided syntax should be considered deprecated 👀
  • -mrestrict-it — restricts generation of IT blocks to conform to the rules of ARMv8-A. IT blocks can only contain a single 16-bit instruction from a select set of instructions. This option is on by default for ARMv8-A Thumb mode 💅
  • -mprint-tune-info — prints CPU tuning information as a comment in the assembler file. This is an option used only for regression testing of the compiler and is not intended for ordinary use in compiling code. Disabled by default 🧪
  • -mverbose-cost-dump — enables verbose cost model dumping in the debug dump files. This option is provided for use in debugging the compiler, so it's a compiler-dev moment, not a you moment 🫶
  • -mpure-code — do not allow constant data to be placed in code sections, periodt. Additionally, when compiling for ELF object format, give all text sections the ELF processor-specific section attribute SHF_ARM_PURECODE. This option is only available when generating non-pic code for M-profile targets 🎀
  • -mcmse — generates secure code as per the "ARMv8-M Security Extensions: Requirements on Development Tools Engineering Specification", which can be found on https://developer.arm.com/documentation/ecm0359818/latest/ 📜
  • -mfix-cmse-cve-2021-35465 — mitigates against a potential security issue with the VLLDM instruction in some M-profile devices when using CMSE (CVE-2021-365465). This option is enabled by default when the option -mcpu= is used with cortex-m33, cortex-m35p or cortex-m55. The option -mno-fix-cmse-cve-2021-35465 can be used to disable the mitigation 🛡️
  • -mstack-protector-guard=guard, -mstack-protector-guard-offset=offset — generate stack protection code using a canary at guard. Supported locations are global for a global canary, or tls for a canary accessible via the TLS register. The option -mstack-protector-guard-offset= is for use with -fstack-protector-guard=tls and not for use in user-land code, okay? Not for you 🙈
  • -mfdpic, -mno-fdpic — selects the FDPIC ABI, which uses 64-bit function descriptors to represent pointers to functions. When the compiler is configured for arm-*-uclinuxfdpiceabi targets, this option is on by default and implies -fPIE if none of the PIC/PIE-related options is provided. On other targets, it only enables the FDPIC-specific code generation features, and you should explicitly provide the PIC/PIE-related options as needed 💖 Note that static linking is not supported, because it would still involve the dynamic linker when the program self-relocates. If such behavior is acceptable, use -static and -Wl,-dynamic-linker options. The opposite -mno-fdpic option is useful (and required) to build the Linux kernel using the same (arm-*-uclinuxfdpiceabi) toolchain as the one used to build the userland programs 👑

🧚 AVR Options 🧚

These options are defined for AVR implementations, bestie:

  • -mmcu=mcu — specify Atmel AVR instruction set architecture (ISA) or MCU type. The default for this option is avr2. GCC supports the following AVR devices and ISAs 🦋
    • avr2 — "Classic" devices with up to 8 KiB of program memory. mcu = attiny22, attiny26, at90s2313, at90s2323, at90s2333, at90s2343, at90s4414, at90s4433, at90s4434, at90c8534, at90s8515, at90s8535.
    • avr25 — "Classic" devices with up to 8 KiB of program memory and with the MOVW instruction. mcu = attiny13, attiny13a, attiny24, attiny24a, attiny25, attiny261, attiny261a, attiny2313, attiny2313a, attiny43u, attiny44, attiny44a, attiny45, attiny48, attiny441, attiny461, attiny461a, attiny4313, attiny84, attiny84a, attiny85, attiny87, attiny88, attiny828, attiny841, attiny861, attiny861a, ata5272, ata6616c, at86rf401.
    • avr3 — "Classic" devices with 16 KiB up to 64 KiB of program memory. mcu = at76c711, at43usb355.
    • avr31 — "Classic" devices with 128 KiB of program memory. mcu = atmega103, at43usb320.

🧚 avr35

"Classic" girlies with 16 KiB up to 64 KiB of program memory and the MOVW instruction — fancy hands, bestie 💅

mcu = attiny167, attiny1634, atmega8u2, atmega16u2, atmega32u2, ata5505, ata6617c, ata664251, at90usb82, at90usb162

🌸 avr4

"Enhanced" devices with up to 8 KiB of program memory — small but mighty, no cap ✨

mcu = atmega48, atmega48a, atmega48p, atmega48pa, atmega48pb, atmega8, atmega8a, atmega8hva, atmega88, atmega88a, atmega88p, atmega88pa, atmega88pb, atmega8515, atmega8535, ata6285, ata6286, ata6289, ata6612c, at90pwm1, at90pwm2, at90pwm2b, at90pwm3, at90pwm3b, at90pwm81

🫶 avr5

"Enhanced" devices with 16 KiB up to 64 KiB of program memory — this list is LONG and it ate, honestly 😭

mcu = atmega16, atmega16a, atmega16hva, atmega16hva2, atmega16hvb, atmega16hvbrevb, atmega16m1, atmega16u4, atmega161, atmega162, atmega163, atmega164a, atmega164p, atmega164pa, atmega165, atmega165a, atmega165p, atmega165pa, atmega168, atmega168a, atmega168p, atmega168pa, atmega168pb, atmega169, atmega169a, atmega169p, atmega169pa, atmega32, atmega32a, atmega32c1, atmega32hvb, atmega32hvbrevb, atmega32m1, atmega32u4, atmega32u6, atmega323, atmega324a, atmega324p, atmega324pa, atmega324pb, atmega325, atmega325a, atmega325p, atmega325pa, atmega328, atmega328p, atmega328pb, atmega329, atmega329a, atmega329p, atmega329pa, atmega3250, atmega3250a, atmega3250p, atmega3250pa, atmega3290, atmega3290a, atmega3290p, atmega3290pa, atmega406, atmega64, atmega64a, atmega64c1, atmega64hve, atmega64hve2, atmega64m1, atmega64rfr2, atmega640, atmega644, atmega644a, atmega644p, atmega644pa, atmega644rfr2, atmega645, atmega645a, atmega645p, atmega649, atmega649a, atmega649p, atmega6450, atmega6450a, atmega6450p, atmega6490, atmega6490a, atmega6490p, ata5795, ata5790, ata5790n, ata5791, ata6613c, ata6614q, ata5782, ata5831, ata8210, ata8510, ata5702m322, at90pwm161, at90pwm216, at90pwm316, at90can32, at90can64, at90scr100, at90usb646, at90usb647, at94k, m3000

🦋 avr51

"Enhanced" devices with 128 KiB of program memory — big brain energy 🧠✨

mcu = atmega128, atmega128a, atmega128rfa1, atmega128rfr2, atmega1280, atmega1281, atmega1284, atmega1284p, atmega1284rfr2, at90can128, at90usb1286, at90usb1287

👑 avr6

"Enhanced" devices with a 3-byte PC, i.e. with more than 128 KiB of program memory — three whole bytes of where am I, we stan a chunky program counter 💖

mcu = atmega256rfr2, atmega2560, atmega2561, atmega2564rfr2

🌈 avrxmega2

"XMEGA" devices with more than 8 KiB and up to 64 KiB of program memory

mcu = atxmega8e5, atxmega16a4, atxmega16a4u, atxmega16c4, atxmega16d4, atxmega16e5, atxmega32a4, atxmega32a4u, atxmega32c3, atxmega32c4, atxmega32d3, atxmega32d4, atxmega32e5

🍓 avrxmega3

"XMEGA" devices with up to 64 KiB of combined program memory and RAM, and with program memory visible in the RAM address space — the memory map said "our space now", iconic 🎀

mcu = attiny202, attiny204, attiny212, attiny214, attiny402, attiny404, attiny406, attiny412, attiny414, attiny416, attiny417, attiny804, attiny806, attiny807, attiny814, attiny816, attiny817, attiny1604, attiny1606, attiny1607, attiny1614, attiny1616, attiny1617, attiny3214, attiny3216, attiny3217, atmega808, atmega809, atmega1608, atmega1609, atmega3208, atmega3209, atmega4808, atmega4809

💜 avrxmega4

"XMEGA" devices with more than 64 KiB and up to 128 KiB of program memory

mcu = atxmega64a3, atxmega64a3u, atxmega64a4u, atxmega64b1, atxmega64b3, atxmega64c3, atxmega64d3, atxmega64d4

⭐ avrxmega5

"XMEGA" devices with more than 64 KiB and up to 128 KiB of program memory and more than 64 KiB of RAM — she has range 💅

mcu = atxmega64a1, atxmega64a1u

🔥 avrxmega6

"XMEGA" devices with more than 128 KiB of program memory

mcu = atxmega128a3, atxmega128a3u, atxmega128b1, atxmega128b3, atxmega128c3, atxmega128d3, atxmega128d4, atxmega192a3, atxmega192a3u, atxmega192c3, atxmega192d3, atxmega256a3, atxmega256a3b, atxmega256a3bu, atxmega256a3u, atxmega256c3, atxmega256d3, atxmega384c3, atxmega384d3

🧊 avrxmega7

"XMEGA" devices with more than 128 KiB of program memory and more than 64 KiB of RAM — the main character of the XMEGA lineup, lowkey 🤩

mcu = atxmega128a1, atxmega128a1u, atxmega128a4u

🙈 avrtiny

"TINY" Tiny core devices with 512 B up to 4 KiB of program memory — baby-sized, pocket-sized, still slays 🎀

mcu = attiny4, attiny5, attiny9, attiny10, attiny20, attiny40

💀 avr1

This ISA is implemented by the minimal AVR core and is supported for assembler only. That's it. No compiler glow-up for this one, bestie 😭

mcu = attiny11, attiny12, attiny15, attiny28, at90s1200


  • -mabsdata — Assume that all data in static storage can be accessed by LDS / STS instructions. Heads up: this option only does anything on reduced Tiny devices like ATtiny40. Also peep the absdata AVR Variable Attributes, variable attribute 🫶
  • -maccumulate-args — Accumulate outgoing function arguments and grab/release the needed stack space for them once in the function prologue/epilogue. Without this option, outgoing arguments get pushed before calling a function and popped afterwards.

Popping args after the call can be expensive on AVR, so accumulating the stack space might give you smaller executables, because the arguments don't need to be removed from the stack after such a call. Ngl that's the whole pitch ✨

This option can reduce code size for functions that make several calls to functions that take their arguments on the stack — like calls to printf-style functions.

  • -mbranch-cost=cost — Set the branch costs for conditional branch instructions to cost. Reasonable values for cost are **small, non-negative integers. The default branch cost is 0. Keep it tiny, keep it cute 🧚
  • -mcall-prologues — Function prologues/epilogues get expanded as calls to the appropriate subroutines. Code size is smaller. Periodt 💅
  • *-mdouble=bits*
  • *-mlong-double=bits* — Set the size (in bits) of the double or long double type, respectively. Possible values for bits are 32 and 64. Whether a specific bits value is even allowed depends on the --with-double= and --with-long-double= configure options (https://gcc.gnu.org/install/configure.html#avr), and the same goes for the default values of these options 🙈
  • -mgas-isr-prologues — Interrupt service routines (ISRs) may use the __gcc_isr pseudo instruction supported by GNU Binutils. If this option is on, you can still disable the feature for individual ISRs using the AVR Function Attributes no_gccisr function attribute. It's activated by default if optimization is on (but not with -Og, @pxref{Optimize Options}), and if GNU Binutils supports PR21683 (https://sourceware.org/PR21683) ⭐
  • -mint8 — Assume int is an 8-bit integer. This affects the sizes of all types: a char is 1 byte, an int is 1 byte, a long is 2 bytes, and long long is 4 bytes. Bestie, please note this option does not conform to the C standards — but it does give you smaller code size 💀
  • -mmain-is-OS_task — Do not save registers in main. Same effect as attaching the AVR Function Attributes OS_task attribute to main. It's activated by default if optimization is on 🫶
  • -mn-flash=num — Assume the flash memory has a size of num times **64 KiB.
  • -mno-interrupts — Generated code is not compatible with hardware interrupts. Code size is smaller. Yes, that's the trade, and yes, it's a real one 🚨
  • -mrelax — Try to replace CALL resp. JMP instructions with the shorter RCALL resp. RJMP instruction if applicable. Setting -mrelax just adds the --mlink-relax option to the assembler's command line and the --relax option to the linker's command line.

Jump relaxing is performed by the linker, because jump offsets aren't known before the code is located. So the assembler code generated by the compiler is the same, but the instructions in the executable may differ from the instructions in the assembler code. Sneaky but valid 💅

Relaxing must be turned on if linker stubs are needed — see the section on EIND and linker stubs below. Don't skip this one, fr fr.
  • -mrmw — Assume the device supports the Read-Modify-Write instructions XCH, LAC, LAS and LAT 🔥
  • -mshort-calls — Assume that RJMP and RCALL can target the whole program memory.

This option is used internally for multilib selection. It is not an optimization option, and you don't need to set it by hand. Hands off, bestie 🙈

  • -msp8 — Treat the stack pointer register as an 8-bit register, i.e. assume the high byte of the stack pointer is zero. In general, you don't need to set this option by hand either.

This option is used internally by the compiler to select and build multilibs for architectures avr2 and avr25. Those architectures mix devices with and without SPH. For any setting other than -mmcu=avr2 or -mmcu=avr25, the compiler driver adds or removes this option from the compiler proper's command line, because the compiler then knows whether the device or architecture has an 8-bit stack pointer and thus no SPH register or not. She's doing bookkeeping behind the scenes, iconic 🎀

  • -mstrict-X — Use address register X the way the hardware proposes. Meaning: X is only used in indirect, post-increment or pre-decrement addressing.

Without this option, the X register may be used the same way as Y or Z, which then gets emulated by additional instructions. For example, loading a value with X+const addressing with a small non-negative const < 64 into a register Rn is performed as:

        adiw r26, const   ; X += const
        ld   <Rn>, X        ; <Rn> = *X
        sbiw r26, const   ; X -= const
  • -mtiny-stack — Only change the lower 8 bits of the stack pointer. Small stack, small problems ✨
  • -mfract-convert-truncate — lets you use truncation instead of rounding-towards-zero when you're dealing with fractional fixed-point types. floor behavior, basically. 💅
  • -nodevicelib — nope, do NOT link against AVR-LibC's device-specific library "lib<mcu>.a". skipping that whole vibe.
  • -nodevicespecs — doesn't add -specs=device-specs/specs-mcu to the compiler driver's command line. and bestie, when you pass this, you are the main character now — you take full responsibility for supplying the sub-processes (compiler proper, assembler, linker) with the appropriate command line options. 😭 this means you have to supply your private device specs file via -specs=path-to-specs-file. the good news? no more need for the option -mmcu=mcu. slay.

this option can also serve as a replacement for the older way of specifying custom device-specs files, which needed -B some-path to point to a directory containing a folder named "device-specs", which contains a specs file named "specs-mcu", where mcu was specified by -mmcu=mcu.

  • -Waddr-space-convert — warns you about conversions between address spaces when the resulting address space is not contained in the incoming address space. red flag behavior, she'll tell you. 🚩
  • -Wmisspelled-isr — warns if the ISR is misspelled, i.e. without the __vector prefix. enabled by default — she's always watching. 👀

🦋 EIND and Devices with More Than 128 Ki Bytes of Flash 🦋

So pointers in this implementation are 16 bits wide, periodt. the address of a function or label is represented as a word address so that indirect jumps and calls can target any code address in the range of 64 Ki words.

To make indirect jump work on devices with more than 128 Ki bytes of program memory, there's a special function register called EIND that serves as the most significant part of the target address when EICALL or EIJMP instructions are used. ✨ iconic of her.

Indirect jumps and calls on these devices get handled as follows by the compiler, and are subject to some limitations:

  • The compiler never sets EIND. not once.
  • The compiler uses EIND implicitly in EICALL/EIJMP instructions, or might read EIND directly in order to emulate an indirect call/jump by means of a RET instruction.
  • The compiler assumes that EIND never changes during the startup code or during the application. in particular, EIND is not saved/restored in function or interrupt service routine prologue/epilogue. so don't come for her.
  • For indirect calls to functions and computed goto, the linker generates stubs. stubs are jump pads, sometimes also called trampolines. so the indirect call/jump jumps to such a stub, and the stub contains a direct jump to the desired address. 🛝
  • Linker relaxation must be turned on so the linker generates the stubs correctly in all situations. see the compiler option -mrelax and the linker option --relax. there are corner cases where the linker is supposed to generate stubs but aborts without relaxation and without a helpful error message. 💀 brutal.
  • The default linker script is arranged for code with EIND = 0. if your code is supposed to work for a setup with EIND != 0, a custom linker script has to be used in order to place the sections whose name start with .trampolines into the segment where EIND points to.
  • The startup code from libgcc never sets EIND. notice that startup code is a blend of code from libgcc and AVR-LibC. for the impact of AVR-LibC on EIND, see the AVR-LibC user manual ("http://nongnu.org/avr-libc/user-manual/").
  • It's legit for user-specific startup code to set up EIND early — for example by means of initialization code located in section .init3. such code runs prior to general startup code that initializes RAM and calls constructors, but after the bit of startup code from AVR-LibC that sets EIND to the segment where the vector table is located. 🫶
#include <avr/io.h>

static void
__attribute__((section(".init3"),naked,used,no_instrument_function))
init3_set_eind (void)
{
  __asm volatile ("ldi r24,pm_hh8(__trampolines_start)\n\t"
                  "out %i0,r24" :: "n" (&EIND) : "r24","memory");
}

The __trampolines_start symbol is defined in the linker script. no cap.

  • Stubs are generated automatically by the linker if these two conditions are met:
    • The address of a label is taken by means of the gs modifier (short for generate stubs), like so:
LDI r24, lo8(gs(<func>))
LDI r25, hi8(gs(<func>))
  • The final location of that label is in a code segment outside the segment where the stubs are located.
  • The compiler emits such gs modifiers for code labels in the following situations:
    • Taking address of a function or code label.
    • Computed goto.
    • If prologue-save function is used, see -mcall-prologues command-line option.
    • Switch/case dispatch tables. if you do not want such dispatch tables, you can specify the -fno-jump-tables command-line option.
    • C and C++ constructors/destructors called during startup/shutdown.
    • If the tools hit a gs() modifier explained above.
  • Jumping to non-symbolic addresses like this is not supported:
int main (void)
{
    /* Call function at word address 0x2 */
    return ((int(*)(void)) 0x2)();
}

instead, a stub has to be set up, i.e. the function has to be called through a symbol (func_4 in the example):

int main (void)
{
    extern int func_4 (void);

    /* Call function at byte address 0x4 */
    return func_4();
}

and the application has to be linked with -Wl,--defsym,func_4=0x4. alternatively, func_4 can be defined in the linker script. iykyk. 🌸


👑 Handling of the RAMPD, RAMPX, RAMPY and RAMPZ Special Function Registers 👑

Some AVR devices support memories larger than the 64 KiB range that can be accessed with 16-bit pointers. to access memory locations outside this 64 KiB range, the content of a RAMP register is used as the high part of the address: the X, Y, Z address register is concatenated with the RAMPX, RAMPY, RAMPZ special function register, respectively, to get a wide address. similarly, RAMPD is used together with direct addressing. she's got range. 💅

  • The startup code initializes the RAMP special function registers with zero.
  • If an AVR Named Address Space — a named address space other than generic or __flash — is used, then RAMPZ is set as needed before the operation.
  • If the device supports RAM larger than 64 KiB and the compiler needs to change RAMPZ to accomplish an operation, RAMPZ is reset to zero after the operation. clean up after yourself, bestie. 🧹
  • If the device comes with a specific RAMP register, the ISR prologue/epilogue saves/restores that SFR and initializes it with zero in case the ISR code might (implicitly) use it.
  • RAM larger than 64 KiB is not supported by GCC for AVR targets. if you use inline assembler to read from locations outside the 16-bit address range and change one of the RAMP registers, you must reset it to zero after the access. no exceptions. 😤

⭐ AVR Built-in Macros ⭐

GCC defines several built-in macros so your user code can test for the presence or absence of features. almost any of the following built-in macros are deduced from device capabilities and thus triggered by the -mmcu= command-line option. ✨

For even more AVR-specific built-in macros, see AVR Named Address Spaces and AVR Built-in Functions.

  • __AVR_ARCH__ — built-in macro that resolves to a decimal number identifying the architecture, and it depends on the -mmcu=mcu option. possible values are:

2, 25, 3, 31, 35, 4, 5, 51, 6

for mcu = "avr2", "avr25", "avr3", "avr31", "avr35", "avr4", "avr5", "avr51", "avr6", respectively, and

100, 102, 103, 104, 105, 106, 107

for mcu = "avrtiny", "avrxmega2", "avrxmega3", "avrxmega4", "avrxmega5", "avrxmega6", "avrxmega7", respectively. if mcu specifies a device, this built-in macro is set accordingly. for example, with -mmcu=atmega8 the macro is defined to 4.

  • __AVR_Device__ — setting -mmcu=device defines this built-in macro, which reflects the device's name. for example, -mmcu=atmega8 defines the built-in macro __AVR_ATmega8__, -mmcu=attiny261a defines __AVR_ATtiny261A__, etc.

the built-in macros' names follow the scheme __AVR_Device__ where Device is the device name as from the AVR user manual. the difference between Device in the built-in macro and device in -mmcu=device is that the latter is always lowercase. 🔤

if device is not a device but only a core architecture like avr51, this macro is not defined.

  • __AVR_DEVICE_NAME__ — setting -mmcu=device defines this built-in macro to the device's name. for example, with -mmcu=atmega8 the macro is defined to "atmega8".

if device is not a device but only a core architecture like avr51, this macro is not defined.

  • __AVR_XMEGA__ — the device / architecture belongs to the XMEGA family of devices. 💜
  • __AVR_HAVE_ELPM__ — the device has the ELPM instruction.
  • __AVR_HAVE_ELPMX__ — the device has the ELPM Rn,Z and ELPM Rn,Z+ instructions.
  • __AVR_HAVE_MOVW__ — the device has the MOVW instruction to perform 16-bit register-register moves.
  • __AVR_HAVE_LPMX__ — the device has the LPM Rn,Z and LPM Rn,Z+ instructions.
  • __AVR_HAVE_MUL__ — the device has a hardware multiplier. 🔥
  • __AVR_HAVE_JMP_CALL__ — the device has the JMP and CALL instructions. this is the case for devices with more than 8 KiB of program memory.
  • __AVR_HAVE_EIJMP_EICALL__, __AVR_3_BYTE_PC__ — the device has the EIJMP and EICALL instructions. this is the case for devices with more than 128 KiB of program memory. this also means the program counter (PC) is 3 bytes wide.
  • __AVR_2_BYTE_PC__ — the program counter (PC) is 2 bytes wide. this is the case for devices with up to 128 KiB of program memory.
  • __AVR_HAVE_8BIT_SP__, __AVR_HAVE_16BIT_SP__ — the stack pointer (SP) register is treated as an 8-bit respectively 16-bit register by the compiler. the definition of these macros is affected by -mtiny-stack. 🎀
  • __AVR_HAVE_SPH__, __AVR_SP8__ — bestie, this chip either has the SPH (high part of stack pointer) special function register, or it has an 8-bit stack pointer, respectively 💅. The definition of these macros is affected by -mmcu= and, in the cases of -mmcu=avr2 and -mmcu=avr25, also by -msp8.
  • __AVR_HAVE_RAMPD__, __AVR_HAVE_RAMPX__, __AVR_HAVE_RAMPY__, __AVR_HAVE_RAMPZ__ — the device has the RAMPD, RAMPX, RAMPY, RAMPZ special function register, respectively ✨.
  • __NO_INTERRUPTS__ — this macro reflects the -mno-interrupts command-line option 💖.
  • __AVR_ERRATA_SKIP__, __AVR_ERRATA_SKIP_JMP_CALL__ — some AVR devices (AT90S8515, ATmega103) must not skip 32-bit instructions because of a hardware erratum 😭. The skip instructions are SBRS, SBRC, SBIS, SBIC and CPSE. The second macro is only defined if __AVR_HAVE_JMP_CALL__ is also set.
  • __AVR_ISA_RMW__ — the device has Read-Modify-Write instructions (XCH, LAC, LAS and LAT) 🔥.
  • __AVR_SFR_OFFSET__=offset — instructions that can address I/O special function registers directly, like IN, OUT, SBI, etc., may use a different address than if addressed by an instruction to access RAM like LD or STS 👀. This offset depends on the device architecture and has to be subtracted from the RAM address in order to get the respective I/O address.
  • __AVR_SHORT_CALLS__ — the -mshort-calls command-line option is set ⭐.
  • __AVR_PM_BASE_ADDRESS__=addr — some devices support reading from flash memory by means of LD* instructions 🦋. The flash memory is seen in the data address space at an offset of __AVR_PM_BASE_ADDRESS__. If this macro is not defined, this feature is not available. If defined, the address space is linear and there is no need to put .rodata into RAM. This is handled by the default linker description file, and is currently available for avrtiny and avrxmega3. Even more convenient, there is no need to use address spaces like __flash or features like attribute progmem and pgm_read_* 🎀.
  • __WITH_AVRLIBC__ — the compiler is configured to be used together with AVR-Libc. See the --with-avrlibc configure option 💜.
  • __HAVE_DOUBLE_MULTILIB__ — defined if -mdouble= acts as a multilib option 🌸.
  • __HAVE_DOUBLE32__, __HAVE_DOUBLE64__ — defined if the compiler supports 32-bit double and 64-bit double, respectively. The actual layout is specified by option -mdouble=.
  • __DEFAULT_DOUBLE__ — the size in bits of double if -mdouble= is not set. To test the layout of double in a program, use the built-in macro __SIZEOF_DOUBLE__ 🧚.
  • __HAVE_LONG_DOUBLE32__, __HAVE_LONG_DOUBLE64__, __HAVE_LONG_DOUBLE_MULTILIB__, __DEFAULT_LONG_DOUBLE__ — same as above, but for long double instead of double 💫.
  • __WITH_DOUBLE_COMPARISON__ — reflects the --with-double-comparison={tristate|bool|libf7} configure option (https://gcc.gnu.org/install/configure.html#avr) and is defined to 2 or 3 👑.
  • __WITH_LIBF7_LIBGCC__, __WITH_LIBF7_MATH__, __WITH_LIBF7_MATH_SYMBOLS__ — reflects the --with-libf7={libgcc|math|math-symbols} configure option (https://gcc.gnu.org/install/configure.html#avr) 🌈.

🖤 Blackfin Options 🖤

  • -mcpu=cpu[-sirevision] — specifies the name of the target Blackfin processor, no cap 🫶. Currently, cpu can be one of bf512, bf514, bf516, bf518, bf522, bf523, bf524, bf525, bf526, bf527, bf531, bf532, bf533, bf534, bf536, bf537, bf538, bf539, bf542, bf544, bf547, bf548, bf549, bf542m, bf544m, bf547m, bf548m, bf549m, bf561, bf592.

The optional sirevision specifies the silicon revision of the target Blackfin processor. Any workarounds available for the targeted silicon revision are enabled. If sirevision is none, no workarounds are enabled. If sirevision is any, all workarounds for the targeted processor are enabled. The __SILICON_REVISION__ macro is defined to two hexadecimal digits representing the major and minor numbers in the silicon revision. If sirevision is none, the __SILICON_REVISION__ is not defined. If sirevision is any, the __SILICON_REVISION__ is defined to be 0xffff. If this optional sirevision is not used, GCC assumes the latest known silicon revision of the targeted Blackfin processor.

GCC defines a preprocessor macro for the specified cpu. For the bfin-elf toolchain, this option causes the hardware BSP provided by libgloss to be linked in if -msim is not given.

Without this option, bf532 is used as the processor by default.

Note that support for bf561 is incomplete. For bf561, only the preprocessor macro is defined 👀.

  • -msim — specifies that the program will be run on the simulator 🎮. This causes the simulator BSP provided by libgloss to be linked in. This option has effect only for bfin-elf toolchain. Certain other options, such as -mid-shared-library and -mfdpic, imply -msim.
  • -momit-leaf-frame-pointer — don't keep the frame pointer in a register for leaf functions 💅. This avoids the instructions to save, set up and restore frame pointers and makes an extra register available in leaf functions.
  • -mspecld-anomaly — when enabled, the compiler ensures that the generated code does not contain speculative loads after jump instructions 🔥. If this option is used, __WORKAROUND_SPECULATIVE_LOADS is defined.
  • -mno-specld-anomaly — don't generate extra code to prevent speculative loads from occurring.
  • -mcsync-anomaly — when enabled, the compiler ensures that the generated code does not contain CSYNC or SSYNC instructions too soon after conditional branches ⚡. If this option is used, __WORKAROUND_SPECULATIVE_SYNCS is defined.
  • -mno-csync-anomaly — don't generate extra code to prevent CSYNC or SSYNC instructions from occurring too soon after a conditional branch.
  • -mlow64k — when enabled, the compiler is free to take advantage of the knowledge that the entire program fits into the low 64k of memory ✨.
  • -mno-low64k — assume that the program is arbitrarily large. This is the default 💀.
  • -mstack-check-l1 — do stack checking using information placed into L1 scratchpad memory by the uClinux kernel 🧠.
  • -mid-shared-library — generate code that supports shared libraries via the library ID method 🫶. This allows for execute in place and shared libraries in an environment without virtual memory management. This option implies -fPIC. With a bfin-elf target, this option implies -msim.
  • -mno-id-shared-library — generate code that doesn't assume ID-based shared libraries are being used. This is the default.
  • -mleaf-id-shared-library — generate code that supports shared libraries via the library ID method, but assumes that this library or executable won't link against any other ID shared libraries 🌿. That allows the compiler to use faster code for jumps and calls.
  • -mno-leaf-id-shared-library — do not assume that the code being compiled won't link against any ID shared libraries. Slower code is generated for jump and call insns 😭.
  • -mshared-library-id=n — specifies the identification number of the ID-based shared library being compiled 🔢. Specifying a value of 0 generates more compact code; specifying other values forces the allocation of that number to the current library but is no more space- or time-efficient than omitting this option.
  • -msep-data — generate code that allows the data segment to be located in a different area of memory from the text segment 🌸. This allows for execute in place in an environment without virtual memory management by eliminating relocations against the text section.
  • -mno-sep-data — generate code that assumes that the data segment follows the text segment. This is the default.
  • -mlong-calls, -mno-long-calls — tells the compiler to perform function calls by first loading the address of the function into a register and then performing a subroutine call on this register 📞. This switch is needed if the target function lies outside of the 24-bit addressing range of the offset-based version of subroutine call instruction.

This feature is not enabled by default. Specifying -mno-long-calls restores the default behavior. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers.

  • -mfast-fp — link with the fast floating-point library ⚡. This library relaxes some of the IEEE floating-point standard's rules for checking inputs against Not-a-Number (NAN), in the interest of performance.
  • -minline-plt — enable inlining of PLT entries in function calls to functions that are not known to bind locally 🎀. It has no effect without -mfdpic.
  • -mmulticore — build a standalone application for multicore Blackfin processors 👑. This option causes proper start files and link scripts supporting multicore to be used, and defines the macro __BFIN_MULTICORE. It can only be used with -mcpu=bf561[-sirevision].

This option can be used with -mcorea or -mcoreb, which selects the one-application-per-core programming model. Without -mcorea or -mcoreb, the single-application/dual-core programming model is used. In this model, the main function of Core B should be named as coreb_main.

If this option is not used, the single-core application programming model is used.

  • -mcorea — build a standalone application for Core A of BF561 when using the one-application-per-core programming model 💖. Proper start files and link scripts are used to support Core A, and the macro __BFIN_COREA is defined. This option can only be used in conjunction with -mmulticore.
  • -mcoreb — build a standalone application for Core B of BF561 when using the one-application-per-core programming model 💜. Proper start files and link scripts are used to support Core B, and the macro __BFIN_COREB is defined. When this option is used, coreb_main should be used instead of main. This option can only be used in conjunction with -mmulticore.
  • -msdram — build a standalone application for SDRAM 🌈. Proper start files and link scripts are used to put the application into SDRAM, and the macro __BFIN_SDRAM is defined. The loader should initialize SDRAM before loading the application.
  • -micplb — assume ICPLBs are already enabled at runtime ✨ this matters for a few of those anomaly workarounds. On Linux targets the default is assume they're on; for standalone applications the default is off. iykyk 💅

🧁 C6X Options

  • -march=name — tells GCC the name of the target architecture. It literally uses this to decide what kind of instructions it's allowed to emit when it makes assembly 💖 the permissible names are: c62x, c64x, c64x+, c67x, c67x+, c674x.
  • -mbig-endian — generate code for a big-endian target 🫶
  • -mlittle-endian — generate code for a little-endian target. this one is the default, bestie ✨
  • -msim — pick startup files and linker script that are suitable for the simulator 🌸
  • -msdata=default — stash small global and static data in the .neardata section, which is pointed to by register B14 🎀 small uninitialized global and static data goes in .bss, which sits right next to .neardata. small read-only data goes in .rodata. the matching sections for chunky data are .fardata, .far and .const.
  • -msdata=all — put all the data in the small-data sections, not just the small objects, and access it via addressing relative to the B14 register 👑
  • -msdata=none — don't touch the small-data sections at all, and use absolute addresses to reach all data. all initialized global and static data goes in .fardata, all uninitialized data goes in .far, and all constant data goes in .const 💜

🌈 CRIS Options

these ones are defined specifically for the CRIS ports, no cap 🧚

  • -march=architecture-type
  • -mcpu=architecture-type — generate code for the specified architecture. the choices for architecture-type are v3, v8 and v10, for ETRAX 4, ETRAX 100, and ETRAX 100 LX respectively. default is v0 ⭐
  • -mtune=architecture-type — tune everything applicable about the generated code to architecture-type, except for the ABI and the set of available instructions 🔥 the choices for architecture-type are the same as for -march=architecture-type.
  • -mmax-stack-frame=n — warn whenever a function's stack frame exceeds n bytes 👀
  • -metrax4
  • -metrax100 — these two are synonyms for -march=v3 and -march=v8 respectively 🦋
  • -mmul-bug-workaround
  • -mno-mul-bug-workaround — work around a bug in the muls and mulu instructions for CPU models where it applies 💀 this option is disabled by default.
  • -mpdebug — turn on CRIS-specific verbose debug-related info in the assembly code. it also has the effect of turning off the #NO_APP formatted-code indicator to the assembler at the beginning of the assembly file 🙈
  • -mcc-init — do not use condition-code results from a previous instruction; always emit compare and test instructions before condition codes get used 💅
  • -mno-side-effects — do not emit instructions with side effects in addressing modes other than post-increment ✨
  • -mstack-align
  • -mno-stack-align
  • -mdata-align
  • -mno-data-align
  • -mconst-align
  • -mno-const-align — these options (and their no- versions) arrange (or eliminate the arrangement of) the stack frame, individual data and constants to be aligned for the maximum single data access size for the chosen CPU model 🎀 the default is to arrange for 32-bit alignment. ABI details such as structure layout are not affected by these options, periodt.
  • -m32-bit
  • -m16-bit
  • -m8-bit — similar to the stack-, data- and const-align options above, these arrange for the stack frame, writable data and constants to all be 32-bit, 16-bit or 8-bit aligned 💖 the default is 32-bit alignment.
  • -mno-prologue-epilogue
  • -mprologue-epilogue — with -mno-prologue-epilogue, the normal function prologue and epilogue that set up the stack frame get omitted, and no return instructions or return sequences are generated in the code 😭
ngl bestie, only use -mno-prologue-epilogue together with your own eyeballs on the compiled code: no warnings or errors are generated when call-saved registers must be saved, or when storage for local variables needs to be allocated. it will not tell you. 💀
  • -melf — legacy no-op option 🫠
  • -sim — arranges to link with input-output functions from a simulator library. code, initialized data and zero-initialized data are allocated consecutively 🌸
  • -sim2 — like -sim, but it passes linker options to locate initialized data at 0x40000000 and zero-initialized data at 0x80000000 ⭐

🍓 CR16 Options

defined specifically for the CR16 ports, iykyk 💜

  • -mmac — enable the use of multiply-accumulate instructions. disabled by default 🙈
  • -mcr16cplus
  • -mcr16c — generate code for the CR16C or CR16C+ architecture. CR16C+ is the default 🎀
  • -msim — links the library libsim.a, which is compatible with the simulator. applicable to the ELF compiler only ✨
  • -mint32 — choose integer type as 32-bit wide 💅
  • -mbit-ops — generates sbit/cbit instructions for bit manipulations 🌈
  • -mdata-model=model — choose a data model. the choices for model are near, far or medium, and medium is the default 👑 heads up though: far is not valid with -mcr16c, because the CR16C architecture does not support the far data model 💀

🦋 C-SKY Options

GCC has these options when compiling for C-SKY V2 processors 🧚

  • -march=arch — specify the C-SKY target architecture. valid values for arch are: ck801, ck802, ck803, ck807, and ck810. the default is ck810 ⭐
  • -mcpu=cpu — specify the C-SKY target processor. valid values for cpu are: ck801, ck801t, ck802, ck802t, ck802j, ck803, ck803h, ck803t, ck803ht, ck803f, ck803fh, ck803e, ck803eh, ck803et, ck803eht, ck803ef, ck803efh, ck803ft, ck803eft, ck803efht, ck803r1, ck803hr1, ck803tr1, ck803htr1, ck803fr1, ck803fhr1, ck803er1, ck803ehr1, ck803etr1, ck803ehtr1, ck803efr1, ck803efhr1, ck803ftr1, ck803eftr1, ck803efhtr1, ck803s, ck803st, ck803se, ck803sf, ck803sef, ck803seft, ck807e, ck807ef, ck807, ck807f, ck810e, ck810et, ck810ef, ck810eft, ck810, ck810v, ck810f, ck810t, ck810fv, ck810tv, ck810ft, and ck810ftv 💖 yes that's the whole list, don't come for me.
  • -mbig-endian
  • -EB
  • -mlittle-endian
  • -EL — select big- or little-endian code. the default is little-endian ✨
  • -mfloat-abi=name — specifies which floating-point ABI to use. permissible values are: soft, softfp and hard. 🎀

specifying soft makes GCC generate output that contains library calls for floating-point operations. softfp allows generation of code that uses hardware floating-point instructions, but it still uses the soft-float calling conventions. hard allows generation of floating-point instructions and uses FPU-specific calling conventions. 🫶

the default depends on the specific target configuration. and note: the hard-float and soft-float ABIs are not link-compatible 😭 you must compile your entire program with the same ABI, and link with a compatible set of libraries. no mixing, bestie.

  • -mhard-float
  • -msoft-float — select hardware or software floating-point implementations. the default is soft float 💜
  • -mdouble-float
  • -mno-double-float — when -mhard-float is in effect, enable generation of double-precision float instructions. this is the default except when compiling for CK803 🌸
  • -mfdivdu
  • -mno-fdivdu — when -mhard-float is in effect, enable generation of frecipd, fsqrtd, and fdivd instructions. this is the default except when compiling for CK803 ⭐
  • -mfpu=fpu — select the floating-point processor. this option can only be used with -mhard-float 🚨 values for fpu are fpv2_sf (equivalent to -mno-double-float -mno-fdivdu), fpv2 (-mdouble-float -mno-divdu), and fpv2_divd (-mdouble-float -mdivdu) 💅
  • -melrw
  • -mno-elrw — enable the extended lrw instruction. this option defaults to on for CK801 and off otherwise ✨
  • -mistack
  • -mno-istack — enable interrupt stack instructions; the default is off. the -mistack option is required to handle the interrupt and isr function attributes 👑
  • -mmp — enable multiprocessor instructions; the default is off 🎀
  • -mcp — enable coprocessor instructions; the default is off 🦋
  • -mcache — enable coprocessor instructions; the default is off (yes, it says coprocessor — that's what the original says, don't @ me) 💀
  • -msecurity — enable C-SKY security instructions; the default is off 🔥
  • -mtrust — enable C-SKY trust instructions; the default is off 🌈
  • -mdsp
  • -medsp
  • -mvdsp — enable C-SKY DSP, Enhanced DSP, or Vector DSP instructions, respectively. all of these default to off 💜
  • -mdiv
  • -mno-div — generate divide instructions. default is off 🙈
  • -msmart
  • -mno-smart — generate code for Smart Mode, using only registers numbered 0-7 so that 16-bit instructions can be used. this option is ignored for CK801, where this is the required behavior, and it defaults to on for CK802. for other targets, the default is off ✨
  • -mhigh-registers
  • -mno-high-registers — generate code using the high registers numbered 16-31. this option is not supported on CK801, CK802, or CK803, and it's enabled by default for other processors ⭐
  • -manchor
  • -mno-anchor — generate code using global anchor symbol addresses 🎀
  • -mpushpop
  • -mno-pushpop — generate code using push and pop instructions. this option defaults to on 💖
  • -mmultiple-stld
  • -mstm
  • -mno-multiple-stld
  • -mno-stm — generate code using stm and ldm instructions. this option isn't supported on CK801 but is enabled by default on other processors 🌸
  • -mconstpool
  • -mno-constpool — create constant pools in the compiler instead of deferring it to the assembler. this option is the default, and it's required for correct code generation on CK801 and CK802, and it's optional on other processors 👑
  • -mstack-size
  • -mno-stack-size — emit .stack_size directives for each function in the assembly output. this option defaults to off 🫠
  • -mccrt
  • -mno-ccrt — generate code for the C-SKY compiler runtime instead of libgcc. this option defaults to off 🦋
  • -mbranch-cost=n — set the branch costs to roughly n instructions. the default is 1 ✨
  • -msched-prolog, -mno-sched-prolog — lets the compiler schedule the function prologue and epilogue sequences. But bestie, heads up: turning this on can give you code that does not comply with the C-SKY V2 ABI prologue requirements, and you literally can't debug or backtrace it 😭. It's disabled by default, so you're fine unless you go looking for chaos.
  • -msim — links in the library libsemi.a, which is compatible with the simulator. Only applicable to the ELF compiler, iykyk.

🍎 Darwin Options

These ones are defined for all architectures running the Darwin operating system.

Okay so first, the lore: FSF GCC on Darwin does not create "fat" object files — it creates an object file for the single architecture that GCC was built to target. Apple's GCC on Darwin does create "fat" files if multiple -arch options are used, and it pulls that off by running the compiler or linker multiple times and gluing the results together with lipo. Slay, honestly 💅.

The subtype of the file created (like ppc7400 or ppc970 or i686) is determined by the flags that specify the ISA that GCC is targeting, like -mcpu or -march. And if you wanna override that whole situation, the -force_cpusubtype_ALL option exists for exactly that.

Now the Darwin tools all have opinions when they hit an ISA mismatch, and they do not agree with each other:

  • The assembler, as, only permits instructions that are valid for the subtype of the file it's generating — so you literally cannot put 64-bit instructions in a ppc750 object file. No cap.
  • The linker for shared libraries, /usr/bin/libtool, fails and prints an error if you ask it to create a shared library with a less restrictive subtype than its input files (like, trying to put a ppc970 object file in a ppc7400 library? absolutely not).
  • The linker for executables, ld, quietly gives the executable the most restrictive subtype of any of its input files. Silent king behavior 👑.

  • -Fdir — adds the framework directory dir to the head of the list of directories searched for header files. These directories get interleaved with the ones you specify with -I options, and they're scanned in a left-to-right order.

Let me break down what a framework directory even is, because the terminology is giving ✨nested✨: a framework directory is a directory with frameworks in it. A framework is a directory with a Headers and/or PrivateHeaders directory contained directly in it, that ends in .framework. The name of a framework is the name of this directory excluding the .framework. Headers associated with the framework are found in one of those two directories, with Headers being searched first.

A subframework is a framework directory that's inside a framework's Frameworks directory. Includes of subframework headers can only appear in a header of a framework that contains the subframework, or in a sibling subframework header. Two subframeworks are siblings if they occur in the same framework. A subframework should not have the same name as a framework — a warning gets issued if you violate this. And currently a subframework cannot have subframeworks; in the future the mechanism may be extended to support this. The standard frameworks live in /System/Library/Frameworks and /Library/Frameworks.

An example include looks like:

#include <Framework/header.h>

where Framework denotes the name of the framework and header.h is found in the PrivateHeaders or Headers directory. Obsessed with how tidy that is 🎀.

  • -iframeworkdir — like -F, except the directory is treated as a system directory. The main difference between this -iframework and -F is that with -iframework the compiler does not warn about constructs contained within header files found via dir. This option is valid only for the C family of languages.
  • -gused — emits debugging information for symbols that are used. For the stabs debugging format, this enables -feliminate-unused-debug-symbols. This is by default ON.
  • -gfull — emits debugging information for all symbols and types. All of them. Every last one 🫶.
  • -mmacosx-version-min=version — the earliest version of MacOS X that this executable will run on is version. Typical values of version include 10.1, 10.2, and 10.3.9.

If the compiler was built to use the system's headers by default, then the default for this option is the system version on which the compiler is running; otherwise the default is to make choices that are compatible with as many systems and code bases as possible. Adaptable icon 💜.

  • -mkernel — enables kernel development mode, main character energy. The -mkernel option sets -static, -fno-common, -fno-use-cxa-atexit, -fno-exceptions, -fno-non-call-exceptions, -fapple-kext, -fno-weak and -fno-rtti where applicable. This mode also sets -mno-altivec, -msoft-float, -fno-builtin and -mlong-branch for PowerPC targets.
  • -mone-byte-bool — overrides the defaults for "bool" so that "sizeof(bool)==1". By default sizeof(bool) is 4 when compiling for Darwin/PowerPC and 1 when compiling for Darwin/x86, so this option has no effect on x86.
Warning: the -mone-byte-bool switch causes GCC to generate code that is not binary compatible with code generated without that switch. Using this switch may require recompiling all other modules in a program, including system libraries 😭. Use this switch to conform to a non-default data model.
  • -mfix-and-continue, -ffix-and-continue, -findirect-data — generate code suitable for fast turnaround development, such as allowing GDB to dynamically load .o files into already-running programs. -findirect-data and -ffix-and-continue are provided for backwards compatibility.
  • -all_load — loads all members of static archive libraries. See man ld(1) for more information.
  • -arch_errors_fatal — causes the errors having to do with files that have the wrong architecture to be fatal.
  • -bind_at_load — causes the output file to be marked such that the dynamic linker will bind all undefined references when the file is loaded or launched.
  • -bundle — produces a Mach-o bundle format file. See man ld(1) for more information.
  • -bundle_loader executable — this option specifies the executable that will load the build output file being linked. See man ld(1) for more information.
  • -dynamiclib — when passed this option, GCC produces a dynamic library instead of an executable when linking, using the Darwin libtool command.
  • -force_cpusubtype_ALL — causes GCC's output file to have the ALL subtype, instead of one controlled by the -mcpu or -march option.

And then there's this whole pile of options that just get passed straight through to the Darwin linker, and the Darwin linker man page describes them in detail 👇

-allowable_client  client_name
-client_name
-compatibility_version
-current_version
-dead_strip
-dependency-file
-dylib_file
-dylinker_install_name
-dynamic
-exported_symbols_list
-filelist
-flat_namespace
-force_flat_namespace
-headerpad_max_install_names
-image_base
-init
-install_name
-keep_private_externs
-multi_module
-multiply_defined
-multiply_defined_unused
-noall_load
-no_dead_strip_inits_and_terms
-nofixprebinding
-nomultidefs
-noprebind
-noseglinkedit
-pagezero_size
-prebind
-prebind_all_twolevel_modules
-private_bundle
-read_only_relocs
-sectalign
-sectobjectsymbols
-whyload
-seg1addr
-sectcreate
-sectobjectsymbols
-sectorder
-segaddr
-segs_read_only_addr
-segs_read_write_addr
-seg_addr_table
-seg_addr_table_filename
-seglinkedit
-segprot
-segs_read_only_addr
-segs_read_write_addr
-single_module
-static
-sub_library
-sub_umbrella
-twolevel_namespace
-umbrella
-undefined
-unexported_symbols_list
-weak_reference_mismatches
-whatsloaded

Yes, -sectobjectsymbols and -segs_read_only_addr and -segs_read_write_addr really do show up twice in that list. That's not me being messy, that's the source, fr fr 💀.


💠 DEC Alpha Options

These -m options are defined for the DEC Alpha implementations. Retro, but make it iconic 🦋.

  • -mno-soft-float, -msoft-float — use (do not use) the hardware floating-point instructions for floating-point operations. When -msoft-float is specified, functions in libgcc.a are used to perform floating-point operations. Unless they're replaced by routines that emulate the floating-point operations, or compiled in such a way as to call such emulation routines, these routines issue floating-point operations. So if you're compiling for an Alpha without floating-point operations, you must ensure that the library is built so as not to call them.

Also note: Alpha implementations without floating-point operations are required to have floating-point registers. Yeah. That's just how it is 🙈.

  • -mfp-reg, -mno-fp-regs — generate code that uses (does not use) the floating-point register set. -mno-fp-regs implies -msoft-float. If the floating-point register set isn't used, floating-point operands are passed in integer registers as if they were integers, and floating-point results are passed in $0 instead of $f0. This is a non-standard calling sequence, so any function with a floating-point argument or return value called by code compiled with -mno-fp-regs must also be compiled with that option. Keep the vibes consistent or it all falls apart 😤.

A typical use of this option is building a kernel that doesn't use — and hence need not save and restore — any floating-point registers.

  • -mieee — okay so the Alpha architecture implements floating-point hardware optimized for maximum performance, and it's mostly compliant with the IEEE floating-point standard. But for full compliance, software assistance is required. This option generates fully IEEE-compliant code except that the inexact-flag is not maintained (see below). If this option is turned on, the preprocessor macro _IEEE_FP is defined during compilation. The resulting code is less efficient but is able to correctly support denormalized numbers and exceptional IEEE values such as not-a-number and plus/minus infinity. Other Alpha compilers call this option -ieee_with_no_inexact.
  • -mieee-with-inexact — like -mieee, except the generated code also maintains the IEEE inexact-flag. Turning on this option causes the generated code to implement fully-compliant IEEE math. In addition to _IEEE_FP, _IEEE_FP_EXACT is defined as a preprocessor macro. On some Alpha implementations the resulting code may execute significantly slower than the code generated by default. Since there is very little code that depends on the inexact-flag, you should normally not specify this option. Other Alpha compilers call this option -ieee_with_inexact.
  • -mfp-trap-mode=trap-mode — this option controls what floating-point related traps are enabled. Other Alpha compilers call this option -fptm trap-mode. The trap mode can be set to one of four values:
  • n — bestie this is the default (normal) setting 💅 the only traps that get enabled are the ones that literally cannot be disabled in software (think division by zero trap, yeah that one).
    • u — everything n gives you, plus underflow traps are enabled too ✨
    • su — like u, but the instructions get marked as safe for software completion (go read the Alpha architecture manual for the deets, iykyk).
    • sui — like su, but inexact traps are enabled as well 🎀
  • -mfp-rounding-mode= rounding-mode — picks the IEEE rounding mode. Other Alpha compilers call this thing -fprm rounding-mode. The rounding-mode can be one of:
    • n — normal IEEE rounding mode, no notes. Floating-point numbers get rounded towards the nearest machine number, or towards the even machine number when it's a tie 🫶
    • m — round towards minus infinity.
    • c — chopped rounding mode. Floating-point numbers get rounded towards zero ✂️
    • d — dynamic rounding mode. A field in the floating-point control register (fpcr, see the Alpha architecture reference manual) controls which rounding mode is actually in effect. The C library initializes this register for rounding towards plus infinity. So unless your program goes and modifies the fpcr, d corresponds to round towards plus infinity 💫
  • -mtrap-precision= trap-precision — okay so in the Alpha architecture, floating-point traps are imprecise 😭 which means without some software assistance it is impossible to recover from a floating trap, and program execution normally needs to be terminated. GCC can generate code that helps operating system trap handlers figure out the exact location that caused a floating-point trap. Depending on what your app needs, you pick different levels of precision:
    • p — program precision. This one is the default and it means a trap handler can only identify which program caused a floating-point exception.
    • f — function precision. The trap handler can determine which function caused a floating-point exception.
    • i — instruction precision. The trap handler can determine the exact instruction that caused a floating-point exception 🔥

Other Alpha compilers ship the equivalent options, and they're called -scope_safe and -resumption_safe.

  • -mieee-conformant — this marks the generated code as IEEE conformant 🎀 but listen: you must not use this option unless you also specify -mtrap-precision=i and either -mfp-trap-mode=su or -mfp-trap-mode=sui. Its only effect is to emit the line .eflag 48 in the function prologue of the generated assembly file. That's it, that's the whole vibe.
  • -mbuild-constants — normally GCC peeks at a 32- or 64-bit integer constant to see if it can construct it from smaller constants in two or three instructions. If it can't, it outputs the constant as a literal and generates code to load it from the data segment at run time. Use this option to force GCC to construct all integer constants using code, even if it takes more instructions (the max is six). You typically use this one to build a shared library dynamic loader 💖 itself a shared library, it has to relocate itself in memory before it can find the variables and constants in its own data segment. Main character energy honestly.
  • -mbwx
  • -mno-bwx
  • -mcix
  • -mno-cix
  • -mfix
  • -mno-fix
  • -mmax
  • -mno-max — these tell GCC whether it should generate code that uses the optional BWX, CIX, FIX and MAX instruction sets 🌈 the default is to use whichever instruction sets are supported by the CPU type you specified via the -mcpu= option, or by the CPU GCC was built on if you specified none.
  • -mfloat-vax
  • -mfloat-ieee — generate code that uses (or doesn't use) VAX F and G floating-point arithmetic instead of IEEE single and double precision 💅
  • -mexplicit-relocs
  • -mno-explicit-relocs — older Alpha assemblers gave you no way to generate symbol relocations except through assembler macros, and those macros do not allow optimal instruction scheduling 😤 GNU binutils as of version 2.12 supports a new syntax that lets the compiler explicitly mark which relocations should apply to which instructions. This option is mostly useful for debugging, since GCC detects the assembler's capabilities when it is built and sets the default accordingly.
  • -msmall-data
  • -mlarge-data — when -mexplicit-relocs is in effect, static data gets accessed via gp-relative relocations. With -msmall-data, objects 8 bytes long or smaller are placed in a small data area (the .sdata and .sbss sections) and are accessed via 16-bit relocations off of the $gp register 🦋 this limits the small data area to 64KB, but it means the variables get directly accessed via a single instruction. Slay.

The default is -mlarge-data. With that option the data area is limited to just below 2GB. Programs that need more than 2GB of data must use malloc or mmap to allocate the data in the heap instead of in the program's data segment.

When generating code for shared libraries, -fpic implies -msmall-data and -fPIC implies -mlarge-data.

  • -msmall-text
  • -mlarge-text — with -msmall-text, the compiler assumes the code of the entire program (or shared library) fits in 4MB, and is therefore reachable with a branch instruction. When -msmall-data is used, the compiler can assume all local symbols share the same $gp value, and that shrinks the number of instructions needed for a function call from 4 down to 1 👑

The default is -mlarge-text.

  • -mcpu= cpu_type — sets the instruction set and instruction scheduling parameters for machine type cpu_type. You can give either the EV style name or the corresponding chip number. GCC supports scheduling parameters for the EV4, EV5 and EV6 family of processors and chooses the default values for the instruction set from the processor you specify. If you don't specify a processor type, GCC defaults to the processor on which the compiler was built.

Supported values for cpu_type are

  • ev4
  • ev45
  • 21064 — schedules as an EV4 and has no instruction set extensions.
  • ev5
  • 21164 — schedules as an EV5 and has no instruction set extensions.
  • ev56
  • 21164a — schedules as an EV5 and supports the BWX extension.
  • pca56
  • 21164pc
  • 21164PC — schedules as an EV5 and supports the BWX and MAX extensions.
  • ev6
  • 21264 — schedules as an EV6 and supports the BWX, FIX, and MAX extensions.
  • ev67
  • 21264a — schedules as an EV6 and supports the BWX, CIX, FIX, and MAX extensions 🚀

Native toolchains also support the value native, which selects the best architecture option for the host processor. -mcpu=native has no effect if GCC does not recognize the processor 🙈

  • -mtune= cpu_type — sets only the instruction scheduling parameters for machine type cpu_type. The instruction set is not changed, bestie.

Native toolchains also support the value native, which selects the best architecture option for the host processor. -mtune=native has no effect if GCC does not recognize the processor.

  • -mmemory-latency= time — sets the latency the scheduler should assume for typical memory references as seen by the application. This number is highly dependent on the memory access patterns your application uses and the size of the external cache on the machine 🧚

Valid options for time are

  • number — a decimal number representing clock cycles.
  • L1
  • L2
  • L3
  • main — the compiler contains estimates of the number of clock cycles for "typical" EV4 & EV5 hardware for the Level 1, 2 & 3 caches (also called Dcache, Scache, and Bcache), as well as to main memory. Note that L3 is only valid for EV5 💜

🧚 eBPF Options ✨

  • -mframe-limit= bytes — specifies the hard limit for frame sizes, in bytes. Currently the value you can specify should be less than or equal to 32767. Defaults to whatever limit is imposed by the version of the Linux kernel you're targeting 🎀
  • -mkernel= version — specifies the minimum version of the kernel that will run the compiled program. GCC uses this version to decide which instructions to use, what kernel helpers to allow, etc. Currently version can be one of 4.0, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 4.10, 4.11, 4.12, 4.13, 4.14, 4.15, 4.16, 4.17, 4.18, 4.19, 4.20, 5.0, 5.1, 5.2, latest and native 🦋
  • -mbig-endian — generate code for a big-endian target.
  • -mlittle-endian — generate code for a little-endian target. This is the default 💅
  • -mjmpext — enable generation of extra conditional-branch instructions. Enabled for CPU v2 and above.
  • -mjmp32 — enable 32-bit jump instructions. Enabled for CPU v3 and above.
  • -malu32 — enable 32-bit ALU instructions. Enabled for CPU v3 and above.
  • -mcpu= version — specifies which version of the eBPF ISA to target. Newer versions may not be supported by all kernels. The default is v3 🔥

Supported values for version are:

  • v1 — the first stable eBPF ISA with no special features or extensions.
  • v2 — supports the jump extensions, as in -mjmpext.
  • v3 — all features of v2, plus:
    • 32-bit jump operations, as in -mjmp32
    • 32-bit ALU operations, as in -malu32
  • -mco-re — enable BPF Compile Once - Run Everywhere (CO-RE) support 👑 requires -gbtf and is implied by -gbtf.
  • -mno-co-re — disable BPF Compile Once - Run Everywhere (CO-RE) support. BPF CO-RE support is enabled by default when generating BTF debug information for the BPF target.
  • -mxbpf — generate code for an expanded version of BPF, which relaxes some of the restrictions imposed by the BPF architecture 💖
    • Save and restore callee-saved registers at function entry and exit, respectively.

🌸 FR30 Options 🎀

These options are defined specifically for the FR30 port, no cap.

  • -msmall-model — use the small address space model. This can produce smaller code, but it does assume that all symbolic values and addresses fit into a 20-bit range 👀
  • -mno-lsim — assume that runtime support has been provided, so there's no need to include the simulator library (libsim.a) on the linker command line.

⭐ FT32 Options 🌈

  • -msim — okay so this one says your program is gonna run on the simulator, so it links up an alternate runtime startup and an alternate library. 🧚 And bestie, listen: you literally must not use this when you're generating programs that are gonna run on real hardware. No cap. If you're going bare-metal, you gotta supply your own runtime library for whatever I/O functions you need. 💅
  • -mlra — turns on Local Register Allocation. It's still experimental for FT32, so by default the compiler just uses standard reload. Lowkey not the moment to be brave. 🙈
  • -mnodiv — do not use div and mod instructions. Simple as that. ✨
  • -mft32b — lets you use the extended instructions of the FT32B processor. Fancy chip energy. 🔥
  • -mcompress — compresses all code using the Ft32B code compression scheme. Tiny code, iconic. 🎀
  • -mnopm — do not generate code that reads program memory. Periodt.

🦋 FRV Options 🦋

  • -mgpr-32 — only use the first 32 general-purpose registers. Rationing, but make it fashion.
  • -mgpr-64 — use all 64 general-purpose registers. Go off, king. 👑
  • -mfpr-32 — use only the first 32 floating-point registers.
  • -mfpr-64 — use all 64 floating-point registers.
  • -mhard-float — use hardware instructions for floating-point operations. The real deal. 💅
  • -msoft-float — use library routines for floating-point operations instead. Softer, slower, still valid.
  • -malloc-cc — dynamically allocate condition code registers.
  • -mfixed-cc — do not try to dynamically allocate condition code registers; only use "icc0" and "fcc0". Set in your ways, honestly relatable.
  • -mdword — change the ABI to use double word insns.
  • -mno-dword — do not use double word instructions.
  • -mdouble — use floating-point double instructions.
  • -mno-double — do not use floating-point double instructions.
  • -mmedia — use media instructions.
  • -mno-media — do not use media instructions.
  • -mmuladd — use multiply and add/subtract instructions.
  • -mno-muladd — do not use multiply and add/subtract instructions.
  • -mfdpic — selects the FDPIC ABI, which uses function descriptors to represent pointers to functions. 🫶 Without any PIC/PIE-related options, it implies -fPIE. With -fpic or -fpie, it assumes GOT entries and small data are within a 12-bit range from the GOT base address; with -fPIC or -fPIE, GOT offsets are computed with 32 bits. And with a bfin-elf target, this option implies -msim.
  • -minline-plt — enables inlining of PLT entries in function calls to functions that are not known to bind locally. Ngl it has no effect without -mfdpic. It's enabled by default if you're optimizing for speed and compiling for shared libraries (i.e., -fPIC or -fpic), or when an optimization option such as -O3 or above is present in the command line. ✨
  • -mTLS — assume a large TLS segment when generating thread-local code.
  • -mtls — do not assume a large TLS segment when generating thread-local code.
  • -mgprel-ro — enables the use of "GPREL" relocations in the FDPIC ABI for data that is known to be in read-only sections. It's enabled by default, except for -fpic or -fpie: even though it may help make the global offset table smaller, it trades 1 instruction for 4. 😭 With -fPIC or -fPIE, it trades 3 instructions for 4, one of which may be shared by multiple symbols, and it avoids the need for a GOT entry for the referenced symbol, so it's more likely to be a win. If it is not, -mno-gprel-ro can be used to disable it. See, it's giving nuance.
  • -multilib-library-pic — link with the (library, not FD) pic libraries. It's implied by -mlibrary-pic, as well as by -fPIC and -fpic without -mfdpic. You should never have to use it explicitly. Like, never ever. 💀
  • -mlinked-fp — follows the EABI requirement of always creating a frame pointer whenever a stack frame is allocated. This option is enabled by default and can be disabled with -mno-linked-fp.
  • -mlong-calls — uses indirect addressing to call functions outside the current compilation unit. This lets the functions be placed anywhere within the 32-bit address space. Roam free, bestie. 🌈
  • -malign-labels — tries to align labels to an 8-byte boundary by inserting NOPs into the previous packet. This one only has an effect when VLIW packing is enabled. It doesn't create new packets; it merely adds NOPs to existing ones. Very "reuse, recycle" of it. 🎀
  • -mlibrary-pic — generate position-independent EABI code.
  • -macc-4 — use only the first four media accumulator registers.
  • -macc-8 — use all eight media accumulator registers.
  • -mpack — pack VLIW instructions.
  • -mno-pack — do not pack VLIW instructions.
  • -mno-eflags — do not mark ABI switches in e_flags.
  • -mcond-move — enables the use of conditional-move instructions (default). ⭐ This switch is mainly for debugging the compiler and will likely be removed in a future version. We love a temporary icon.
  • -mno-cond-move — disables the use of conditional-move instructions. This switch is mainly for debugging the compiler and will likely be removed in a future version. Same energy, opposite direction.
  • -mscc — enables the use of conditional set instructions (default). This switch is mainly for debugging the compiler and will likely be removed in a future version.
  • -mno-scc — disables the use of conditional set instructions. This switch is mainly for debugging the compiler and will likely be removed in a future version.
  • -mcond-exec — enables the use of conditional execution (default). This switch is mainly for debugging the compiler and will likely be removed in a future version.
  • -mno-cond-exec — disables the use of conditional execution. This switch is mainly for debugging the compiler and will likely be removed in a future version.
  • -mvliw-branch — runs a pass to pack branches into VLIW instructions (default). This switch is mainly for debugging the compiler and will likely be removed in a future version. 🦋
  • -mno-vliw-branch — do not run a pass to pack branches into VLIW instructions. This switch is mainly for debugging the compiler and will likely be removed in a future version.
  • -mmulti-cond-exec — enables optimization of "&&" and "||" in conditional execution (default). This switch is mainly for debugging the compiler and will likely be removed in a future version.
  • -mno-multi-cond-exec — disables optimization of "&&" and "||" in conditional execution. This switch is mainly for debugging the compiler and will likely be removed in a future version.
  • -mnested-cond-exec — enables nested conditional execution optimizations (default). This switch is mainly for debugging the compiler and will likely be removed in a future version. 💜
  • -mno-nested-cond-exec — disables nested conditional execution optimizations. This switch is mainly for debugging the compiler and will likely be removed in a future version.
  • -moptimize-membar — this switch removes redundant "membar" instructions from the compiler-generated code. It is enabled by default. Cleanup queen. 🧹
  • -mno-optimize-membar — this switch disables the automatic removal of redundant "membar" instructions from the generated code.
  • -mtomcat-stats — causes gas to print out tomcat statistics. Numbers! Stats! 🍓
  • -mcpu=cpu — selects the processor type for which to generate code. Possible values are frv, fr550, tomcat, fr500, fr450, fr405, fr400, fr300 and simple.

🌸 GNU/Linux Options 🌸

These -m options are defined for GNU/Linux targets:

  • -mglibc — use the GNU C library. This is the default except on *-*-linux-*uclibc*, *-*-linux-*musl* and *-*-linux-*android* targets.
  • -muclibc — use uClibc C library. This is the default on *-*-linux-*uclibc* targets.
  • -mmusl — use the musl C library. This is the default on *-*-linux-*musl* targets.
  • -mbionic — use Bionic C library. This is the default on *-*-linux-*android* targets.
  • -mandroid — compile code compatible with the Android platform. This is the default on *-*-linux-*android* targets. ✨ When compiling, this option enables -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default. When linking, this option makes the GCC driver pass Android-specific options to the linker. Finally, this option causes the preprocessor macro "__ANDROID__" to be defined. It's giving main character energy on Android fr fr.
  • -tno-android-cc — disables compilation effects of -mandroid, i.e., do not enable -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default.
  • -tno-android-ld — disables linking effects of -mandroid, i.e., pass standard Linux linking options to the linker.

🎀 H8/300 Options 🎀

These -m options are defined for the H8/300 implementations:

  • -mrelax — shortens some address references at link time, when possible; uses the linker option -relax.
  • -mh — generate code for the H8/300H.
  • -ms — generate code for the H8S.
  • -mn — generate code for the H8S and H8/300H in the normal mode. This switch must be used either with -mh or -ms. No solo runs, bestie. 💅
  • -ms2600 — generate code for the H8S/2600. This switch must be used with -ms.
  • -mexr — extended registers are stored on stack before execution of function with monitor attribute. Default option is -mexr. This option is valid only for H8S targets.
  • -mno-exr — extended registers are not stored on stack before execution of function with monitor attribute. Default option is -mno-exr. This option is valid only for H8S targets.
  • -mint32 — make "int" data 32 bits by default.
  • -malign-300 — on the H8/300H and H8S, use the same alignment rules as for the H8/300. The default for the H8/300H and H8S is to align longs and floats on 4-byte boundaries. -malign-300 causes them to be aligned on 2-byte boundaries. This option has no effect on the H8/300. Alignments are a whole vibe, honestly. 🦋

👑 HPPA Options 👑

These -m options are defined for the HPPA family of computers:

  • -march=architecture-type — generate code for the specified architecture. The choices for architecture-type are 1.0 for PA 1.0, 1.1 for PA 1.1, and 2.0 for PA 2.0 processors. Refer to /usr/lib/sched.models on an HP-UX system to determine the proper architecture option for your machine. 🔍 Code compiled for lower numbered architectures runs on higher numbered architectures, but not the other way around. So it's one-way slay, no cap.
  • -mpa-risc-1-0
  • -mpa-risc-1-1
  • -mpa-risc-2-0 — synonyms for -march=1.0, -march=1.1, and -march=2.0 respectively. Three nicknames for the same icon. ✨
  • -mcaller-copies — makes the caller do the copying of function arguments that get passed by hidden reference. Use this one with care, bestie — it does not play nice with the default 32-bit runtime. The good news? Only aggregates bigger than eight bytes get passed by hidden reference, and this option gives you better OpenMP compatibility. 💅
  • -mjump-in-delay — literally ignored. It's just vibing here for compatibility purposes only. 🫠
  • -mdisable-fpregs — floating-point registers are hereby banned from being used in any manner. This is necessary for compiling kernels that do lazy context switching of floating-point registers. But heads up: if you use this option and then try to do floating-point operations, the compiler aborts. 💀
  • -mdisable-indexing — stops the compiler from using indexing address modes, which avoids some rather obscure problems when compiling MIG generated code under MACH. iykyk. 🌀
  • -mno-space-regs — generates code that assumes the target has no space registers. This lets GCC generate faster indirect calls and use unscaled index address modes.

Such code is suitable for level 0 PA systems and kernels. ✨

  • -mfast-indirect-calls — generates code that assumes calls never cross space boundaries, which lets GCC emit code that performs faster indirect calls.
Fr fr: this option does not work in the presence of shared libraries or nested functions. 😭
  • -mfixed-range= register-range — generates code treating the given register range as fixed registers. A fixed register is one the register allocator cannot use, which is useful when compiling kernel code. A register range is specified as two registers separated by a dash. Multiple register ranges can be specified separated by a comma. 🎀
  • -mlong-load-store — generates 3-instruction load and store sequences, as sometimes required by the HP-UX 10 linker. Equivalent to the +k option to the HP compilers. 🧚
  • -mportable-runtime — uses the portable calling conventions proposed by HP for ELF systems.
  • -mgas — enables the use of assembler directives only GAS understands. ⭐
  • -mschedule= cpu-type — schedules code according to the constraints for the machine type cpu-type. The choices for cpu-type are 700, 7100, 7100LC, 7200, 7300 and 8000. Peep /usr/lib/sched.models on an HP-UX system to figure out the proper scheduling option for your machine. Default scheduling is 8000. 👑
  • -mlinker-opt — enables the optimization pass in the HP-UX linker. Note: this makes symbolic debugging impossible. It also triggers a bug in the HP-UX 8 and HP-UX 9 linkers where they give bogus error messages when linking some programs. 💀
  • -msoft-float — generates output containing library calls for floating point.
Warning: the requisite libraries are not available for all HPPA targets. Normally the facilities of the machine's usual C compiler are used, but this cannot be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation. 🙈

-msoft-float changes the calling convention in the output file, so it's only useful if you compile all of a program with this option. In particular, you need to compile libgcc.a — the library that comes with GCC — with -msoft-float for this to work. 🌸

  • -msio — generates the predefine _SIO for server IO. The default is -mwsio, which generates the predefines __hp9000s700, __hp9000s700__ and _WSIO for workstation IO. These options are available under HP-UX and HI-UX. 💜
  • -mgnu-ld — uses options specific to GNU ld. This passes -shared to ld when building a shared library. It's the default when GCC is configured — explicitly or implicitly — with the GNU linker. This option does not affect which ld is called; it only changes what parameters get passed to that ld. Which ld gets called is determined by the --with-ld configure option, GCC's program search path, and finally by the user's PATH. The linker used by GCC can be printed using which gcc -print-prog-name=ld. This option is only available on the 64-bit HP-UX GCC, i.e. configured with hppa*64*-*-hpux*. 🎯
  • -mhp-ld — uses options specific to HP ld. This passes -b to ld when building a shared library and passes +Accept TypeMismatch to ld on all links. It's the default when GCC is configured — explicitly or implicitly — with the HP linker. This option does not affect which ld is called; it only changes what parameters get passed to that ld. Which ld gets called is determined by the --with-ld configure option, GCC's program search path, and finally by the user's PATH. The linker used by GCC can be printed using which gcc -print-prog-name=ld. This option is only available on the 64-bit HP-UX GCC, i.e. configured with hppa*64*-*-hpux*. 🎯
  • -mlong-calls — generates code that uses long call sequences, so a call is always able to reach linker generated stubs. The default is to generate long calls only when the distance from the call site to the beginning of the function or translation unit (as the case may be) exceeds a predefined limit set by the branch type being used. The limits for normal calls are 7,600,000 and 240,000 bytes, respectively for the PA 2.0 and PA 1.X architectures. Sibcalls are always limited at 240,000 bytes. 📏

Distances are measured from the beginning of functions when using the -ffunction-sections option, or when using the -mgas and -mno-portable-runtime options together under HP-UX with the SOM linker.

It's normally not desirable to use this option since it degrades performance. But it may be useful in large applications — particularly when partial linking is used to build the application.

The types of long calls used depend on the capabilities of the assembler and linker, and the type of code being generated. The impact on systems that support long absolute calls, and long pic symbol-difference or pc-relative calls, should be relatively small. However, an indirect call is used on 32-bit ELF systems in pic code, and it is quite long. 😮‍💨

  • -munix= unix-std — generates compiler predefines and selects a startfile for the specified UNIX standard. The choices for unix-std are 93, 95 and 98. 93 is supported on all HP-UX versions. 95 is available on HP-UX 10.10 and later. 98 is available on HP-UX 11.11 and later. The default values are 93 for HP-UX 10.00, 95 for HP-UX 10.10 through to 11.00, and 98 for HP-UX 11.11 and later. 🗓️

-munix=93 provides the same predefines as GCC 3.3 and 3.4. -munix=95 provides additional predefines for XOPEN_UNIX and _XOPEN_SOURCE_EXTENDED, and the startfile unix95.o. -munix=98 provides additional predefines for _XOPEN_UNIX, _XOPEN_SOURCE_EXTENDED, _INCLUDE__STDC_A1_SOURCE and _INCLUDE_XOPEN_SOURCE_500, and the startfile unix98.o.

Important, bestie: this option changes the interfaces for various library routines. It also affects the operational behavior of the C library. So extreme care is needed when using it. 😬

Library code intended to operate with more than one UNIX standard must test, set and restore the variable __xpg4_extended_mask as appropriate. Most GNU software doesn't provide this capability. 💔

  • -nolibdld — suppresses the generation of link options to search libdld.sl when the -static option is specified on HP-UX 10 and later. 🚫
  • -static — so here's the tea: the HP-UX implementation of setlocale in libc has a dependency on libdld.sl, and there isn't an archive version of libdld.sl. Thus, when the -static option is specified, special link options are needed to resolve this dependency. ☕

On HP-UX 10 and later, the GCC driver adds the necessary options to link with libdld.sl when the -static option is specified. This causes the resulting binary to be dynamic. On the 64-bit port, the linkers generate dynamic binaries by default in any case. The -nolibdld option can be used to prevent the GCC driver from adding these link options. 🌀

  • -threads — adds support for multithreading with the dce thread library under HP-UX. This option sets flags for both the preprocessor and linker. 🧵

🦋 IA-64 Options 🦋

These are the -m options defined for the Intel IA-64 architecture. Iconic, honestly. ✨

  • -mbig-endian — generates code for a big-endian target. This is the default for HP-UX.
  • -mlittle-endian — generates code for a little-endian target. This is the default for AIX5 and GNU/Linux.
  • -mgnu-as, -mno-gnu-as — generate (or don't) code for the GNU assembler. This is the default. 🎀
  • -mgnu-ld, -mno-gnu-ld — generate (or don't) code for the GNU linker. This is the default. 🎀
  • -mno-pic — generates code that does not use a global pointer register. The result is not position independent code, and it violates the IA-64 ABI. 😳
  • -mvolatile-asm-stop, -mno-volatile-asm-stop — generate (or don't) a stop bit immediately before and after volatile asm statements.
  • -mregister-names, -mno-register-names — generate (or don't) in, loc, and out register names for the stacked registers. This may make assembler output more readable. 👀
  • -mno-sdata, -msdata — disable (or enable) optimizations that use the small data section. This may be useful for working around optimizer bugs. 🐛
  • -mconstant-gp — generates code that uses a single constant global pointer value. Useful when compiling kernel code. 👑
  • -mauto-pic — generates code that is self-relocatable. This implies -mconstant-gp. Useful when compiling firmware code. 🔧
  • -minline-float-divide-min-latency — generates code for inline divides of floating-point values using the minimum latency algorithm. ⚡
  • -minline-float-divide-max-throughput — generates code for inline divides of floating-point values using the maximum throughput algorithm. 🔥
  • -mno-inline-float-divide — do not generate inline code for divides of floating-point values. 🙅‍♀️
  • -minline-int-divide-min-latency — generates code for inline divides of integer values using the minimum latency algorithm. ⚡
  • -minline-int-divide-max-throughput — generates code for inline divides of integer values using the maximum throughput algorithm. 🔥
  • -mno-inline-int-divide — do not generate inline code for divides of integer values. 🙅‍♀️
  • -minline-sqrt-min-latency — makes the compiler spit out inline square roots using the minimum latency algorithm. Speed-of-light vibes, lowkey.
  • -minline-sqrt-max-throughput — same inline square root situation but tuned for maximum throughput instead. Different algorithm, different flex. ✨
  • -mno-inline-sqrt — nope, no inline code for sqrt. Periodt.
  • -mfused-madd, -mno-fused-madd — do (or don't) generate code that uses the fused multiply/add or multiply/subtract instructions. The default is to use these instructions, so she's out here fusing by default 💅
  • -mno-dwarf2-asm, -mdwarf2-asm — don't (or do) generate assembler code for the DWARF line number debugging info. Genuinely useful when you're not using the GNU assembler, iykyk.
  • -mearly-stop-bits, -mno-early-stop-bits — lets stop bits get placed earlier than immediately before the instruction that triggered the stop bit. This can improve instruction scheduling, but honestly it doesn't always do so 🙈
  • -mfixed-range=register-range — generates code treating the given register range as fixed registers. A fixed register = one the register allocator literally cannot use. Iconic for compiling kernel code. A register range is two registers separated by a dash, and you can stack multiple register ranges separated by a comma.
  • -mtls-size=tls-size — specifies the bit size of immediate TLS offsets. Valid values are 14, 22, and 64.
  • -mtune=cpu-type — tunes the instruction scheduling for a particular CPU. Valid values are itanium, itanium1, merced, itanium2, and mckinley.
  • -milp32, -mlp64 — generate code for a 32-bit or 64-bit environment. The 32-bit environment sets int, long and pointer to 32 bits. The 64-bit environment sets int to 32 bits and long and pointer to 64 bits. These are HP-UX specific flags, bestie 🫶
  • -mno-sched-br-data-spec, -msched-br-data-spec — (dis/en)able data speculative scheduling before reload. This generates ld.a instructions and the corresponding check instructions (ld.c / chk.a). Default setting is disabled.
  • -msched-ar-data-spec, -mno-sched-ar-data-spec — (en/dis)able data speculative scheduling after reload. Generates ld.a instructions plus the check instructions (ld.c / chk.a). Default setting is enabled.
  • -mno-sched-control-spec, -msched-control-spec — (dis/en)able control speculative scheduling. Heads up: this feature is only available during region scheduling (i.e. before reload). Generates ld.s instructions and the corresponding check instructions chk.s. Default setting is disabled.
  • -msched-br-in-data-spec, -mno-sched-br-in-data-spec — (en/dis)able speculative scheduling of the instructions that depend on the data speculative loads before reload. Only actually does anything with -msched-br-data-spec enabled. Default setting is enabled.
  • -msched-ar-in-data-spec, -mno-sched-ar-in-data-spec — (en/dis)able speculative scheduling of the instructions that depend on the data speculative loads after reload. Effective only with -msched-ar-data-spec enabled. Default setting is enabled.
  • -msched-in-control-spec, -mno-sched-in-control-spec — (en/dis)able speculative scheduling of the instructions that depend on the control speculative loads. Effective only with -msched-control-spec enabled. Default setting is enabled.
  • -mno-sched-prefer-non-data-spec-insns, -msched-prefer-non-data-spec-insns — if enabled, data-speculative instructions only get picked for the schedule when there's literally no other choice at that moment. Makes data speculation wayyy more conservative. Default setting is disabled.
  • -mno-sched-prefer-non-control-spec-insns, -msched-prefer-non-control-spec-insns — if enabled, control-speculative instructions only get picked when there's no other choice at that moment. Also more conservative energy. Default setting is disabled.
  • -mno-sched-count-spec-in-critical-path, -msched-count-spec-in-critical-path — if enabled, speculative dependencies get considered while computing instruction priorities. Makes speculation a bit more conservative. Default setting is disabled.
  • -msched-spec-ldc — use a simple data speculation check. On by default 👑
  • -msched-control-spec-ldc — use a simple check for control speculation. On by default too.
  • -msched-stop-bits-after-every-cycle — place a stop bit after every cycle when scheduling. On by default.
  • -msched-fp-mem-deps-zero-cost — assumes floating-point stores and loads are not likely to conflict when placed into the same instruction group. Disabled by default.
  • -msel-sched-dont-check-control-spec — generate checks for control speculation in selective scheduling. Disabled by default.
  • -msched-max-memory-insns=max-insns — caps the number of memory insns per instruction group, giving lower priority to subsequent memory insns trying to schedule into the same instruction group. Frequently useful for preventing cache bank conflicts. The default value is 1.
  • -msched-max-memory-insns-hard-limit — makes the limit set by msched-max-memory-insns a hard limit, disallowing more than that number in an instruction group. Otherwise the limit is "soft", meaning non-memory operations get preferred once the limit is reached, but memory operations can still be scheduled anyway. Soft launch vs hard launch, basically 💀

✨ LM32 Options ✨

These -m options are defined for the LatticeMico32 architecture:

  • -mbarrel-shift-enabled — enable barrel-shift instructions.
  • -mdivide-enabled — enable divide and modulus instructions.
  • -mmultiply-enabled — enable multiply instructions.
  • -msign-extend-enabled — enable sign extend instructions.
  • -muser-enabled — enable user-defined instructions.

🌸 LoongArch Options 🌸

These command-line options are defined for LoongArch targets:

  • -march=cpu-type — generate instructions for the machine type cpu-type. And bestie, listen: unlike -mtune=cpu-type, which merely tunes the generated code for the specified cpu-type, -march=cpu-type lets GCC generate code that may not run at all on processors other than the one indicated 😭. Specifying -march=cpu-type implies -mtune=cpu-type, except where noted otherwise.

The choices for cpu-type are:

  • native — selects the CPU to generate code for at compilation time by determining the processor type of the compiling machine. Using -march=native enables all instruction subsets supported by the local machine (hence the result might not run on different machines). Using -mtune=native produces code optimized for the local machine under the constraints of the selected instruction set. It's giving main character energy on your machine specifically.
  • loongarch64 — a generic CPU with 64-bit extensions.
  • la464 — LoongArch LA464 CPU with LBT, LSX, LASX, LVZ.
  • -mtune=cpu-type — optimize the output for the given processor, specified by microarchitecture name.
  • -mabi=base-abi-type — generate code for the specified calling convention. base-abi-type can be one of:
    • lp64d — uses 64-bit general purpose registers and 32/64-bit floating-point registers for parameter passing. Data model is LP64, where int is 32 bits, while long int and pointers are 64 bits.
    • lp64f — uses 64-bit general purpose registers and 32-bit floating-point registers for parameter passing. Data model is LP64, where int is 32 bits, while long int and pointers are 64 bits.
    • lp64s — uses 64-bit general purpose registers and no floating-point registers for parameter passing. Data model is LP64, where int is 32 bits, while long int and pointers are 64 bits.
  • -mfpu=fpu-type — generate code for the specified FPU type, which can be one of:
    • 64 — allow the use of hardware floating-point instructions for 32-bit and 64-bit operations.
    • 32 — allow the use of hardware floating-point instructions for 32-bit operations.
    • none, 0 — prevent the use of hardware floating-point instructions. Absolutely no FPU activities permitted 🚫
  • -msoft-float — forces -mfpu=none and prevents the use of floating-point registers for parameter passing. Warning bestie: this option may change the target ABI ⚠️
  • -msingle-float — forces -mfpu=32 and allows the use of 32-bit floating-point registers for parameter passing. Also may change the target ABI.
  • -mdouble-float — forces -mfpu=64 and allows the use of 32/64-bit floating-point registers for parameter passing. Also may change the target ABI.
  • -mbranch-cost=n — set the cost of branches to roughly n instructions.
  • -mcheck-zero-division, -mno-check-zero-divison — trap (do not trap) on integer division by zero. Default is -mcheck-zero-division for -O0 or -Og, and -mno-check-zero-division for other optimization levels. (And yes, the second flag is spelled -mno-check-zero-divison in the manual — no, that's not a typo I made, don't come for me 💀)
  • -mcond-move-int, -mno-cond-move-int — conditional moves for integral data in general-purpose registers are enabled (disabled). The default is -mcond-move-int.
  • -mcond-move-float, -mno-cond-move-float — conditional moves for floating-point registers are enabled (disabled). The default is -mcond-move-float.
  • -mmemcpy, -mno-memcpy — force (do not force) the use of memcpy for non-trivial block moves. The default is -mno-memcpy, which lets GCC inline most constant-sized copies. Setting the optimization level to -Os also forces the use of memcpy, but -mno-memcpy may override this behavior if explicitly specified — regardless of the order these options appear on the command line 👀
  • -mstrict-align, -mno-strict-align — avoid or allow generating memory accesses that may not be aligned on a natural object boundary as described in the architecture specification. The default is -mno-strict-align.
  • -msmall-data-limit=number — put global and static data smaller than number bytes into a special section (on some targets). The default value is 0.
  • -mmax-inline-memcpy-size=n — inline all block moves (such as calls to memcpy or structure copies) less than or equal to n bytes. The default value of n is 1024.
  • -mcmodel=code-model — bestie, this sets the code model, and the code model is basically the vibe check for how far apart your stuff is allowed to live in memory 🗺️✨ Pick one:
  • tiny-static — for the absolute homebodies:
    • local symbol and global strong symbol: the data section must be within +/-2MiB addressing space, and the text section must be within +/-128MiB addressing space.
    • global weak symbol: the got table must be within +/-2GiB addressing space.
  • tiny — still small, slightly chiller:
    • local symbol: the data section must be within +/-2MiB addressing space, and the text section must be within +/-128MiB addressing space.
    • global symbol: the got table must be within +/-2GiB addressing space.
  • normal — the default, the main character 👑
    • local symbol: the data section must be within +/-2GiB addressing space, and the text section must be within +/-128MiB addressing space.
    • global symbol: the got table must be within +/-2GiB addressing space.
  • large — big energy, no cap:
    • local symbol: the data section must be within +/-2GiB addressing space, and the text section must be within +/-128GiB addressing space.
    • global symbol: the got table must be within +/-2GiB addressing space.
  • extreme (Not implemented yet) — manifesting, but like, not yet 💀
    • local symbol: the data and text section must be within +/-8EiB addressing space.
    • global symbol: the data got table must be within +/-8EiB addressing space.

The default code model is normal. Periodt.


🧚 M32C Options 🧚

  • -mcpu=name — tells GCC which CPU it's writing code for. name can be r8c for the R8C/Tiny series, m16c for the M16C (up to /60) series, m32cm for the M16C/80 series, or m32c for the M32C/80 series. Pick your fighter 💅
  • -msim — declares that the program is gonna run on the simulator 🖥️✨ This makes GCC link in an alternate runtime library that supports things like file I/O, which is so nice of it. But do not use this option when you're generating programs that will run on real hardware — you have to provide your own runtime library for whatever I/O functions you need. Real talk, that's on you 🫶
  • -memregs=number — sets how many memory-based pseudo-registers GCC uses while generating code. These pseudo-registers get used just like real registers, so there's a whole tradeoff going on 😭 between GCC's ability to fit the code into the available registers and the performance penalty of using memory instead of registers. Heads up: all modules in a program have to be compiled with the same value for this option. And because of that, you must not use this option with GCC's default runtime libraries. No cap, it'll be a mess 💀

🦋 M32R/D Options 🦋

These -m options are defined for Renesas M32R/D architectures:

  • -m32r2 — generate code for the M32R/2.
  • -m32rx — generate code for the M32R/X.
  • -m32r — generate code for the M32R. This is the default one 💖
  • -mmodel=small — assumes all objects live in the lower 16MB of memory (so their addresses can be loaded with the ld24 instruction), and assumes all subroutines are reachable with the bl instruction. This is the default ✨

The addressability of a particular object can be set with the model attribute.

  • -mmodel=medium — assumes objects may be anywhere in the 32-bit address space (the compiler generates seth/add3 instructions to load their addresses), and assumes all subroutines are reachable with the bl instruction.
  • -mmodel=large — assumes objects may be anywhere in the 32-bit address space (the compiler generates seth/add3 instructions to load their addresses), and assumes subroutines may not be reachable with the bl instruction — so the compiler generates the much slower seth/add3/jl instruction sequence 😭 it's giving sacrifices were made.
  • -msdata=none — disables use of the small data area. Variables go into one of .data, .bss, or .rodata (unless the section attribute has been specified). This is the default.

The small data area consists of sections .sdata and .sbss. Objects may be explicitly put in the small data area with the section attribute using one of these sections.

  • -msdata=sdata — puts small global and static data in the small data area, but does not generate special code to reference them.
  • -msdata=use — puts small global and static data in the small data area, and generates special instructions to reference them. Fancy 💅
  • -G num — puts global and static objects less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS sections. The default value of num is 8. The -msdata option must be set to one of sdata or use for this option to have any effect, otherwise it's just out here doing nothing, awkward 🙈

All modules should be compiled with the same -G num value. Compiling with different values of num may or may not work; if it doesn't, the linker gives an error message — but good news, incorrect code is not generated. We love a loud failure 🔥

  • -mdebug — makes the M32R-specific code in the compiler display some statistics that might help in debugging programs. Detective mode 🔍
  • -malign-loops — aligns all loops to a 32-byte boundary.
  • -mno-align-loops — does not enforce a 32-byte alignment for loops. This is the default.
  • -missue-rate=number — issues number instructions per cycle. number can only be 1 or 2.
  • -mbranch-cost=number — number can only be 1 or 2. If it's 1 then branches are preferred over conditional code; if it's 2, then the opposite applies. Pick a lane 🎀
  • -mflush-trap=number — specifies the trap number to use to flush the cache. The default is 12. Valid numbers are between 0 and 15 inclusive.
  • -mno-flush-trap — specifies that the cache cannot be flushed by using a trap.
  • -mflush-func=name — specifies the name of the operating system function to call to flush the cache. The default is _flush_cache, but a function call is only used if a trap is not available.
  • -mno-flush-func — indicates that there is no OS function for flushing the cache. Cool cool cool, no cache flush for you 💀

🌈 M680x0 Options 🌈

These are the -m options defined for M680x0 and ColdFire processors. The default settings depend on which architecture was selected when the compiler was configured; the defaults for the most common choices are given below. iykyk 🌸

  • -march=arch — generate code for a specific M680x0 or ColdFire instruction set architecture. Permissible values of arch for M680x0 architectures are: 68000, 68010, 68020, 68030, 68040, 68060 and cpu32. ColdFire architectures are selected according to Freescale's ISA classification, and the permissible values are: isaa, isaaplus, isab and isac.

GCC defines a macro __mcfarch__ whenever it is generating code for a ColdFire target. The arch in this macro is one of the -march arguments given above. Cute 🎀

When used together, -march and -mtune select code that runs on a family of similar processors but that is optimized for a particular microarchitecture. Bestie teamwork honestly 🤝

  • -mcpu=cpu — generate code for a specific M680x0 or ColdFire processor. The M680x0 *cpu*s are: 68000, 68010, 68020, 68030, 68040, 68060, 68302, 68332 and cpu32. The ColdFire *cpu*s are given by the list below, which also classifies the CPUs into families:
    • Family 51: 51 51ac 51ag 51cn 51em 51je 51jf 51jg 51jm 51mm 51qe 51qm
    • Family 5206: 5202 5204 5206
    • Family 5206e: 5206e
    • Family 5208: 5207 5208
    • Family 5211a: 5210a 5211a
    • Family 5213: 5211 5212 5213
    • Family 5216: 5214 5216
    • Family 52235: 52230 52231 52232 52233 52234 52235
    • Family 5225: 5224 5225
    • Family 52259: 52252 52254 52255 52256 52258 52259
    • Family 5235: 5232 5233 5234 5235 523x
    • Family 5249: 5249
    • Family 5250: 5250
    • Family 5271: 5270 5271
    • Family 5272: 5272
    • Family 5275: 5274 5275
    • Family 5282: 5280 5281 5282 528x
    • Family 53017: 53011 53012 53013 53014 53015 53016 53017
    • Family 5307: 5307
    • Family 5329: 5327 5328 5329 532x
    • Family 5373: 5372 5373 537x
    • Family 5407: 5407
    • Family 5475: 5470 5471 5472 5473 5474 5475 547x 5480 5481 5482 5483 5484 5485

-mcpu=cpu overrides -march=arch if arch is compatible with cpu. Other combinations of -mcpu and -march are rejected 🙅‍♀️ don't try it.

GCC defines the macro __mcf_cpu_cpu when ColdFire target cpu is selected. It also defines __mcf_family_family, where the value of family is given by the list above. Slay, macros 💅

  • -mtune=tune — tunes the code for a particular microarchitecture within the constraints set by -march and -mcpu. The M680x0 microarchitectures are: 68000, 68010, 68020, 68030, 68040, 68060 and cpu32. The ColdFire microarchitectures are: cfv1, cfv2, cfv3, cfv4 and cfv4e.

You can also use -mtune=68020-40 for code that needs to run relatively well on 68020, 68030 and 68040 targets. -mtune=68020-60 is similar but includes 68060 targets as well. These two options select the same tuning decisions as -m68020-40 and -m68020-60 respectively. Range queen behavior 👑

GCC defines the macros __mcarch and __mcarch__ when tuning for 680x0 architecture arch. It also defines mcarch unless either -ansi or a non-GNU -std option is used. If GCC is tuning for a range of architectures, as selected by -mtune=68020-40 or -mtune=68020-60, it defines the macros for every architecture in the range.

GCC also defines the macro __muarch__ when tuning for ColdFire microarchitecture uarch, where uarch is one of the arguments given above.

  • -m68000, -mc68000 — generate output for a 68000. This is the default when the compiler is configured for 68000-based systems. It is equivalent to -march=68000.

Use this option for microcontrollers with a 68000 or EC000 core, including the 68008, 68302, 68306, 68307, 68322, 68328 and 68356. Old-school but iconic 🎀

  • -m68010 — generate output for a 68010. This is the default when the compiler is configured for 68010-based systems. It is equivalent to -march=68010.
  • -m68020, -mc68020 — generate output for a 68020. This is the default when the compiler is configured for 68020-based systems. It is equivalent to -march=68020.
  • -m68030 — generate output for a 68030. This is the default when the compiler is configured for 68030-based systems. It is equivalent to -march=68030.
  • -m68040 — generate output for a 68040. This is the default when the compiler is configured for 68040-based systems. It is equivalent to -march=68040.

This option inhibits the use of 68881/68882 instructions that have to be emulated by software on the 68040. Use this option if your 68040 does not have code to emulate those instructions. Fr fr, check your hardware first 💀

  • -m68060 — bestie, this one's for the 68060. It's the default when the compiler is configured for 68060-based systems, and it's literally equivalent to -march=68060.

The whole point ✨: this option inhibits the use of 68020 and 68881/68882 instructions that have to be emulated by software on the 68060. So use this option if your 68060 does not have code to emulate those instructions. No emulation? No problem, this flag's got you 🫶

  • -mcpu32 — generate output for a CPU32. Default when the compiler is configured for CPU32-based systems, and it's equivalent to -march=cpu32.

Use this one for microcontrollers with a CPU32 or CPU32+ core, including the 68330, 68331, 68332, 68333, 68334, 68336, 68340, 68341, 68349 and 68360. That's a lot of little guys and every single one of them slays 💅

  • -m5200 — generate output for a 520X ColdFire CPU. Default when the compiler is configured for 520X-based systems. It's equivalent to -mcpu=5206, and — heads up — it's now deprecated in favor of that option 😭

Use it for microcontrollers with a 5200 core, including the MCF5202, MCF5203, MCF5204 and MCF5206.

  • -m5206e — generate output for a 5206e ColdFire CPU. This option is now deprecated in favor of the equivalent -mcpu=5206e. rip to a real one 🪦
  • -m528x — generate output for a member of the ColdFire 528X family. Also now deprecated in favor of the equivalent -mcpu=528x.
  • -m5307 — generate output for a ColdFire 5307 CPU. Deprecated in favor of the equivalent -mcpu=5307.
  • -m5407 — generate output for a ColdFire 5407 CPU. Deprecated in favor of the equivalent -mcpu=5407.
  • -mcfv4e — generate output for a ColdFire V4e family CPU (e.g. 547x/548x). This includes use of hardware floating-point instructions. Equivalent to -mcpu=547x, and yep, now deprecated in favor of that option. The deprecation arc is not stopping, bestie 😮‍💨
  • -m68020-40 — generate output for a 68040 without using any of the new instructions. The result is code that can run relatively efficiently on either a 68020/68881 or a 68030 or a 68040. The generated code does use the 68881 instructions that are emulated on the 68040.

It's equivalent to -march=68020 -mtune=68020-40. Compromise queen 👑

  • -m68020-60 — generate output for a 68060, again without using any of the new instructions. Result: code that runs relatively efficiently on either a 68020/68881 or a 68030 or a 68040. The generated code does use the 68881 instructions that are emulated on the 68060.

Equivalent to -march=68020 -mtune=68020-60.

  • -mhard-float, -m68881 — generate floating-point instructions. This is the default for 68020 and above, and for ColdFire devices that have an FPU. It defines the macro "__HAVE_68881__" on M680x0 targets and "__mcffpu__" on ColdFire targets. Floaty math hours 🔥
  • -msoft-float — do not generate floating-point instructions; use library calls instead. This is the default for 68000, 68010, and 68832 targets. It's also the default for ColdFire devices that have no FPU. No hardware? Cute, we'll just call the library 🫶
  • -mdiv, -mno-div — generate (or don't generate) ColdFire hardware divide and remainder instructions. Here's the tea on defaults ☕: if -march is used without -mcpu, the default is "on" for ColdFire architectures and "off" for M680x0 architectures. Otherwise the default is taken from the target CPU (either the default CPU, or the one specified by -mcpu). For example, the default is "off" for -mcpu=5206 and "on" for -mcpu=5206e.

GCC defines the macro "__mcfhwdiv__" when this option is enabled.

  • -mshort — consider type "int" to be 16 bits wide, like "short int". Additionally, parameters passed on the stack are also aligned to a 16-bit boundary even on targets whose API mandates promotion to 32-bit. We're shrinking the ints, it's a whole thing 🙈
  • -mno-short — do not consider type "int" to be 16 bits wide. This is the default. Ints stay big, periodt.
  • -mnobitfield, -mno-bitfield — do not use the bit-field instructions. The -m68000, -mcpu32 and -m5200 options imply -mnobitfield.
  • -mbitfield — do use the bit-field instructions. The -m68020 option implies -mbitfield. This is the default if you use a configuration designed for a 68020.
  • -mrtd — use a different function-calling convention, where functions that take a fixed number of arguments return with the "rtd" instruction, which pops their arguments while returning. Iconic efficiency: this saves one instruction in the caller since there's no need to pop the arguments there. 💅
⚠️ Bestie, read the fine print, this one bites. This calling convention is incompatible with the one normally used on Unix, so you cannot use it if you need to call libraries compiled with the Unix compiler.

Also, you must provide function prototypes for all functions that take variable numbers of arguments (including "printf"); otherwise incorrect code is generated for calls to those functions. 😭

In addition, seriously incorrect code results if you call a function with too many arguments. (Normally, extra arguments are harmlessly ignored.) So like… don't do that.

The "rtd" instruction is supported by the 68010, 68020, 68030, 68040, 68060 and CPU32 processors, but not by the 68000 or 5200.

The default is -mno-rtd.

  • -malign-int, -mno-align-int — control whether GCC aligns "int", "long", "long long", "float", "double", and "long double" variables on a 32-bit boundary (-malign-int) or a 16-bit boundary (-mno-align-int). Aligning variables on 32-bit boundaries produces code that runs somewhat faster on processors with 32-bit busses — at the expense of more memory. Trade-offs, bestie, it's always trade-offs ⚖️
⚠️ Warning: if you use the -malign-int switch, GCC aligns structures containing the above types differently than most published application binary interface specifications for the m68k. That's an ABI oopsie, be careful 🫠
  • (the flag name got eaten in the source, but it's -mpcrel — it's named right there in the text) — use the pc-relative addressing mode of the 68000 directly, instead of using a global offset table. At present, this option implies -fpic, allowing at most a 16-bit offset for pc-relative addressing. -fPIC is not presently supported with -mpcrel, though this could be supported for 68020 and higher processors. (Future plans, not current facts, iykyk 💜)
  • -mno-strict-align, -mstrict-align — do not (do) assume that unaligned memory references are handled by the system.
  • -msep-data — generate code that allows the data segment to be located in a different area of memory from the text segment. This allows for execute-in-place in an environment without virtual memory management. This option implies -fPIC.
  • -mno-sep-data — generate code that assumes the data segment follows the text segment. This is the default.
  • -mid-shared-library — generate code that supports shared libraries via the library ID method. This allows for execute-in-place and shared libraries in an environment without virtual memory management. This option implies -fPIC. The multitasker of flags ✨
  • -mno-id-shared-library — generate code that doesn't assume ID-based shared libraries are being used. This is the default.
  • -mshared-library-id=n — specifies the identification number of the ID-based shared library being compiled. Specifying a value of 0 generates more compact code; specifying other values forces the allocation of that number to the current library, but is no more space- or time-efficient than omitting this option. So like… 0 or bust, honestly.
  • -mxgot, -mno-xgot — when generating position-independent code for ColdFire, generate code that works if the GOT has more than 8192 entries. This code is larger and slower than code generated without this option. On M680x0 processors, this option is not needed; -fPIC suffices.

GCC normally uses a single instruction to load values from the GOT. While this is relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger causes the linker to report an error such as:

relocation truncated to fit: R_68K_GOT16O foobar

If this happens, you should recompile your code with -mxgot. It should then work with very large GOTs. However, code generated with -mxgot is less efficient, since it takes 4 instructions to fetch the value of a global symbol. Four!! Bestie, that's so many 😭

Note that some linkers, including newer versions of the GNU linker, can create multiple GOTs and sort GOT entries. If you have such a linker, you should only need to use -mxgot when compiling a single object file that accesses more than 8192 GOT entries. Very few do. (Very few do, and honestly, respect.)

These options have no effect unless GCC is generating position-independent code.

  • -mlong-jump-table-offsets — use 32-bit offsets in "switch" tables. The default is to use 16-bit offsets.

🌈 MCore Options 🌈

These are the -m options defined for the Motorola M*Core processors. Little niche, little iconique 💅

  • -mhardlit, -mno-hardlit — inline constants into the code stream if it can be done in two instructions or less. Two instructions max, that's the rule 🎀
  • -mdiv, -mno-div — use the divide instruction. (Enabled by default.) Go off, divider.
  • -mrelax-immediate, -mno-relax-immediate — allow arbitrary-sized immediates in bit operations. No size shaming here ✨
  • -mwide-bitfields, -mno-wide-bitfields — always treat bit-fields as "int"-sized.
  • -m4byte-functions, -mno-4byte-functions — force all functions to be aligned to a 4-byte boundary. Every single one, no exceptions, we love a strict queen 👑
  • -mcallgraph-data, -mno-callgraph-data — emit callgraph information.
  • -mslow-bytes, -mno-slow-bytes — prefer word access when reading byte quantities.
  • -mlittle-endian, -mbig-endian — generate code for a little-endian target. (The endianness discourse continues, and honestly at this point it's a lifestyle.)
  • -m210, -m340 — generate code for the 210 processor. Yes, both of them, that's what the source says, don't come for me 🙈
  • -mno-lsim — assume that runtime support has been provided and so omit the simulator library (libsim.a) from the linker command line. Trusting your environment, a bold move 🫶
  • -mstack-increment=size — set the maximum amount for a single stack increment operation. Large values can increase the speed of programs that contain functions that need a large amount of stack space — but they can also trigger a segmentation fault if the stack is extended too much. 😭 The default value is 0x1000.
⚠️ Yeah that's a real segfault risk, not a vibe. Bigger number, bigger crash potential.

🦋 MeP Options 🦋

  • -mabsdiff — enables the "abs" instruction, which is the absolute difference between two registers. Difference but make it absolute, we stan a decisive instruction 💅
  • -mall-opts — enables all the optional instructions: average, multiply, divide, bit operations, leading zero, absolute difference, min/max, clip, and saturation. All of them. Every single one. Absolutely unhinged, absolutely iconic 🔥
  • -maverage — enables the "ave" instruction, which computes the average of two registers. Middle ground, but make it hardware.
  • -mbased=n — variables of size n bytes or smaller are placed in the ".based" section by default. Based variables use the $tp register as a base register, and there is a 128-byte limit to the ".based" section. So small variables only, and mind the ceiling 🎀
  • -mbitops — turns on the bit-op instructions: bit test (btstm), set (bsetm), clear (bclrm), invert (bnotm), and test-and-set (tas). bit manipulation era 💅
  • -mc=name — picks which section your constant data gets yeeted into. name can be tiny, near, or far.
  • -mclip — enables the clip instruction. bestie listen: -mclip is lowkey useless unless you also hand it -mminmax. they're a package deal fr 🫶
  • -mconfig=name — selects one of the built-in core configurations. every MeP chip has one or more modules inside it, and each module has a core CPU plus a whole little ecosystem of coprocessors, optional instructions, and peripherals. the MeP-Integrator tool (which is not part of GCC, to be clear) hands you these configurations through this option — and using this option is literally the same as using all the corresponding command-line options one by one. default configuration is default. ✨
  • -mcop — enables the coprocessor instructions. by default that's a 32-bit coprocessor. ngl, the coprocessor is normally enabled through the -mconfig= option anyway.
  • -mcop32 — enables the 32-bit coprocessor's instructions.
  • -mcop64 — enables the 64-bit coprocessor's instructions.
  • -mivc2 — enables IVC2 scheduling. IVC2 is a 64-bit VLIW coprocessor, in case you were wondering 👑
  • -mdc — makes constant variables land in the .near section.
  • -mdiv — enables the div and divu instructions.
  • -meb — generate big-endian code.
  • -mel — generate little-endian code.
  • -mio-volatile — tells the compiler that any variable marked with the io attribute must be treated as volatile.
  • -ml — variables get assigned to the .far section by default.
  • -mleadz — enables the leadz (leading zero) instruction.
  • -mm — variables get assigned to the .near section by default.
  • -mminmax — enables the min and max instructions.
  • -mmult — enables the multiplication and multiply-accumulate instructions.
  • -mno-opts — disables all the optional instructions that -mall-opts turned on. the anti-slay button 💀
  • -mrepeat — enables the repeat and erepeat instructions, which are the low-overhead looping girlies.
  • -ms — makes all variables default to the .tiny section. heads up: this section has a 65536-byte limit. accesses to these variables use the %gp base register.
  • -msatur — enables the saturation instructions. note that the compiler does not currently generate these itself — this option exists for compatibility with other tools, like as. it's giving "i'm just here to match the group chat" 🙈
  • -msdram — link the SDRAM-based runtime instead of the default ROM-based runtime.
  • -msim — link the simulator run-time libraries.
  • -msimnovec — link the simulator runtime libraries, minus the built-in support for reset and exception vectors and tables.
  • -mtf — makes all functions default to the .far section. without this option, functions default to the .near section.
  • -mtiny=n — variables that are n bytes or smaller get allocated to the .tiny section. these variables use the $gp base register. the default for this option is 4, but bestie remember there's a 65536-byte limit on the .tiny section. no cap. 🌸

🦋 MicroBlaze Options 🦋

  • -msoft-float — use software emulation for floating point (this is the default).
  • -mhard-float — use hardware floating-point instructions.
  • -mmemcpy — do not optimize block moves, just use memcpy.
  • -mno-clearbss — this option is deprecated. use -fno-zero-initialized-in-bss instead, okay? 💅
  • -mcpu=cpu-type — use features of, and schedule code for, the given CPU. supported values come in the format vX.YY.Z, where X is a major version, YY is the minor version, and Z is compatibility code. example values are v3.00.a, v4.00.b, v5.00.a, v5.00.b, v6.00.a.
  • -mxl-soft-mul — use software multiply emulation (default).
  • -mxl-soft-div — use software emulation for divides (default).
  • -mxl-barrel-shift — use the hardware barrel shifter.
  • -mxl-pattern-compare — use pattern compare instructions.
  • -msmall-divides — use table lookup optimization for small signed integer divisions.
  • -mxl-stack-check — this option is deprecated. use -fstack-check instead.
  • -mxl-gp-opt — use GP-relative .sdata/.sbss sections.
  • -mxl-multiply-high — use multiply high instructions for the high part of a 32x32 multiply.
  • -mxl-float-convert — use hardware floating-point conversion instructions.
  • -mxl-float-sqrt — use the hardware floating-point square root instruction.
  • -mbig-endian — generate code for a big-endian target.
  • -mlittle-endian — generate code for a little-endian target.
  • -mxl-reorder — use reorder instructions (swap and byte reversed load/store).
  • -mxl-mode-app-model — select application model app-model. the valid models are:
    • executable — normal executable (default), uses startup code crt0.o.
    • xmdstub — for use with Xilinx Microprocessor Debugger (XMD) based software intrusive debug agent called xmdstub. this one uses startup file crt1.o and sets the start address of the program to 0x800.
    • bootstrap — for applications that are loaded using a bootloader. this model uses startup file crt2.o, which does not contain a processor reset vector handler. it's suitable for transferring control on a processor reset to the bootloader rather than to the application.
    • novectors — for applications that don't require any of the MicroBlaze vectors. this option may be useful for applications running within a monitoring application. this model uses crt3.o as a startup file.

also: the option -xl-mode-app-model is a deprecated alias for -mxl-mode-app-model.

  • -mpic-data-is-text-relative — assume that the displacement between the text and data segments is fixed at static link time. this lets data be referenced by offset from the start of the text address instead of the GOT, since PC-relative addressing isn't supported. 🙈

👑 MIPS Options 👑

  • -EB — generate big-endian code.
  • -EL — generate little-endian code. this is the default for mips*el-*-* configurations.
  • -march=arch — generate code that runs on arch, which can be the name of a generic MIPS ISA or the name of a particular processor. the ISA names are: mips1, mips2, mips3, mips4, mips32, mips32r2, mips32r3, mips32r5, mips32r6, mips64, mips64r2, mips64r3, mips64r5 and mips64r6. the processor names are: 4kc, 4km, 4kp, 4ksc, 4kec, 4kem, 4kep, 4ksd, 5kc, 5kf, 20kc, 24kc, 24kf2_1, 24kf1_1, 24kec, 24kef2_1, 24kef1_1, 34kc, 34kf2_1, 34kf1_1, 34kn, 74kc, 74kf2_1, 74kf1_1, 74kf3_2, 1004kc, 1004kf2_1, 1004kf1_1, i6400, i6500, interaptiv, loongson2e, loongson2f, loongson3a, gs464, gs464e, gs264e, m4k, m14k, m14kc, m14ke, m14kec, m5100, m5101, octeon, octeon+, octeon2, octeon3, orion, p5600, p6600, r2000, r3000, r3900, r4000, r4400, r4600, r4650, r4700, r5900, r6000, r8000, rm7000, rm9000, r10000, r12000, r14000, r16000, sb1, sr71000, vr4100, vr4111, vr4120, vr4130, vr4300, vr5000, vr5400, vr5500, xlr and xlp. and the special value from-abi selects the most compatible architecture for the selected ABI — that is, mips1 for 32-bit ABIs and mips3 for 64-bit ABIs.

the native Linux/GNU toolchain also supports the value native, which selects the best architecture option for the host processor. -march=native has no effect if GCC doesn't recognize the processor. 😭

in processor names, a final 000 can be abbreviated as k (so like, -march=r2k). prefixes are optional, and vr may be written as r.

names of the form *n*f*2_1 refer to processors with FPUs clocked at half the rate of the core, names of the form *n*f*1_1 refer to processors with FPUs clocked at the same rate as the core, and names of the form *n*f*3_2 refer to processors with FPUs clocked at a ratio of 3:2 with respect to the core. for compatibility reasons, *n*f is accepted as a synonym for *n*f*2_1, while *n*x and *n*bfx are accepted as synonyms for *n*f*1_1.

GCC defines two macros based on the value of this option. the first is _MIPS_ARCH, which gives the name of the target architecture as a string. the second has the form _MIPS_ARCH_foo, where foo is the capitalized value of _MIPS_ARCH. for example, -march=r2000 sets _MIPS_ARCH to "r2000" and defines the macro _MIPS_ARCH_R2000. iconic. ⭐

note that the _MIPS_ARCH macro uses the processor names given above — meaning it has the full prefix and does not abbreviate 000 as k. in the case of from-abi, the macro names the resolved architecture (either "mips1" or "mips3"). and it names the default architecture when no -march option is given.

  • -mtune=arch — optimize for arch. among other things, this option controls the way instructions are scheduled and the perceived cost of arithmetic operations. the list of arch values is the same as for -march.

when this option isn't used, GCC optimizes for the processor specified by -march. by using -march and -mtune together, it's possible to generate code that runs on a whole family of processors but optimize the code for one particular member of that family. bestie that's range 🫶

-mtune defines the macros _MIPS_TUNE and _MIPS_TUNE_foo, which work in the same way as the -march ones described above.

  • -mips1 — equivalent to -march=mips1.
  • -mips2 — equivalent to -march=mips2.
  • -mips3 — equivalent to -march=mips3.
  • -mips4 — equivalent to -march=mips4.
  • -mips32 — equivalent to -march=mips32.
  • -mips32r3 — equivalent to -march=mips32r3.
  • -mips32r5 — equivalent to -march=mips32r5.
  • -mips32r6 — equivalent to -march=mips32r6.
  • -mips64 — equivalent to -march=mips64.
  • -mips64r2 — equivalent to -march=mips64r2.
  • -mips64r3 — equivalent to -march=mips64r3.
  • -mips64r5 — equivalent to -march=mips64r5.
  • -mips64r6 — equivalent to -march=mips64r6.
  • -mips16, -mno-mips16 — generate (do not generate) MIPS16 code. if GCC is targeting a MIPS32 or MIPS64 architecture, it makes use of the MIPS16e ASE.

MIPS16 code generation can also be controlled on a per-function basis by means of the mips16 and nomips16 attributes. 💜

  • -mflip-mips16 — generate MIPS16 code on alternating functions. this option is provided for regression testing of mixed MIPS16/non-MIPS16 code generation, and is not intended for ordinary use in compiling user code. like, genuinely, it's a testing-only situation 🙈
  • -minterlink-compressed, -mno-interlink-compressed — okay so this one is a requirement switch 💅: it says code using the standard (uncompressed) MIPS ISA must be link-compatible with MIPS16 and microMIPS code, and vice versa. -mno- says it doesn't have to be.

Example time, bestie: code using the standard ISA encoding cannot jump directly to MIPS16 or microMIPS code — it has to go through a call or an indirect jump. So -minterlink-compressed disables direct jumps unless GCC knows the target of the jump isn't compressed. 🎯

  • -minterlink-mips16, -mno-interlink-mips16 — literally just aliases of -minterlink-compressed and -mno-interlink-compressed. They predate the microMIPS ASE and are kept around for backwards compatibility. Vintage, but still iconic 🎀
  • -mabi=32, -mabi=o64, -mabi=n32, -mabi=64, -mabi=eabi — generate code for the given ABI. Pick your fighter ✨

Note that the EABI has a 32-bit and a 64-bit variant. GCC normally generates 64-bit code when you select a 64-bit architecture, but you can use -mgp32 to get 32-bit code instead.

For the tea on the O64 ABI, see https://gcc.gnu.org/projects/mipso64-abi.html.

GCC supports a variant of the o32 ABI where floating-point registers are 64 rather than 32 bits wide. Select that combo with -mabi=32 -mfp64. This ABI relies on the mthc1 and mfhc1 instructions, so it's only supported for MIPS32R2, MIPS32R3 and MIPS32R5 processors. No exceptions, no cap 🫶

The register assignments for arguments and return values stay the same, but each scalar value is passed in a single 64-bit register rather than a pair of 32-bit registers. For example, scalar floating-point values are returned in $f0 only, not a $f0/$f1 pair. The set of call-saved registers also remains the same in that the even-numbered double-precision registers are saved.

Two additional variants of the o32 ABI are supported so you can transition from 32-bit to 64-bit registers. Those are FPXX (-mfpxx) and FP64A (-mfp64 -mno-odd-spreg). The FPXX extension mandates that all code must execute correctly when run using 32-bit or 64-bit registers. The code can be interlinked with either FP32 or FP64, but not both. The FP64A extension is similar to the FP64 extension but forbids the use of odd-numbered single-precision registers. This can be used together with the FRE mode of FPUs in MIPS32R5 processors and allows both FP32 and FP64A code to interlink and run in the same process without changing FPU modes. Honestly? Versatile queen behavior 👑


  • -mabicalls, -mno-abicalls — generate (or don't generate) code suitable for SVR4-style dynamic objects. -mabicalls is the default for SVR4-based systems. Default behavior, we love her 🌸
  • -mshared, -mno-shared — generate (or don't generate) code that's fully position-independent and can therefore be linked into shared libraries. Heads up: this option only affects -mabicalls.

All -mabicalls code has traditionally been position-independent, regardless of options like -fPIC and -fpic. But as an extension, the GNU toolchain allows executables to use absolute accesses for locally-binding symbols. It can also use shorter GP initialization sequences and generate direct calls to locally-defined functions. That mode is selected by -mno-shared.

-mno-shared depends on binutils 2.16 or higher and generates objects that can only be linked by the GNU linker. However, the option does not affect the ABI of the final executable; it only affects the ABI of relocatable objects. Using -mno-shared generally makes executables both smaller and quicker. Smaller and faster? Ate. 🔥

-mshared is the default.

  • -mplt, -mno-plt — assume (or don't assume) that the static and dynamic linkers support PLTs and copy relocations. This option only affects -mno-shared -mabicalls. For the n64 ABI, this option has no effect without -msym32. Read the fine print, bestie 📋

You can make -mplt the default by configuring GCC with --with-mips-plt. The default is -mno-plt otherwise.

  • -mxgot, -mno-xgot — lift (or don't lift) the usual restrictions on the size of the global offset table.

GCC normally uses a single instruction to load values from the GOT. Efficient? Relatively, yes 💅 but it only works if the GOT is smaller than about 64k. Anything bigger and the linker reports an error like:

relocation truncated to fit: R_MIPS_GOT16 foobar

If that happens, recompile your code with -mxgot. It works with very large GOTs, although the code is also less efficient, since it takes three instructions to fetch the value of a global symbol. Tradeoffs, babes 😭

Note that some linkers can create multiple GOTs. If you have such a linker, you should only need -mxgot when a single object file accesses more than 64k's worth of GOT entries. Very few do.

These options have no effect unless GCC is generating position independent code.

  • -mgp32 — assume that general-purpose registers are 32 bits wide.
  • -mgp64 — assume that general-purpose registers are 64 bits wide.
  • -mfp32 — assume that floating-point registers are 32 bits wide.
  • -mfp64 — assume that floating-point registers are 64 bits wide.
  • -mfpxx — do not assume the width of floating-point registers. Mysterious. Unknowable. We respect that 🙈
  • -mhard-float — use floating-point coprocessor instructions.
  • -msoft-float — do not use floating-point coprocessor instructions. Implement floating-point calculations using library calls instead.
  • -mno-float — equivalent to -msoft-float, but it additionally asserts that the program being compiled performs no floating-point operations at all. Right now this option is only supported by some bare-metal MIPS configurations, where it may select a special set of libraries that lack all floating-point support — including, for example, the floating-point printf formats.
⚠️ If code compiled with -mno-float accidentally contains floating-point operations, it's likely to suffer a link-time or run-time failure. Like, actually prepare for chaos 💀
  • -msingle-float — assume the floating-point coprocessor only supports single-precision operations.
  • -mdouble-float — assume the floating-point coprocessor supports double-precision operations. This is the default. 🌈
  • -modd-spreg, -mno-odd-spreg — enable the use of odd-numbered single-precision floating-point registers for the o32 ABI. This is the default for processors known to support these registers. When using the o32 FPXX ABI, -mno-odd-spreg is set by default.

  • -mabs=2008, -mabs=legacy — these control how the special not-a-number (NaN) IEEE 754 floating-point data gets treated with the abs.fmt and neg.fmt machine instructions. Tiny options, big responsibility 🧚

By default, or when -mabs=legacy is used, the legacy treatment is selected. In this case those instructions are considered arithmetic and are avoided where correct operation is required and the input operand might be a NaN. A longer sequence of instructions that manipulates the sign bit of floating-point datum manually is used instead, unless the -ffinite-math-only option has also been specified.

The -mabs=2008 option selects the IEEE 754-2008 treatment. In this case the instructions are considered non-arithmetic and therefore operating correctly in all cases, including in particular where the input operand is a NaN. So these instructions are always used for the respective operations. Slay, correctness 💖

  • -mnan=2008, -mnan=legacy — these control the encoding of the special not-a-number (NaN) IEEE 754 floating-point data. (Different thing from the previous one, don't mix them up bestie, iykyk 🫶)

-mnan=legacy selects the legacy encoding. In this case quiet NaNs (qNaNs) are denoted by the first bit of their trailing significand field being 0, whereas signaling NaNs (sNaNs) are denoted by the first bit of their trailing significand field being 1.

-mnan=2008 selects the IEEE 754-2008 encoding. Then it flips: qNaNs get 1 as the first bit of their trailing significand field, and sNaNs get 0. Literally the mirror image, no cap 🪞

The default is -mnan=legacy unless GCC has been configured with --with-nan=2008.

  • -mllsc, -mno-llsc — use (or don't use) ll, sc, and sync instructions to implement atomic memory built-in functions. When neither option is specified, GCC uses the instructions if the target architecture supports them.

-mllsc is useful if the runtime environment can emulate the instructions, and -mno-llsc can be useful when compiling for nonstandard ISAs. You can make either option the default by configuring GCC with --with-llsc and --without-llsc respectively. --with-llsc is the default for some configurations; see the installation documentation for details. Go check the docs, bestie, I'm not making this up 📚

  • -mdsp, -mno-dsp — use (or don't use) revision 1 of the MIPS DSP ASE. This option defines the preprocessor macro __mips_dsp. It also defines __mips_dsp_rev to 1. Number one! 🥇
  • -mdspr2, -mno-dspr2 — use (or don't use) revision 2 of the MIPS DSP ASE. This option defines the preprocessor macros __mips_dsp and __mips_dspr2. It also defines __mips_dsp_rev to 2. Glow-up season ✨
  • -msmartmips, -mno-smartmips — use (or don't use) the MIPS SmartMIPS ASE. Name checks out 🎀
  • -mpaired-single, -mno-paired-single — use (or don't use) paired-single floating-point instructions. This option requires hardware floating-point support to be enabled.
  • -mdmx, -mno-mdmx — use (or don't use) MIPS Digital Media Extension instructions. This option can only be used when generating 64-bit code and requires hardware floating-point support to be enabled. Gatekeeping, honestly 💅
  • -mips3d, -mno-mips3d — use (or don't use) the MIPS-3D ASE. The option -mips3d implies -mpaired-single. Packaged deal 🎁
  • -mmicromips, -mno-micromips — generate (or don't generate) microMIPS code.

MicroMIPS code generation can also be controlled on a per-function basis using the micromips and nomicromips attributes. Per-function control? Main character energy 👑

  • -mmt, -mno-mt — use (or don't use) MT Multithreading instructions.
  • -mmcu, -mno-mcu — use (or don't use) the MIPS MCU ASE instructions.
  • -meva, -mno-eva — use (or don't use) the MIPS Enhanced Virtual Addressing instructions.
  • -mvirt, -mno-virt — use (or don't use) the MIPS Virtualization (VZ) instructions.
  • -mxpa, -mno-xpa — use (or don't use) the MIPS eXtended Physical Address (XPA) instructions. Addressing, but like, extended 💫
  • -mcrc, -mno-crc — turn on (or off) the MIPS Cyclic Redundancy Check (CRC) instructions. 💅
  • -mginv, -mno-ginv — turn on (or off) the MIPS Global INValidate (GINV) instructions. ✨
  • -mloongson-mmi, -mno-loongson-mmi — turn on (or off) the MIPS Loongson MultiMedia extensions Instructions (MMI). 🎀
  • -mloongson-ext, -mno-loongson-ext — turn on (or off) the MIPS Loongson EXTensions (EXT) instructions.
  • -mloongson-ext2, -mno-loongson-ext2 — turn on (or off) the MIPS Loongson EXTensions r2 (EXT2) instructions.
  • -mlong64 — forces long types to be 64 bits wide, periodt. If you wanna know what the default is and how the pointer size gets decided, go peek at -mlong32 👀
  • -mlong32 — forces long, int, and pointer types to all be 32 bits wide.

So like, the default size of ints, longs and pointers? It depends on the ABI, bestie. All the supported ABIs use 32-bit ints. The n64 ABI uses 64-bit longs, and so does the 64-bit EABI — the rest use 32-bit longs. And pointers are the same size as longs, or the same size as integer registers — whichever one is smaller. 🦋

  • -msym32, -mno-sym32 — assume (or don't assume) that every symbol has a 32-bit value, no matter which ABI you picked. This one's a collab with -mabi=64 and -mno-abicalls — together they let GCC generate shorter and faster references to symbolic addresses. 🔥
  • -G num — puts definitions of externally-visible data into a small data section if that data is no bigger than num bytes. Then GCC can generate way more efficient accesses to that data; -mgpopt has the deets.

The default -G option depends on the configuration, iykyk.

  • -mlocal-sdata, -mno-local-sdata — extend (or don't extend) the -G behavior to local data too, like static variables in C. -mlocal-sdata is the default for all configurations. 🌸

If the linker starts complaining that an application is using too much small data, you might wanna try rebuilding the less performance-critical parts with -mno-local-sdata. You might also wanna build large libraries with -mno-local-sdata, so the libraries leave more room for the main program. team player energy 🫶

  • -mextern-sdata, -mno-extern-sdata — assume (or don't assume) that externally-defined data lives in a small data section if that data's size is within the -G limit. -mextern-sdata is the default for all configurations.

Okay so here's the vibe check, because this one has rules: if you compile a module Mod with -mextern-sdata -G num -mgpopt, and Mod references a variable Var that's no bigger than num bytes, you must make sure that Var is placed in a small data section. If Var is defined by another module, you must either compile that module with a high-enough -G setting or attach a section attribute to Var's definition. And if Var is common, you must link the application with a high-enough -G setting. 😭

The easiest way of satisfying these restrictions is to compile and link every module with the same -G option — simple, iconic, done. But maybe you wanna build a library that supports several different small data limits. You can do that by compiling the library with the highest supported -G setting and additionally using -mno-extern-sdata to stop the library from making assumptions about externally-defined data. 💜

  • -mgpopt, -mno-gpopt — use (or don't use) GP-relative accesses for symbols that are known to be in a small data section; see -G, -mlocal-sdata and -mextern-sdata. -mgpopt is the default for all configurations. ✨

-mno-gpopt is the move for cases where the $gp register might not hold the value of _gp. For example, if the code is part of a library that might be used in a boot monitor, programs that call boot monitor routines pass an unknown value in $gp. (In such situations, the boot monitor itself is usually compiled with -G0.) 👑

Heads up: -mno-gpopt implies -mno-local-sdata and -mno-extern-sdata. Chain reaction, no cap.
  • -membedded-data, -mno-embedded-data — allocate variables to the read-only data section first if possible, then next in the small data section if possible, otherwise in data. This gives slightly slower code than the default, but it reduces the amount of RAM required when executing — which is why some embedded systems are obsessed with it. 🌈
  • -muninit-const-in-rodata, -mno-uninit-const-in-rodata — put uninitialized const variables in the read-only data section. This option is only meaningful in conjunction with -membedded-data, so don't come at it alone. 💀
  • *-mcode-readable=setting* — picks whether GCC may generate code that reads from executable sections. Three possible settings, queens:
    • -mcode-readable=yes — instructions may freely access executable sections. This is the default setting. 🙈
    • -mcode-readable=pcrel — MIPS16 PC-relative load instructions can access executable sections, but other instructions must not do so. This one's useful on 4KSc and 4KSd processors when the code TLBs have the Read Inhibit bit set. It's also useful on processors that can be configured to have a dual instruction/data SRAM interface and that, like the M4K, automatically redirect PC-relative loads to the instruction RAM. 🧚
    • -mcode-readable=no — instructions must not access executable sections. This can be useful on targets that are configured to have a dual instruction/data SRAM interface but that (unlike the M4K) do not automatically redirect PC-relative loads to the instruction RAM. ⭐
  • -msplit-addresses, -mno-split-addresses — enable (or disable) use of the %hi() and %lo() assembler relocation operators. This one's been superseded by -mexplicit-relocs but it's retained for backwards compatibility. elder icon behavior 🎀
  • -mexplicit-relocs, -mno-explicit-relocs — use (or don't use) assembler relocation operators when dealing with symbolic addresses. The alternative, selected by -mno-explicit-relocs, is to use assembler macros instead.

-mexplicit-relocs is the default if GCC was configured to use an assembler that supports relocation operators. 🦋

  • -mcheck-zero-division, -mno-check-zero-division — trap (or don't trap) on integer division by zero.

The default is -mcheck-zero-division. 💅

  • -mdivide-traps, -mdivide-breaks — MIPS systems check for division by zero by generating either a conditional trap or a break instruction. Using traps results in smaller code, but it's only supported on MIPS II and later. Also — and this is the messy part 😭 — some versions of the Linux kernel have a bug that prevents trap from generating the proper signal (SIGFPE). Use -mdivide-traps to allow conditional traps on architectures that support them, and -mdivide-breaks to force the use of breaks.

The default is usually -mdivide-traps, but this can be overridden at configure time using --with-divide=breaks. Divide-by-zero checks can be completely disabled using -mno-check-zero-division.

  • -mload-store-pairs, -mno-load-store-pairs — enable (or disable) an optimization that pairs consecutive load or store instructions to enable load/store bonding. Enabled by default, but it only takes effect when the selected architecture is known to support bonding. lowkey conditional 💜
  • -munaligned-access, -mno-unaligned-access — enable (or disable) direct unaligned access for MIPS Release 6. MIPSr6 requires load/store unaligned-access support, by hardware or trap&emulate. So -mno-unaligned-access may be needed by kernel. 👑
  • -mmemcpy, -mno-memcpy — force (or don't force) the use of memcpy for non-trivial block moves. The default is -mno-memcpy, which allows GCC to inline most constant-sized copies. ✨
  • -mlong-calls, -mno-long-calls — disable (or don't disable) use of the jal instruction. Calling functions using jal is more efficient but requires the caller and callee to be in the same 256 megabyte segment. so like, same neighborhood or nothing 🫶

This option has no effect on abicalls code. The default is -mno-long-calls.

  • -mmad, -mno-mad — enable (or disable) use of the mad, madu and mul instructions, as provided by the R4650 ISA. 🌸
  • -mimadd, -mno-imadd — enable (or disable) use of the madd and msub integer instructions. The default is -mimadd on architectures that support madd and msub — except for the 74k architecture, where it was found to generate slower code. not the 74k catching strays 💀
  • -mfused-madd, -mno-fused-madd — enable (or disable) use of the floating-point multiply-accumulate instructions, when they're available. The default is -mfused-madd. 🔥

On the R8000 CPU, when multiply-accumulate instructions are used, the intermediate product is calculated to infinite precision and is not subject to the FCSR Flush to Zero bit. That may be undesirable in some circumstances, jsyk. On other processors the result is numerically identical to the equivalent computation using separate multiply, add, subtract and negate instructions. ✨

  • -nocpp — tells the MIPS assembler to not run its preprocessor over user assembler files (with a .s suffix) when assembling them. minding its own business 🙈
  • -mfix-24k, -mno-fix-24k — works around the 24K E48 (lost data on stores during refill) errata. The workarounds are implemented by the assembler rather than by GCC. 🎀
  • -mfix-r4000, -mno-fix-r4000 — works around certain R4000 CPU errata:
    • A double-word or a variable shift may give an incorrect result if executed immediately after starting an integer division.
    • A double-word or a variable shift may give an incorrect result if executed while an integer multiplication is in progress.
    • An integer division may give an incorrect result if started in a delay slot of a taken branch or a jump.

like three separate little gremlins, all handled 😤

  • -mfix-r4400, -mno-fix-r4400 — works around certain R4400 CPU errata:
    • A double-word or a variable shift may give an incorrect result if executed immediately after starting an integer division.
  • -mfix-r10000, -mno-fix-r10000 — works around certain R10000 errata:
    • ll/sc sequences may not behave atomically on revisions prior to 3.0. They may deadlock on revisions 2.6 and earlier. 💀
This option can only be used if the target architecture supports branch-likely instructions. -mfix-r10000 is the default when -march=r10000 is used; -mno-fix-r10000 is the default otherwise.
  • -mfix-r5900, -mno-fix-r5900 — basically: don't try to schedule the instruction right before a branch into the delay slot of a branch that sits at the end of a short loop of six instructions or fewer, and always schedule a "nop" there instead. Why? Because of a hardware bug in the R5900 chip — under certain conditions the short loop bug makes loops run only once or twice 😭. The workaround is implemented by the assembler, not by GCC itself. Good to know!
  • -mfix-rm7000, -mno-fix-rm7000 — works around the RM7000 "dmult"/"dmultu" errata 🛠️. Again, the workarounds live in the assembler, not in GCC.
  • -mfix-vr4120, -mno-fix-vr4120 — works around certain VR4120 errata, and bestie there are two of them:
    • "dmultu" doesn't always produce the correct result 😬
    • "div" and "ddiv" don't always produce the correct result if one of the operands is negative.

The workarounds for the division errata rely on special functions in libgcc.a. At the moment, those functions are only provided by the "mips64vr*-elf" configurations.

Other VR4120 errata need a NOP inserted between certain pairs of instructions — those are handled by the assembler, not by GCC itself.

  • -mfix-vr4130 — works around the VR4130 "mflo"/"mfhi" errata. The workarounds are implemented by the assembler rather than by GCC, although GCC avoids using "mflo" and "mfhi" if the VR4130 "macc", "macchi", "dmacc" and "dmacchi" instructions are available instead. Clever girl 💅
  • -mfix-sb1, -mno-fix-sb1 — works around certain SB-1 CPU core errata. (Right now this flag works around the SB-1 revision 2 "F1" and "F2" floating-point errata.)
  • -mr10k-cache-barrier=setting — tells GCC whether it should insert cache barriers to avoid the side effects of speculation on R10K processors.

So here's the lore 📖: like lots of processors, the R10K tries to predict the outcome of a conditional branch and speculatively executes instructions from the "taken" branch. It later aborts those instructions if the prediction was wrong. But on the R10K, even aborted instructions can have side effects 😳.

This problem only affects kernel stores and, depending on the system, kernel loads. For example, a speculatively-executed store may load the target memory into cache and mark the cache line as dirty, even if the store itself is later aborted. If a DMA operation writes to the same area of memory before the "dirty" line is flushed, the cached data overwrites the DMA-ed data. See the R10K processor manual for the full description, including other potential problems.

One workaround is to insert cache barrier instructions before every memory access that might be speculatively executed and that might have side effects even if aborted. -mr10k-cache-barrier=setting controls GCC's implementation of this workaround. It assumes that aborted accesses to any byte in the following regions do not have side effects:

  1. the memory occupied by the current function's stack frame;
  2. the memory occupied by an incoming stack argument;
  3. the memory occupied by an object with a link-time-constant address.
It is the kernel's responsibility to ensure that speculative accesses to these regions are indeed safe. No pressure or anything 💀

If the input program contains a function declaration such as:

void foo (void);

then the implementation of "foo" must allow "j foo" and "jal foo" to be executed speculatively. GCC honors this restriction for functions it compiles itself. It expects non-GCC functions (such as hand-written assembly code) to do the same.

The option has three forms:

  • -mr10k-cache-barrier=load-store — insert a cache barrier before a load or store that might be speculatively executed and that might have side effects even if aborted.
  • -mr10k-cache-barrier=store — insert a cache barrier before a store that might be speculatively executed and that might have side effects even if aborted.
  • -mr10k-cache-barrier=none — disable the insertion of cache barriers. This is the default setting ✨
  • -mflush-func=func, -mno-flush-func — specifies the function to call to flush the I and D caches, or to not call any such function at all. If it is called, the function must take the same arguments as the common "_flush_func", that is, the address of the memory range for which the cache is being flushed, the size of the memory range, and the number 3 (to flush both caches). The default depends on the target GCC was configured for, but it's commonly either "_flush_func" or "__cpu_flush".
  • mbranch-cost=num — set the cost of branches to roughly num "simple" instructions. (Yes, it's written without the leading dash in the original — copying it exactly, bestie 🫶.) This cost is only a heuristic, and it is not guaranteed to produce consistent results across releases. A zero cost redundantly selects the default, which is based on the -mtune setting.
  • -mbranch-likely, -mno-branch-likely — enable or disable use of Branch Likely instructions, regardless of what the default is for the selected architecture. By default, Branch Likely instructions may be generated if the selected architecture supports them. There's an exception for the MIPS32 and MIPS64 architectures and processors that implement those architectures — for those, Branch Likely instructions are not generated by default, because the MIPS32 and MIPS64 architectures specifically deprecate their use 🚫
  • -mcompact-branches=never, -mcompact-branches=optimal, -mcompact-branches=always — these control which form of branches will be generated. The default is -mcompact-branches=optimal.
    • -mcompact-branches=never ensures that compact branch instructions will never be generated.
    • -mcompact-branches=always ensures that a compact branch instruction will be generated if available. If a compact branch instruction isn't available, a delay slot form of the branch is used instead.
    • -mcompact-branches=optimal will cause a delay slot branch to be used if one is available in the current ISA and the delay slot is successfully filled. If the delay slot isn't filled, a compact branch will be chosen if one is available.

This option is supported from MIPS Release 6 onwards 🎀

  • -mfp-exceptions, -mno-fp-exceptions — specifies whether FP exceptions are enabled. This affects how FP instructions are scheduled for some processors. The default is that FP exceptions are enabled.

For instance, on the SB-1, if FP exceptions are disabled and we're emitting 64-bit code, then we can use both FP pipes. Otherwise we can only use one FP pipe 🥲

  • -mvr4130-align, -mno-vr4130-align — the VR4130 pipeline is two-way superscalar, but it can only issue two instructions together if the first one is 8-byte aligned. When this option is enabled, GCC aligns pairs of instructions that it thinks should execute in parallel.

This option only has an effect when optimizing for the VR4130. It normally makes code faster, but at the expense of making it bigger. It's enabled by default at optimization level -O3 🔥

  • -msynci, -mno-synci — enable (disable) generation of "synci" instructions on architectures that support it. The "synci" instructions (if enabled) are generated when "__builtin___clear_cache" is compiled.

This option defaults to -mno-synci, but the default can be overridden by configuring GCC with --with-synci.

When compiling code for single processor systems, it's generally safe to use "synci". However, on many multi-core (SMP) systems it does not invalidate the instruction caches on all cores and may lead to undefined behavior ⚠️
  • -mrelax-pic-calls, -mno-relax-pic-calls — try to turn PIC calls that are normally dispatched via register $25 into direct calls. This is only possible if the linker can resolve the destination at link time and if the destination is within range for a direct call.

-mrelax-pic-calls is the default if GCC was configured to use an assembler and a linker that support the ".reloc" assembly directive and -mexplicit-relocs is in effect. With -mno-explicit-relocs, this optimization can be performed by the assembler and the linker alone without any help from the compiler ✨

  • -mmcount-ra-address, -mno-mcount-ra-address — emit (do not emit) code that allows "_mcount" to modify the calling function's return address. When enabled, this option extends the usual "_mcount" interface with a new ra-address parameter, which has type "intptr_t *" and is passed in register $12. "_mcount" can then modify the return address by doing both of these:
    • returning the new address in register $31;
    • storing the new address in "*ra-address", if ra-address is nonnull.

The default is -mno-mcount-ra-address.

  • -mframe-header-opt, -mno-frame-header-opt — enable (disable) frame header optimization in the o32 ABI. When using the o32 ABI, calling functions will allocate 16 bytes on the stack for the called function to write out register arguments. When enabled, this optimization will suppress the allocation of the frame header if it can be determined that it's unused.

This optimization is off by default at all optimization levels 🙈

  • -mlxc1-sxc1, -mno-lxc1-sxc1 — when applicable, enable (disable) the generation of "lwxc1", "swxc1", "ldxc1", "sdxc1" instructions. Enabled by default 💜
  • -mmadd4, -mno-madd4 — when applicable, enable (disable) the generation of 4-operand "madd.s", "madd.d" and related instructions. Enabled by default 💜

🌸 MMIX Options 🌸

These options are defined for the MMIX, bestie:

  • -mlibfuncs, -mno-libfuncs — specify that intrinsic library functions are being compiled, passing all values in registers, no matter the size.
  • -mepsilon, -mno-epsilon — generate floating-point comparison instructions that compare with respect to the "rE" epsilon register.
  • -mabi=mmixware, -mabi=gnu — generate code that passes function parameters and return values that (in the called function) are seen as registers $0 and up, as opposed to the GNU ABI which uses global registers $231 and up. Two vibes, one choice 🦋
  • -mzero-extend, -mno-zero-extend — okay so when you're reading data out of memory in chunks shorter than 64 bits, this makes the default load instructions zero-extending instead of sign-extending. Use -mzero-extend to zero-extend, -mno-zero-extend to... not do that. 💅
  • -mknuthdiv, -mno-knuthdiv — this one's about the sign of the remainder when a division leaves one. With -mknuthdiv, the remainder's sign matches the divisor. With the default, -mno-knuthdiv, the remainder's sign follows the dividend. Both are arithmetically valid, bestie — it's just that the latter is almost exclusively the one people actually use. 🎀
  • -mtoplevel-symbols, -mno-toplevel-symbols — prepend (or don't prepend) a : to all global symbols, so your assembly can be fed to the PREFIX assembly directive. iconic behavior honestly ✨
  • -melf — generate an executable in ELF format instead of the default mmo format (the one the mmix simulator uses). glow-up for your binary 🦋
  • -mbranch-predict, -mno-branch-predict — use (or don't use) the probable-branch instructions when static branch prediction says a branch is probably gonna happen. manifesting the branch ✨
  • -mbase-addresses, -mno-base-addresses — generate (or don't generate) code that uses base addresses. Using a base address auto-generates a request (handled by the assembler and the linker, no you don't do it) for a constant to be set up in a global register. That register then serves one or more base address requests within the range 0 to 255 from the value held in the register. Generally this leads to short and fast code, but the number of different data items you can address is limited. So like… a program with lots of static data may need -mno-base-addresses. trade-offs, always trade-offs 😭
  • -msingle-exit, -mno-single-exit — force (or don't force) generated code to have a single exit point in each function. one door out, main character energy 👑

🌸 MN10300 Options 🌸

These -m options are defined for Matsushita MN10300 architectures:

  • -mmult-bug — generate code that dodges bugs in the multiply instructions for MN10300 processors. This is the default, bestie — it's protecting you by default 🫶
  • -mno-mult-bug — do not generate code to avoid those multiply instruction bugs. your choice, live your truth 🙈
  • -mam33 — generate code using features specific to the AM33 processor.
  • -mno-am33 — don't generate code using AM33-specific features. This is the default.
  • -mam33-2 — generate code using features specific to the AM33/2.0 processor.
  • -mam34 — generate code using features specific to the AM34 processor.
  • -mtune=cpu-type — use the timing characteristics of the indicated CPU type when scheduling instructions. Heads up: this does not change the targeted processor type. The CPU type must be one of mn10300, am33, am33-2 or am34.
  • -mreturn-pointer-on-d0 — when generating a function that returns a pointer, return that pointer in both a0 and d0. Otherwise the pointer comes back only in a0, and attempts to call such functions without a prototype result in errors. Note that this option is on by default — use -mno-return-pointer-on-d0 to turn it off. 💅
  • -mno-crt0 — do not link in the C run-time initialization object file.
  • -mrelax — tell the linker it should do a relaxation optimization pass to shorten branches, calls and absolute memory addresses. This option only does anything when you use it on the command line for the final link step.
Fr fr though: this option makes symbolic debugging impossible. like, gone. no cap. 😭
  • -mliw — let the compiler generate Long Instruction Word instructions if the target is AM33 or later. This is the default. This option defines the preprocessor macro __LIW__. ✨
  • -mno-liw — don't allow Long Instruction Word instruction generation. This option defines the preprocessor macro __NO_LIW__.
  • -msetlb — let the compiler generate the SETLB and Lcc instructions if the target is AM33 or later. This is the default. This option defines the preprocessor macro __SETLB__.
  • -mno-setlb — don't allow generation of SETLB or Lcc instructions. This option defines the preprocessor macro __NO_SETLB__.

🦋 Moxie Options 🦋

  • -meb — generate big-endian code. This is the default for moxie-*-* configurations.
  • -mel — generate little-endian code.
  • -mmul.x — generate mul.x and umul.x instructions. This is the default for moxiebox-*-* configurations.
  • -mno-crt0 — do not link in the C run-time initialization object file. (yes it's here again, she gets around 💅)

🎀 MSP430 Options 🎀

These options are defined for the MSP430:

  • -masm-hex — force assembly output to always use hex constants. Normally such constants are signed decimals, but this option exists for testsuite and/or aesthetic purposes. aesthetic purposes!! she said it, not me 🎀✨
  • -mmcu= — select the MCU to target. This is used to create a C preprocessor symbol based on the MCU name, converted to upper case and pre- and post-fixed with __. That symbol is in turn used by the msp430.h header file to select an MCU-specific supplementary header file.

The option also sets the ISA to use. If the MCU name is one known to only support the 430 ISA, then that's selected — otherwise the 430X ISA is selected. A generic MCU name of msp430 can also be used to select the 430 ISA. Similarly the generic msp430x MCU name selects the 430X ISA.

In addition, an MCU-specific linker script gets added to the linker command line. The script's name is the name of the MCU with .ld appended. So specifying -mmcu=xxx on the gcc command line defines the C preprocessor symbol __XXX__ and causes the linker to search for a script called xxx.ld.

The ISA and hardware multiply supported for the different MCUs is hard-coded into GCC. However — plot twist — an external devices.csv file can be used to extend device support beyond what's been hard-coded. 👀

GCC searches for the devices.csv file using the following methods in the given precedence order, where the first method takes precedence over the second, which takes precedence over the third.

Include path specified with -I and -L

devices.csv will be searched for in each of the directories specified by include paths and linker library search paths.

Path specified by the environment variable MSP430_GCC_INCLUDE_DIR

Define the value of the global environment variable MSP430_GCC_INCLUDE_DIR to the full path to the directory containing devices.csv, and GCC will search this directory for devices.csv. If devices.csv is found, this directory will also be registered as an include path and a linker library path. Header files and linker scripts in this directory can therefore be used without manually specifying -I and -L on the command line. honestly, convenient king behavior 👑

The msp430-elf{,bare}/include/devices directory

Finally, GCC will examine msp430-elf{,bare}/include/devices from the toolchain root directory. This directory does not exist in a default installation, but if you've created it and copied devices.csv there, then the MCU data will be read. As above, this directory will also be registered as an include path and linker library path.

If none of the above search methods find devices.csv, then the hard-coded MCU data is used. fallback era 💅

  • -mwarn-mcu, -mno-warn-mcu — enables or disables warnings about conflicts between the MCU name specified by -mmcu and the ISA set by -mcpu and/or the hardware multiply support set by -mhwmult. It also toggles warnings about unrecognized MCU names. This option is on by default.
  • -mcpu= — specifies the ISA to use. Accepted values are msp430, msp430x and msp430xv2. This option is deprecated 😬 — the -mmcu= option should be used to select the ISA instead.
  • -msim — link to the simulator runtime libraries and linker script. Overrides any scripts that would have been selected by the -mmcu= option.
  • -mlarge — use large-model addressing (20-bit pointers, 20-bit size_t).
  • -msmall — use small-model addressing (16-bit pointers, 16-bit size_t).
  • -mrelax — this option is passed to the assembler and linker, and lets the linker perform certain optimizations that cannot be done until the final link. ⭐
  • mhwmult= — describes the type of hardware multiply supported by the target. Accepted values are none for no hardware multiply, 16bit for the original 16-bit-only multiply supported by early MCUs, 32bit for the 16/32-bit multiply supported by later MCUs, and f5series for the 16/32-bit multiply supported by F5-series MCUs. A value of auto can also be given — that tells GCC to deduce the hardware multiply support based on the MCU name provided by the -mmcu option. If no -mmcu option is specified, or if the MCU name isn't recognized, then no hardware multiply support is assumed. "auto" is the default setting. 🌀

Hardware multiplies are normally performed by calling a library routine. This saves space in the generated code. When compiling at -O3 or higher, though, the hardware multiplier is invoked inline — bigger code, but faster. a classic trade-off moment, iykyk 🫶

The hardware multiply routines disable interrupts while running and restore the previous interrupt state when they finish. That makes them safe to use inside interrupt handlers as well as in normal code. ✨

  • -minrt — enable the use of a minimum runtime environment: no static initializers or constructors. This is intended for memory-constrained devices. The compiler includes special symbols in some objects that tell the linker and runtime which code fragments are required. tiny but mighty 🧚
  • -mtiny-printf — enable reduced code size printf and puts library functions. Heads up though: the tiny implementations of these functions are not reentrant, so they must be used with caution in multi-threaded applications. 😭

Support for streams has been removed, and the string to be printed will always be sent to stdout via the write syscall. The string is not buffered before it's sent to write.

This option requires Newlib Nano IO, so GCC must be configured with --enable-newlib-nano-formatted-io.

  • -mmax-inline-shift= — this option takes an integer between 0 and 64 inclusive, and sets the maximum number of inline shift instructions that should be emitted to perform a shift operation by a constant amount. When this value needs to be exceeded, an mspabi helper function is used instead. The default value is 4. 💜

This bit only kicks in when a shift by multiple positions can't be completed with a single instruction — like, for real, all shifts >1 on the 430 ISA. 😭

Shifts of a 32-bit value are at least twice as costly, so the value passed for this option is divided by 2 and the resulting value is used instead. Math said what it said. 💅

  • -mcode-region= and -mdata-region= — these tell the compiler where to place functions and data that do not have one of the "lower", "upper", "either" or "section" attributes. Possible values are "lower", "upper", "either" or "any". The first three behave like the corresponding attribute. The fourth possible value — "any" — is the default. It leaves placement entirely up to the linker script and how it assigns the standard sections (.text, .data, etc.) to the memory regions. ✨
  • -msilicon-errata= — this passes on a request to the assembler to enable the fixes for the named silicon errata. 🛠️
  • -msilicon-errata-warn= — this passes on a request to the assembler to enable warning messages when a silicon errata might need to be applied. 👀
  • -mwarn-devices-csv, -mno-warn-devices-csv — warn if devices.csv is not found or if there's a problem parsing it (default: on). csv watch activated 🫶

🌸 NDS32 Options 🌸

These options are defined for NDS32 implementations:

  • -mbig-endian — generate code in big-endian mode.
  • -mlittle-endian — generate code in little-endian mode.
  • -mreduced-regs — use reduced-set registers for register allocation.
  • -mfull-regs — use full-set registers for register allocation.
  • -mcmov — generate conditional move instructions.
  • -mno-cmov — do not generate conditional move instructions.
  • -mext-perf — generate performance extension instructions.
  • -mno-ext-perf — do not generate performance extension instructions.
  • -mext-perf2 — generate performance extension 2 instructions.
  • -mno-ext-perf2 — do not generate performance extension 2 instructions.
  • -mext-string — generate string extension instructions.
  • -mno-ext-string — do not generate string extension instructions.
  • -mv3push — generate v3 push25/pop25 instructions.
  • -mno-v3push — do not generate v3 push25/pop25 instructions.
  • -m16-bit — generate 16-bit instructions.
  • -mno-16-bit — do not generate 16-bit instructions.
  • -misr-vector-size=num — specify the size of each interrupt vector, which must be 4 or 16.
  • -mcache-block-size=num — specify the size of each cache block, which must be a power of 2 between 4 and 512.
  • -march=arch — specify the name of the target architecture.
  • -mcmodel=code-model — set the code model to one of:
    • small — all the data and read-only data segments must be within 512KB addressing space. The text segment must be within 16MB addressing space.
    • medium — the data segment must be within 512KB while the read-only data segment can be within 4GB addressing space. The text segment should be still within 16MB addressing space.
    • large — all the text and data segments can be within 4GB addressing space.
  • -mctor-dtor — enable constructor/destructor feature.
  • -mrelax — guide linker to relax instructions.

🦋 Nios II Options 🦋

These are the options defined for the Altera Nios II processor.

  • -G num — put global and static objects less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS sections. The default value of num is 8.
  • -mgpopt=option, -mgpopt, -mno-gpopt — generate (do not generate) GP-relative accesses. The following option names are recognized:
    • none — do not generate GP-relative accesses.
    • local — generate GP-relative accesses for small data objects that are not external, weak, or uninitialized common symbols. Also use GP-relative addressing for objects that have been explicitly placed in a small data section via a "section" attribute.
    • global — as for local, but also generate GP-relative accesses for small data objects that are external, weak, or common. If you use this option, you must ensure that all parts of your program (including libraries) are compiled with the same -G setting.
    • data — generate GP-relative accesses for all data objects in the program. If you use this option, the entire data and BSS segments of your program must fit in 64K of memory and you must use an appropriate linker script to allocate them within the addressable range of the global pointer.
    • all — generate GP-relative addresses for function pointers as well as data pointers. If you use this option, the entire text, data, and BSS segments of your program must fit in 64K of memory and you must use an appropriate linker script to allocate them within the addressable range of the global pointer.

-mgpopt is equivalent to -mgpopt=local, and -mno-gpopt is equivalent to -mgpopt=none.

The default is -mgpopt except when -fpic or -fPIC is specified to generate position-independent code. Note that the Nios II ABI does not permit GP-relative accesses from shared libraries. ABI boundaries said no 💅

You may need to specify -mno-gpopt explicitly when building programs that include large amounts of small data, including large GOT data sections. In this case, the 16-bit offset for GP-relative addressing may not be large enough to allow access to the entire small data section.

  • -mgprel-sec=regexp — this specifies additional section names that can be accessed via GP-relative addressing. It is most useful in conjunction with "section" attributes on variable declarations and a custom linker script. The regexp is a POSIX Extended Regular Expression. This option does not affect the behavior of the -G option, and the specified sections are in addition to the standard .sdata and .sbss small-data sections that are recognized by -mgpopt.
  • -mr0rel-sec=regexp — this specifies names of sections that can be accessed via a 16-bit offset from r0; that is, in the low 32K or high 32K of the 32-bit address space. It is most useful in conjunction with "section" attributes on variable declarations and a custom linker script. The regexp is a POSIX Extended Regular Expression. In contrast to the use of GP-relative addressing for small data, zero-based addressing is never generated by default and there are no conventional section names used in standard linker scripts for sections in the low or high areas of memory.
  • -mel, -meb — generate little-endian (default) or big-endian (experimental) code, respectively.
  • -march=arch — this specifies the name of the target Nios II architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. Permissible names are: r1, r2. The preprocessor macro __nios2_arch__ is available to programs, with value 1 or 2, indicating the targeted ISA level.
  • -mbypass-cache, -mno-bypass-cache — force all load and store instructions to always bypass cache by using I/O variants of the instructions. The default is not to bypass the cache.
  • -mno-cache-volatile, -mcache-volatile — volatile memory access bypass the cache using the I/O variants of the load and store instructions. The default is not to bypass the cache.
  • -mno-fast-sw-div, -mfast-sw-div — do not use table-based fast divide for small numbers. The default is to use the fast divide at -O3 and above.
  • -mno-hw-mul, -mhw-mul, -mno-hw-mulx, -mhw-mulx, -mno-hw-div, -mhw-div — enable or disable emitting "mul", "mulx" and "div" family of instructions by the compiler. The default is to emit "mul" and not emit "div" and "mulx".
  • -mbmx, -mno-bmx, -mcdx, -mno-cdx — enable or disable generation of Nios II R2 BMX (bit manipulation) and CDX (code density) instructions. Enabling these instructions also requires -march=r2. Since these instructions are optional extensions to the R2 architecture, the default is not to emit them.
  • -mcustom-insn=N, -mno-custom-insn — each -mcustom-insn=N option enables use of a custom instruction with encoding N when generating code that uses insn. For example, -mcustom-fadds=253 generates custom instruction 253 for single-precision floating-point add operations instead of the default behavior of using a library call. custom instruction era ✨

The following values of insn are supported. Except as otherwise noted, floating-point operations are expected to be implemented with normal IEEE 754 semantics and correspond directly to the C operators or the equivalent GCC built-in functions.

Single-precision floating point:

  • fadds, fsubs, fdivs, fmuls — binary arithmetic operations.
  • fnegs — unary negation.
  • fabss — unary absolute value.
  • fcmpeqs, fcmpges, fcmpgts, fcmples, fcmplts, fcmpnes — comparison operations.
  • fmins, fmaxs — floating-point minimum and maximum. These instructions are only generated if -ffinite-math-only is specified.
  • fsqrts — unary square root operation.
  • fcoss, fsins, ftans, fatans, fexps, flogs — floating-point trigonometric and exponential functions. These instructions are only generated if -funsafe-math-optimizations is also specified.

Double-precision floating point:

  • faddd, fsubd, fdivd, fmuld — binary arithmetic operations.
  • fnegd — unary negation.
  • fabsd — unary absolute value.
  • fcmpeqd, fcmpged, fcmpgtd, fcmpled, fcmpltd, fcmpned — comparison operations.
  • fmind, fmaxd — double-precision minimum and maximum. These instructions are only generated if -ffinite-math-only is specified.
  • fsqrtd — unary square root operation.
  • fcosd, fsind, ftand, fatand, fexpd, flogd — double-precision trigonometric and exponential functions. These instructions are only generated if -funsafe-math-optimizations is also specified.

Conversions:

  • fextsd — conversion from single precision to double precision.
  • ftruncds — conversion from double precision to single precision.
  • fixsi, fixsu, fixdi, fixdu — converting from floating point into signed or unsigned integer types, with truncation toward zero 🫶
    • round — single-precision float → signed int, rounding to the nearest integer and breaking ties away from zero. This is literally what __builtin_lroundf does when you've got -fno-math-errno on.
    • floatis, floatus, floatid, floatud — going the other way: signed or unsigned integer types → floating-point types.

Also — and this is the part nobody tells you — all of these transfer instructions for internal registers X and Y must be provided for you to use any of the double-precision floating-point instructions. Custom instructions that take two double-precision source operands expect operand #1 in the 64-bit register X. The other operand (or the only operand, if it's a unary op) gets handed to the custom arithmetic instruction with the least significant half in source register src1 and the most significant half in src2. A custom instruction returning a double-precision result puts the most significant 32 bits in the destination register and the other half in 32-bit register Y. GCC auto-generates the necessary code sequences to write register X and/or read register Y whenever double-precision floating-point instructions are in play ✨

  • fwrx — write src1 into the least significant half of X, and src2 into the most significant half of X.
  • fwry — write src1 into Y.
  • frdxhi, frdxlo — read the most (or least, respectively) significant half of X and stash it in dest.
  • frdy — read the value of Y and store it into dest.
ngl you can get way more local control over Nios II custom instruction generation by using the target("custom-insn=N") and target("no-custom-insn") function attributes or pragmas 💅
  • -mcustom-fpu-cfg=name — turns on a predefined, named set of custom instruction encodings (peep -mcustom-insn above). Right now these are the sets that exist:
    • -mcustom-fpu-cfg=60-1 is equivalent to: -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -fsingle-precision-constant
    • -mcustom-fpu-cfg=60-2 is equivalent to: -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255 -fsingle-precision-constant
    • -mcustom-fpu-cfg=72-3 is equivalent to: -mcustom-floatus=243 -mcustom-fixsi=244 -mcustom-floatis=245 -mcustom-fcmpgts=246 -mcustom-fcmples=249 -mcustom-fcmpeqs=250 -mcustom-fcmpnes=251 -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255 -fsingle-precision-constant
    • -mcustom-fpu-cfg=fph2 is equivalent to: -mcustom-fabss=224 -mcustom-fnegs=225 -mcustom-fcmpnes=226 -mcustom-fcmpeqs=227 -mcustom-fcmpges=228 -mcustom-fcmpgts=229 -mcustom-fcmples=230 -mcustom-fcmplts=231 -mcustom-fmaxs=232 -mcustom-fmins=233 -mcustom-round=248 -mcustom-fixsi=249 -mcustom-floatis=250 -mcustom-fsqrts=251 -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255

Custom instruction assignments you hand over with individual -mcustom-insn= options override whatever -mcustom-fpu-cfg= said — doesn't matter what order the options sit in on the command line. Periodt 🎀

you can also get more local control over picking a FPU configuration with the target("custom-fpu-cfg=name") function attribute or pragma 🌸

The name fph2 is short for Nios II Floating Point Hardware 2 Component. Heads up though: the custom instructions enabled by -mcustom-fmins=233 and -mcustom-fmaxs=234 are only generated if -ffinite-math-only is specified. The custom instruction enabled by -mcustom-round=248 is only generated if -fno-math-errno is specified. And unlike the other configurations, -fsingle-precision-constant is not set here 😭


These extra -m options are available for the Altera Nios II ELF (bare-metal) target:

  • -mhal — link with HAL BSP. This suppresses linking with the GCC-provided C runtime startup and termination code, and is typically used together with -msys-crt0= to specify where the alternate startup code provided by the HAL BSP lives 💖
  • -msmallc — link against a limited version of the C library, -lsmallc, instead of Newlib.
  • -msys-crt0=startfile — startfile is the file name of the startfile (crt0) to use when linking. This option is only useful in conjunction with -mhal.
  • -msys-lib=systemlib — systemlib is the library name of the library that provides the low-level system calls the C library needs, e.g. "read" and "write". Typically used to link with a library provided by a HAL BSP 🧚

🌈 Nvidia PTX Options

These options are defined for Nvidia PTX:

  • -m64 — ignored, but kept around for backward compatibility. Only the 64-bit ABI is supported. It's giving "we left it on read" 💀
  • -march=architecture-string — generate code for the specified PTX ISA target architecture (e.g. sm_35). Valid architecture strings are sm_30, sm_35, sm_53, sm_70, sm_75 and sm_80. The default target architecture is sm_30.

This option sets the value of the preprocessor macro "__PTX_SM__" — for instance, for sm_35 it has the value 350 ✨

  • -misa=architecture-string — alias of -march=.
  • -march-map=architecture-string — pick the closest available -march= value that isn't more capable. For instance, for -march-map=sm_50 select -march=sm_35, and for -march-map=sm_53 select -march=sm_53. Lowkey the downgrade button 🔥
  • -mptx=version-string — generate code for the specified PTX ISA version (e.g. 7.0). Valid version strings include 3.1, 6.0, 6.3, and 7.0. The default PTX ISA version is 6.0, unless a higher version is required for the specified PTX ISA target architecture via option -march=.

This option sets the values of the preprocessor macros "__PTX_ISA_VERSION_MAJOR__" and "__PTX_ISA_VERSION_MINOR__" — for instance, for 3.1 the macros have the values 3 and 1, respectively.

  • -mmainkernel — link in code for a __main kernel. This is for stand-alone instead of offloading execution.
  • -moptimize — apply partitioned execution optimizations. This is the default when any level of optimization is selected 👑
  • -msoft-stack — generate code that does not use ".local" memory directly for stack storage. Instead, a per-warp stack pointer is maintained explicitly. This enables variable-length stack allocation (with variable-length arrays or "alloca"), and when global memory is used for underlying storage, it makes it possible to access automatic variables from other threads, or with atomic instructions. This code generation variant is used for OpenMP offloading, but the option is exposed on its own for the purpose of testing the compiler; to generate code suitable for linking into programs using OpenMP offloading, use option -mgomp 🦋
  • -muniform-simt — switch to the code generation variant that lets all threads in each warp execute, while maintaining memory state and side effects as if only one thread in each warp was active outside of OpenMP SIMD regions. All atomic operations and calls to runtime (malloc, free, vprintf) are conditionally executed (iff current lane index equals the master lane index), and the register being assigned is copied via a shuffle instruction from the master lane. Outside of SIMD regions lane 0 is the master; inside, each thread sees itself as the master. Shared memory array "int __nvptx_uni[]" stores all-zeros or all-ones bitmasks for each warp, indicating current mode (0 outside of SIMD regions). Each thread can bitwise-and the bitmask at position "tid.y" with current lane index to compute the master lane index 💅
  • -mgomp — generate code for use in OpenMP offloading: enables -msoft-stack and -muniform-simt options, and selects the corresponding multilib variant 🌟

🌸 OpenRISC Options

These options are defined for OpenRISC:

  • -mboard=name — configure a board-specific runtime. This gets passed to the linker for newlib board library linking. The default is "or1ksim".
  • -mnewlib — this option is ignored; it's purely for compatibility purposes. It used to select linker and preprocessor options for use with newlib. RIP to its job 🙈
  • -msoft-div, -mhard-div — select software or hardware divide ("l.div", "l.divu") instructions. The default is hardware divide.
  • -msoft-mul, -mhard-mul — select software or hardware multiply ("l.mul", "l.muli") instructions. The default is hardware multiply.
  • -msoft-float, -mhard-float — select software or hardware for floating point operations. The default is software.
  • -mdouble-float — when -mhard-float is selected, enables generation of double-precision floating point instructions. By default, functions from libgcc are used to do double-precision floating point operations.
  • -munordered-float — when -mhard-float is selected, enables generation of unordered floating point compare and set flag ("lf.sfun*") instructions. By default, functions from libgcc are used for unordered floating point compare and set flag operations.
  • -mcmov — enable generation of conditional move ("l.cmov") instructions. By default the equivalent is generated using set and branch.
  • -mror — enable generation of rotate right ("l.ror") instructions. By default, functions from libgcc are used for rotate right operations.
  • -mrori — enable generation of rotate right with immediate ("l.rori") instructions. By default, functions from libgcc are used for rotate right with immediate operations.
  • -msext — enable generation of sign extension ("l.ext*") instructions. By default, memory loads are used for sign extension.
  • -msfimm — enable generation of compare and set flag with immediate ("l.sf*i") instructions. By default, extra instructions get generated to store the immediate to a register first.
  • -mshftimm — enable generation of shift with immediate ("l.srai", "l.srli", "l.slli") instructions. By default, extra instructions get generated to store the immediate to a register first.
  • -mcmodel=small — generate OpenRISC code for the small model: the GOT is limited to 64k. This is the default model.
  • -mcmodel=large — generate OpenRISC code for the large model: the GOT may grow up to 4G in size 🫶

💜 PDP-11 Options

  • -mfpu — ok so this one turns on hardware FPP floating point, and it's the default, bestie 💅 (just so you know: FIS floating point on the PDP-11/40 is not supported, so don't come for me). This one implies -m45.
  • -msoft-float — nope, no hardware floating point for you. Do it in software, slay.
  • -mac0 — put floating-point results in ac0 (fr0 if you're speaking Unix assembler syntax 🎀).
  • -mno-ac0 — put floating-point results in memory instead. This is the default, lowkey.
  • -m40 — generate code for a PDP-11/40. Implies -msoft-float -mno-split.
  • -m45 — generate code for a PDP-11/45. This is the default one ✨.
  • -m10 — generate code for a PDP-11/10. Implies -msoft-float -mno-split.
  • -mint16, -mno-int32 — use 16-bit int. Default behavior, no cap.
  • -mint32, -mno-int16 — use 32-bit int. Big int energy.
  • -msplit — the target has split instruction and data space. Implies -m45.
  • -munix-asm — use Unix assembler syntax.
  • -mdec-asm — use DEC assembler syntax.
  • -mgnu-asm — use GNU assembler syntax. Default, obviously 💖.
  • -mlra — use the new LRA register allocator. By default the old "reload" allocator is the one doing the work, so this is you choosing chaos (the fresh kind).

🧚 picoChip Options

These -m options are the ones defined for picoChip implementations, and honestly? They're giving niche and iconic:

  • -mae=ae_type — set the instruction set, register set, and instruction scheduling parameters for array element type ae_type. The supported values for ae_type are ANY, MUL, and MAC. Breakdown time:
    • -mae=ANY selects a completely generic AE type 🌀. Code generated with this option runs on any of the other AE types. It's not as efficient as it'd be if you compiled for a specific AE type, and some types of operation (e.g., multiplication) do not work properly on all types of AE. So like… it travels well but it's not thriving everywhere.
    • -mae=MUL selects a MUL AE type. This is the most useful AE type for compiled code, and it's the default — main character energy 👑.
    • -mae=MAC selects a DSP-style MAC AE. Code compiled with this option may suffer from poor performance of byte (char) manipulation, since the DSP AE does not provide hardware support for byte load/stores. 😭 rough out here for the bytes.
  • -msymbol-as-address — lets the compiler directly use a symbol name as an address in a load/store instruction, without first loading it into a register. Typically this generates larger programs, which run faster than when the option isn't used. But the results vary from program to program, so it's left as a user option rather than being permanently enabled. iykyk 🫶
  • -mno-inefficient-warnings — disables warnings about the generation of inefficient code 💀. These warnings can pop up, for example, when compiling code that performs byte-level memory operations on the MAC AE type. The MAC AE has no hardware support for byte-level memory operations, so all byte load/stores must be synthesized from word load/store operations. That's inefficient, and a warning is generated to tell you that you should rewrite the code to avoid byte operations, or target an AE type that has the necessary hardware support. This option just turns those warnings off. 🙈

🌈 PowerPC Options

These are listed under

(that's genuinely it, bestie — the page just points you elsewhere, so go look 👀)


⭐ PRU Options

These command-line options are defined for the PRU target:

  • -minrt — link with a minimum runtime environment, with no support for static initializers and constructors. Using this can significantly reduce the size of the final ELF binary 🎀. > Beware: the compiler could still generate code with static initializers and constructors. It's up to the programmer to make sure the source program won't use those features. So like, that's on you, fr fr.
  • -mmcu=mcu — specify the PRU MCU variant to use. Check Newlib for the exact list of supported MCUs 💖.
  • -mno-relax — make GCC pass the --no-relax command-line option to the linker instead of the --relax option.
  • -mloop — allow (or do not allow) GCC to use the LOOP instruction.
  • -mabi=variant — specify the ABI variant to output code for. -mabi=ti selects the unmodified TI ABI, while -mabi=gnu selects a GNU variant that copes more naturally with certain GCC assumptions. These are the differences, bestie:
    • Function Pointer Size — TI ABI specifies that function (code) pointers are 16-bit, whereas GNU supports only 32-bit data and code pointers.
    • Optional Return Value Pointer — function return values larger than 64 bits are passed by using a hidden pointer as the first argument of the function. TI ABI, though, mandates that the pointer can be NULL in case the caller is not using the returned value. GNU always passes and expects a valid return value pointer.

The current -mabi=ti implementation simply raises a compile error when any of the above code constructs is detected 😭. As a consequence the standard C library cannot be built and it is omitted when linking with -mabi=ti.

Relaxation is a GNU feature and for safety reasons is disabled when using -mabi=ti. The TI toolchain does not emit relocations for QBBx instructions, so the GNU linker cannot adjust them when shortening adjacent LDI32 pseudo instructions. Not a vibe, but it is what it is.


🦋 RISC-V Options

These command-line options are defined for RISC-V targets:

  • -mbranch-cost=n — set the cost of branches to roughly n instructions.
  • -mplt, -mno-plt — when generating PIC code, do or don't allow the use of PLTs. Ignored for non-PIC. The default is -mplt ✨.
  • -mabi=ABI-string — specify integer and floating-point calling convention. ABI-string contains two parts: the size of integer types and the registers used for floating-point types. For example -march=rv64ifd -mabi=lp64d means that long and pointers are 64-bit (implicitly defining int to be 32-bit), and that floating-point values up to 64 bits wide are passed in F registers. Contrast this with -march=rv64ifd -mabi=lp64f, which still allows the compiler to generate code that uses the F and D extensions but only allows floating-point values up to 32 bits long to be passed in registers; or -march=rv64ifd -mabi=lp64, in which no floating-point arguments will be passed in registers. 🫶

The default for this argument is system dependent, and users who want a specific calling convention should specify one explicitly. The valid calling conventions are: ilp32, ilp32f, ilp32d, lp64, lp64f, and lp64d. Some calling conventions are impossible to implement on some ISAs: for example, -march=rv32if -mabi=ilp32d is invalid because the ABI requires 64-bit values be passed in F registers, but F registers are only 32 bits wide. There's also the ilp32e ABI that can only be used with the rv32e architecture. This ABI is not well specified at present, and is subject to change 👀 — so don't get too attached.

  • -mfdiv, -mno-fdiv — do or don't use hardware floating-point divide and square root instructions. This requires the F or D extensions for floating-point registers. The default is to use them if the specified architecture has these instructions 🔥.
  • -mdiv, -mno-div — do or don't use hardware instructions for integer division. This requires the M extension. The default is to use them if the specified architecture has these instructions.
  • -misa-spec=ISA-spec-string — specify the version of the RISC-V Unprivileged (formerly User-Level) ISA specification to produce code conforming to. The possibilities for ISA-spec-string are:
    • 2.2 — produce code conforming to version 2.2.
    • 20190608 — produce code conforming to version 20190608.
    • 20191213 — produce code conforming to version 20191213.

The default is -misa-spec=20191213 unless GCC has been configured with --with-isa-spec= specifying a different default version. 💅

  • -march=ISA-string — generate code for given RISC-V ISA (e.g. rv64im). ISA strings must be lower-case. Examples include rv64i, rv32g, rv32e, and rv32imaf.

When -march= is not specified, use the setting from -mcpu.

If both -march and -mcpu= are not specified, the default for this argument is system dependent, and users who want a specific architecture extensions should specify one explicitly. Like, just say what you want, bestie 🎀

  • -mcpu=processor-string — use architecture of and optimize the output for the given processor, specified by particular CPU name. Permissible values for this option are: sifive-e20, sifive-e21, sifive-e24, sifive-e31, sifive-e34, sifive-e76, sifive-s21, sifive-s51, sifive-s54, sifive-s76, sifive-u54, and sifive-u74. A whole roster 👑
  • -mtune=processor-string — optimize the output for the given processor, specified by microarchitecture or particular CPU name. Permissible values for this option are: rocket, sifive-3-series, sifive-5-series, sifive-7-series, size, and all valid options for -mcpu=.

When -mtune= is not specified, use the setting from -mcpu; the default is rocket if both are not specified.

The size choice is not intended for use by end-users 🙈. It's used when -Os is specified. It overrides the instruction cost info provided by -mtune=, but does not override the pipeline info. This helps reduce code size while still giving good performance — iconic multitasking.

  • -mpreferred-stack-boundary=num — attempt to keep the stack boundary aligned to a 2 raised to num byte boundary. If -mpreferred-stack-boundary is not specified, the default is 4 (16 bytes or 128-bits).
Warning: if you use this switch, then you must build all modules with the same value, including any libraries. This includes the system libraries and startup modules. No exceptions, no cap 💀
  • -msmall-data-limit=n — put global and static data smaller than n bytes into a special section (on some targets).
  • -msave-restore, -mno-save-restore — do or don't use smaller but slower prologue and epilogue code that uses library function calls. The default is to use fast inline prologues and epilogues ⚡
  • -mshorten-memrefs, -mno-shorten-memrefs — do or do not attempt to make more use of compressed load/store instructions by replacing a load/store of 'base register + large offset' with a new load/store of 'new base + small offset'. If the new base gets stored in a compressed register, then the new load/store can be compressed. Currently targets 32-bit integer load/stores only. 🌸
  • -mstrict-align, -mno-strict-align — do not or do generate unaligned memory accesses. The default is set depending on whether the processor we are optimizing for supports fast unaligned access or not. 🦋
  • -mcmodel=medlow — the medium-low code model, bestie. Your program and its statically defined symbols have to live inside a single 2 GiB address range, and they must sit between absolute addresses -2 GiB and +2 GiB. Programs can be statically or dynamically linked. This one's the default code model, so it's basically the main character 🎀
  • -mcmodel=medany — the medium-any code model. Now your program and its statically defined symbols just need to be within any single 2 GiB address range. Still statically or dynamically linkable, no drama.
Okay so heads up 💀 the code generated by medium-any is position-independent, but it is not guaranteed to function correctly when linked into position-independent executables or libraries. Not me warning you fr.
  • -mexplicit-relocs, -mno-exlicit-relocs — use (or don't use) assembler relocation operators when dealing with symbolic addresses. The alternative is assembler macros instead, which may limit optimization. Yes the second one is spelled -mno-exlicit-relocs in the page, that's not a typo on my end, iykyk 🙈
  • -mrelax, -mno-relax — take advantage of linker relaxations to reduce the number of instructions needed to materialize symbol addresses. Default? Take advantage. Slay, fewer instructions ✨
  • -memit-attribute, -mno-emit-attribute — emit (or don't emit) RISC-V attribute to record extra information into ELF objects. This feature needs at least binutils 2.32, no cap.
  • -malign-data=type — controls how GCC aligns variables and constants of array, structure, or union types. Supported values for type are xlen, which uses x register width as the alignment value, and natural, which uses natural alignment. xlen is the default 💅
  • -mbig-endian — generate big-endian code. This is the default when GCC is configured for a riscv64be-*-* or riscv32be-*-* target.
  • -mlittle-endian — generate little-endian code. This is the default when GCC is configured for a riscv64-*-* or riscv32-*-* but not a riscv64be-*-* or riscv32be-*-* target.
  • -mstack-protector-guard=guard, -mstack-protector-guard-reg=reg, -mstack-protector-guard-offset=offset — generate stack protection code using canary at guard. Supported locations are global for a global canary or tls for per-thread canary in the TLS block 🌸

With the latter choice, -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which register to use as base register for reading the canary, and from what offset from that base register. There is no default register or offset, as this is entirely for use within the Linux kernel. Like, it's not for you, it's for the kernel, respectfully 🫶


🌈 RL78 Options 🌈

  • -msim — links in additional target libraries to support operation within a simulator.
  • -mmul=none, -mmul=g10, -mmul=g13, -mmul=g14, -mmul=rl78 — specifies the type of hardware multiplication and division support to be used. The simplest is none, which uses software for both multiplication and division — that's the default. The g13 value is for the hardware multiply/divide peripheral found on the RL78/G13 (S2 core) targets. The g14 value selects the use of the multiplication and division instructions supported by the RL78/G14 (S3 core) parts. The value rl78 is an alias for g14 and the value mg10 is an alias for none. Little alias moment 💅

In addition, a C preprocessor macro is defined based on the setting of this option. Possible values are: __RL78_MUL_NONE__, __RL78_MUL_G13__ or __RL78_MUL_G14__.

  • -mcpu=g10, -mcpu=g13, -mcpu=g14, -mcpu=rl78 — specifies the RL78 core to target. The default is the G14 core, also known as an S3 core or just RL78. The G13 or S2 core does not have multiply or divide instructions — instead it uses a hardware peripheral for these operations. The G10 or S1 core does not have register banks, so it uses a different calling convention.

If this option is set it also selects the type of hardware multiply support to use, unless that gets overridden by an explicit -mmul=none option on the command line. So specifying -mcpu=g13 enables the use of the G13 hardware multiply peripheral, and specifying -mcpu=g10 disables the use of hardware multiplications altogether.

Note, although the RL78/G14 core is the default target, specifying -mcpu=g14 or -mcpu=rl78 on the command line does change the behavior of the toolchain, since it also enables G14 hardware multiply support. If these options are not specified on the command line then software multiplication routines will be used even though the code targets the RL78 core. That's for backwards compatibility with older toolchains which didn't have hardware multiply and divide support. Legacy vibes, honestly 😭

In addition, a C preprocessor macro is defined based on the setting of this option. Possible values are: __RL78_G10__, __RL78_G13__ or __RL78_G14__.

  • -mg10, -mg13, -mg14, -mrl78 — these are aliases for the corresponding -mcpu= option, provided for backwards compatibility.
  • -mallregs — allow the compiler to use all of the available registers. By default registers r24..r31 are reserved for use in interrupt handlers. With this option enabled, these registers can be used in ordinary functions as well. Letting them all out of the group chat 🔥
  • -m64bit-doubles, -m32bit-doubles — make the double data type be 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. The default is -m32bit-doubles.
  • -msave-mduc-in-interrupts, -mno-save-mduc-in-interrupts — specifies that interrupt handler functions should preserve the MDUC registers. This is only necessary if normal code might use the MDUC registers, for example because it performs multiplication and division operations. The default is to ignore the MDUC registers, since this makes the interrupt handlers faster. The target option -mg13 needs to be passed for this to work, as this feature is only available on the G13 target (S2 core). The MDUC registers will only be saved if the interrupt handler performs a multiplication or division operation or it calls another function. Conditional saving, we love efficiency ⭐

👑 IBM RS/6000 and PowerPC Options 👑

These -m options are defined for the IBM RS/6000 and PowerPC:

  • -mpowerpc-gpopt, -mno-powerpc-gpopt, -mpowerpc-gfxopt, -mno-powerpc-gfxopt, -mpowerpc64, -mno-powerpc64, -mmfcrf, -mno-mfcrf, -mpopcntb, -mno-popcntb, -mpopcntd, -mno-popcntd, -mfprnd, -mno-fprnd, -mcmpb, -mno-cmpb, -mhard-dfp, -mno-hard-dfp — you use these options to specify which instructions are available on the processor you're using. The default value of these options is determined when configuring GCC. Specifying the -mcpu=cpu_type overrides the specification of these options. We recommend you use the -mcpu=cpu_type option rather than the options listed above, bestie, it's just cleaner.

Specifying -mpowerpc-gpopt allows GCC to use the optional PowerPC architecture instructions in the General Purpose group, including floating-point square root. Specifying -mpowerpc-gfxopt allows GCC to use the optional PowerPC architecture instructions in the Graphics group, including floating-point select.

The -mmfcrf option allows GCC to generate the move from condition register field instruction implemented on the POWER4 processor and other processors that support the PowerPC V2.01 architecture. The -mpopcntb option allows GCC to generate the popcount and double-precision FP reciprocal estimate instruction implemented on the POWER5 processor and other processors that support the PowerPC V2.02 architecture. The -mpopcntd option allows GCC to generate the popcount instruction implemented on the POWER7 processor and other processors that support the PowerPC V2.06 architecture. The -mfprnd option allows GCC to generate the FP round to integer instructions implemented on the POWER5+ processor and other processors that support the PowerPC V2.03 architecture. The -mcmpb option allows GCC to generate the compare bytes instruction implemented on the POWER6 processor and other processors that support the PowerPC V2.05 architecture. The -mhard-dfp option allows GCC to generate the decimal floating-point instructions implemented on some POWER processors. So many processors, so many offers, they ate 💅

The -mpowerpc64 option allows GCC to generate the additional 64-bit instructions that are found in the full PowerPC64 architecture and to treat GPRs as 64-bit, doubleword quantities. GCC defaults to -mno-powerpc64.

  • -mcpu=cpu_type — set architecture type, register usage, and instruction scheduling parameters for machine type cpu_type. Supported values for cpu_type are 401, 403, 405, 405fp, 440, 440fp, 464, 464fp, 476, 476fp, 505, 601, 602, 603, 603e, 604, 604e, 620, 630, 740, 7400, 7450, 750, 801, 821, 823, 860, 970, 8540, a2, e300c2, e300c3, e500mc, e500mc64, e5500, e6500, ec603e, G3, G4, G5, titan, power3, power4, power5, power5+, power6, power6x, power7, power8, power9, power10, powerpc, powerpc64, powerpc64le, rs64, and native. Whole buffet of CPUs, ngl 🍓

-mcpu=powerpc, -mcpu=powerpc64, and -mcpu=powerpc64le specify pure 32-bit PowerPC (either endian), 64-bit big endian PowerPC, and 64-bit little endian PowerPC architecture machine types, with an appropriate, generic processor model assumed for scheduling purposes.

Specifying native as cpu type detects and selects the architecture option that corresponds to the host processor of the system performing the compilation. -mcpu=native has no effect if GCC doesn't recognize the processor 🙈

The other options specify a specific processor. Code generated under those options runs best on that processor, and may not run at all on others. Main character CPU energy, honestly.

The -mcpu options automatically enable or disable the following options:

-maltivec  -mfprnd  -mhard-float  -mmfcrf  -mmultiple -mpopcntb
-mpopcntd  -mpowerpc64 -mpowerpc-gpopt  -mpowerpc-gfxopt -mmulhw
-mdlmzb  -mmfpgpr  -mvsx -mcrypto  -mhtm  -mpower8-fusion
-mpower8-vector -mquad-memory  -mquad-memory-atomic  -mfloat128
-mfloat128-hardware -mprefixed -mpcrel -mmma -mrop-protect

The particular options set for any particular CPU varies between compiler versions, depending on what setting seems to produce optimal code for that CPU — it doesn't necessarily reflect the actual hardware's capabilities. If you wish to set an individual option to a particular value, you may specify it after the -mcpu option, like -mcpu=970 -mno-altivec. Order matters, bestie, put it after 💜

On AIX, the -maltivec and -mpowerpc64 options are not enabled or disabled by the -mcpu option rn, because AIX doesn't fully support these options yet 😭. You can still enable or disable them individually if you're sure it'll work in your environment, bestie 🫶.

  • -mtune=cpu_type — sets the instruction scheduling params for machine type cpu_type, but does not set the architecture type or register usage the way -mcpu=cpu_type does. Same cpu_type values for -mtune as for -mcpu ✨. If you specify both, the code generated uses the architecture and registers set by -mcpu, but the scheduling params set by -mtune. Periodt.
  • -mcmodel=small — generates PowerPC64 code for the small model: the TOC is limited to 64k 🎀.
  • -mcmodel=medium — generates PowerPC64 code for the medium model: the TOC and other static data may be up to a total of 4G in size. This is the default for 64-bit Linux 👑.
  • -mcmodel=large — generates PowerPC64 code for the large model: the TOC may be up to 4G in size. Other data and code is only limited by the 64-bit address space 🌈.
  • -maltivec, -mno-altivec — generate code that uses (does not use) AltiVec instructions, and also enable the use of built-in functions that allow more direct access to the AltiVec instruction set 💅. You may also need to set -mabi=altivec to adjust the current ABI with AltiVec ABI enhancements.

When -maltivec is used, the element order for AltiVec intrinsics such as vec_splat, vec_extract, and vec_insert match array element order corresponding to the endianness of the target 🦋. That is, element zero identifies the leftmost element in a vector register when targeting a big-endian platform, and identifies the rightmost element in a vector register when targeting a little-endian platform. iykyk.

  • -mvrsave, -mno-vrsave — generate VRSAVE instructions when generating AltiVec code ⭐.
  • -msecure-plt — generates code that allows ld and ld.so to build executables and shared libraries with non-executable .plt and .got sections 🔥. This is a PowerPC 32-bit SYSV ABI option.
  • -mbss-plt — generates code that uses a BSS .plt section that ld.so fills in, and requires .plt and .got sections that are both writable and executable 😳. This is a PowerPC 32-bit SYSV ABI option. (yes that's as spicy as it sounds, no cap)
  • -misel, -mno-isel — this switch enables or disables the generation of ISEL instructions 💫.
  • -mvsx, -mno-vsx — generate code that uses (does not use) vector/scalar (VSX) instructions, and also enable the use of built-in functions that allow more direct access to the VSX instruction set 🌸.
  • -mcrypto, -mno-crypto — enable (disable) the use of the built-in functions that allow direct access to the cryptographic instructions that were added in version 2.07 of the PowerPC ISA 🔐.
  • -mhtm, -mno-htm — enable (disable) the use of the built-in functions that allow direct access to the Hardware Transactional Memory (HTM) instructions that were added in version 2.07 of the PowerPC ISA 🧠.
  • -mpower8-fusion, -mno-power8-fusion — generate code that keeps (does not keeps — yes, that's what the original says, don't come for me 💀) some integer operations adjacent so that the instructions can be fused together on power8 and later processors.
  • -mpower8-vector, -mno-power8-vector — generate code that uses (does not use) the vector and scalar instructions that were added in version 2.07 of the PowerPC ISA ✨. Also enables the use of built-in functions that allow more direct access to the vector instructions.
  • -mquad-memory, -mno-quad-memory — generate code that uses (does not use) the non-atomic quad word memory instructions. The -mquad-memory option requires use of 64-bit mode ⚠️.
  • -mquad-memory-atomic, -mno-quad-memory-atomic — generate code that uses (does not use) the atomic quad word memory instructions. The -mquad-memory-atomic option requires use of 64-bit mode too ⚠️.
  • -mfloat128, -mno-float128 — enable/disable the __float128 keyword for IEEE 128-bit floating point, and use either software emulation for IEEE 128-bit floating point or hardware instructions 🎀.

The VSX instruction set (-mvsx) must be enabled to use the IEEE 128-bit floating point support. The IEEE 128-bit floating point is only supported on Linux 🐧.

The default for -mfloat128 is enabled on PowerPC Linux systems using the VSX instruction set, and disabled on other systems.

If you use the ISA 3.0 instruction set (-mpower9-vector or -mcpu=power9) on a 64-bit system, the IEEE 128-bit floating point support will also enable the generation of ISA 3.0 IEEE 128-bit floating point instructions 🔥. Otherwise, if you don't specify to generate ISA 3.0 instructions or you're targeting a 32-bit big endian system, IEEE 128-bit floating point will be done with software emulation 😭.

  • -mfloat128-hardware, -mno-float128-hardware — enable/disable using ISA 3.0 hardware instructions to support the __float128 data type ⚡.

The default for -mfloat128-hardware is enabled on PowerPC Linux systems using the ISA 3.0 instruction set, and disabled on other systems.

  • -m32, -m64 — generate code for 32-bit or 64-bit environments of Darwin and SVR4 targets (including GNU/Linux) 🦋. The 32-bit environment sets int, long and pointer to 32 bits and generates code that runs on any PowerPC variant. The 64-bit environment sets int to 32 bits and long and pointer to 64 bits, and generates code for PowerPC64, as for -mpowerpc64.
  • -mfull-toc, -mno-fp-in-toc, -mno-sum-in-toc, -mminimal-toc — modify generation of the TOC (Table Of Contents), which is created for every executable file 💅. The -mfull-toc option is selected by default. In that case, GCC allocates at least one TOC entry for each unique non-automatic variable reference in your program. GCC also places floating-point constants in the TOC. However, only 16,384 entries are available in the TOC 👀.

If you receive a linker error message that saying you have overflowed the available TOC space, you can reduce the amount of TOC space used with the -mno-fp-in-toc and -mno-sum-in-toc options 🫶. -mno-fp-in-toc prevents GCC from putting floating-point constants in the TOC and -mno-sum-in-toc forces GCC to generate code to calculate the sum of an address and a constant at run time instead of putting that sum into the TOC. You may specify one or both of these options. Each causes GCC to produce very slightly slower and larger code at the expense of conserving TOC space 😭.

If you still run out of space in the TOC even when you specify both of these options, specify -mminimal-toc instead. This option causes GCC to make only one TOC entry for every file. When you specify this option, GCC produces code that is slower and larger but which uses extremely little TOC space 💀. You may wish to use this option only on files that contain less frequently-executed code, bestie.

  • -maix64, -maix32 — enable 64-bit AIX ABI and calling convention: 64-bit pointers, 64-bit long type, and the infrastructure needed to support them 👑. Specifying -maix64 implies -mpowerpc64, while -maix32 disables the 64-bit ABI and implies -mno-powerpc64. GCC defaults to -maix32.
  • -mxl-compat, -mno-xl-compat — produce code that conforms more closely to IBM XL compiler semantics when using AIX-compatible ABI 🌸. Pass floating-point arguments to prototyped functions beyond the register save area (RSA) on the stack in addition to argument FPRs. Do not assume that most significant double in 128-bit long double value is properly rounded when comparing values and converting to double. Use XL symbol names for long double support routines.

The AIX calling convention was extended but not initially documented to handle an obscure K&R C case of calling a function that takes the address of its arguments with fewer arguments than declared 👀. IBM XL compilers access floating-point arguments that do not fit in the RSA from the stack when a subroutine is compiled without optimization. Because always storing floating-point arguments on the stack is inefficient and rarely needed, this option is not enabled by default and only is necessary when calling subroutines compiled by IBM XL compilers without optimization.

  • -mpe — support IBM RS/6000 SP Parallel Environment (PE) 🧚. Link an application written to use message passing with special startup code to enable the application to run. The system must have PE installed in the standard location (/usr/lpp/ppe.poe/), or the specs file must be overridden with the -specs= option to specify the appropriate directory location 📁. The Parallel Environment does not support threads, so the -mpe option and the -pthread option are incompatible ⚠️ (pick a lane, bestie).
  • -malign-natural, -malign-power — on AIX, 32-bit Darwin, and 64-bit PowerPC GNU/Linux, the option -malign-natural overrides the ABI-defined alignment of larger types, such as floating-point doubles, on their natural size-based boundary 🎀. The option -malign-power instructs GCC to follow the ABI-specified alignment rules. GCC defaults to the standard alignment defined in the ABI.

On 64-bit Darwin, natural alignment is the default, and -malign-power is not supported 🙈.

  • -msoft-float, -mhard-float — generate code that does not use (uses) the floating-point register set 💅. Software floating-point emulation is provided if you use the -msoft-float option, and pass the option to GCC when linking (don't forget the link step, she's important).
  • -mmultiple, -mno-multiple — generate code that uses (does not use) the load multiple word instructions and the store multiple word instructions ⭐. These instructions are generated by default on POWER systems, and not generated on PowerPC systems. Do not use -mmultiple on little-endian PowerPC systems, since those instructions do not work when the processor is in little-endian mode 💀. The exceptions are PPC740 and PPC750 which permit these instructions in little-endian mode 👑.
  • -mupdate, -mno-update — bestie, this one decides whether we generate code that uses (or doesn't use) the load/store instructions that update the base register to the address of the calculated memory location 🎀. These bad boys are generated by default. But heads up: if you go -mno-update, there's a tiny little window between when the stack pointer gets updated and when the address of the previous frame is stored — which means code that walks the stack frame across interrupts or signals may end up with corrupted data 😭. So like, know what you're doing.
  • -mavoid-indexed-addresses, -mno-avoid-indexed-addresses — generate code that tries to avoid (or not avoid) using indexed load or store instructions. Why would you avoid them? Because they can incur a performance penalty on Power6 processors in certain situations — like when you're stepping through large arrays that cross a 16M boundary 💀. This option is enabled by default when targeting Power6 and disabled otherwise. Slay, but contextually.
  • -mfused-madd, -mno-fused-madd — generate code that uses (doesn't use) the floating-point multiply and accumulate instructions ✨. These are generated by default if hardware floating point is used. Also plot twist: the machine-dependent -mfused-madd option is now mapped to the machine-independent -ffp-contract=fast option, and -mno-fused-madd is mapped to -ffp-contract=off. Glow-up era 🦋.
  • -mmulhw, -mno-mulhw — generate code that uses (doesn't use) the half-word multiply and multiply-accumulate instructions on the IBM 405, 440, 464 and 476 processors 💅. Generated by default when targeting those processors. No notes.
  • -mdlmzb, -mno-dlmzb — generate code that uses (doesn't use) the string-search dlmzb instruction on the IBM 405, 440, 464 and 476 processors 🌸. Also generated by default when targeting those processors. She's consistent.
  • -mno-bit-align, -mbit-align — on System V.4 and embedded PowerPC systems, do not (do) force structures and unions that contain bit-fields to be aligned to the base type of the bit-field 🎀. Example time, because yes: by default a structure containing nothing but 8 unsigned bit-fields of length 1 is aligned to a 4-byte boundary and has a size of 4 bytes. Use -mno-bit-align and that same structure is aligned to a 1-byte boundary and is 1 byte in size. Size difference is giving main character energy.
  • -mno-strict-align, -mstrict-align — on System V.4 and embedded PowerPC systems, do not (do) assume that unaligned memory references are handled by the system 🙈. That's it, that's the whole vibe check.
  • -mrelocatable, -mno-relocatable — generate code that allows (doesn't allow) a static executable to be relocated to a different address at run time ✨. A simple embedded PowerPC system loader should relocate the entire contents of .got2 and 4-byte locations listed in the .fixup section — a table of 32-bit addresses generated by this option 👑. For this to work, all objects linked together must be compiled with -mrelocatable or -mrelocatable-lib. Also -mrelocatable code aligns the stack to an 8-byte boundary.
  • -mrelocatable-lib, -mno-relocatable-lib — like -mrelocatable, -mrelocatable-lib generates a .fixup section to allow static executables to be relocated at run time 🦋. But — and this is the tea — -mrelocatable-lib does not use the smaller stack alignment of -mrelocatable. The good news: objects compiled with -mrelocatable-lib may be linked with objects compiled with any combination of the -mrelocatable options. Flexible queen 💅.
  • -mno-toc, -mtoc — on System V.4 and embedded PowerPC systems, do not (do) assume that register 2 contains a pointer to a global area pointing to the addresses used in the program 🌸. Register 2 erasure, respectfully.
  • -mlittle, -mlittle-endian — on System V.4 and embedded PowerPC systems, compile code for the processor in little-endian mode 🎀. And -mlittle-endian is literally the exact same thing as -mlittle. Same girl, different name.
  • -mbig, -mbig-endian — on System V.4 and embedded PowerPC systems, compile code for the processor in big-endian mode 💜. And yes, -mbig-endian is the same as -mbig. Twin icons 👯
  • -mdynamic-no-pic — on Darwin and Mac OS X systems, compile code so that it is not relocatable, but its external references are relocatable 🌈. The resulting code is suitable for applications, but not shared libraries. Read that twice bestie, it matters.
  • -msingle-pic-base — treat the register used for PIC addressing as read-only, rather than loading it in the prologue for each function 🙈. Fair warning: the runtime system is responsible for initializing this register with an appropriate value before execution begins. Not you, not gcc — the runtime. Periodt.
  • -mprioritize-restricted-insns=priority — this option controls the priority that is assigned to dispatch-slot restricted instructions during the second scheduling pass ✨. The argument priority takes the value 0, 1, or 2 to assign no, highest, or second-highest (respectively) priority to dispatch-slot restricted instructions. Cute little 0-1-2 situation.
  • -msched-costly-dep=dependence_type — controls which dependences are considered costly by the target during instruction scheduling 💅. The argument dependence_type takes one of these values:
    • no — no dependence is costly.
    • all — all dependences are costly.
    • true_store_to_load — a true dependence from store to load is costly.
    • store_to_load — any dependence from store to load is costly.
    • number — any dependence for which the latency is greater than or equal to number is costly.
  • -minsert-sched-nops=scheme — controls which NOP insertion scheme is used during the second scheduling pass 🦋. The argument scheme takes one of these values:
    • no — don't insert NOPs.
    • pad — pad with NOPs any dispatch group that has vacant issue slots, according to the scheduler's grouping.
    • regroup_exact — insert NOPs to force costly dependent insns into separate groups. Insert exactly as many NOPs as needed to force an insn to a new group, according to the estimated processor grouping 🎀.
    • number — insert NOPs to force costly dependent insns into separate groups. Insert number NOPs to force an insn to a new group.
  • -mcall-sysv — on System V.4 and embedded PowerPC systems, compile code using calling conventions that adhere to the March 1995 draft of the System V Application Binary Interface, PowerPC processor supplement 📜. This is the default unless you configured GCC using powerpc-*-eabiaix. Vintage but valid.
  • -mcall-sysv-eabi, -mcall-eabi — specify both -mcall-sysv and -meabi options. Bundle deal 💖.
  • -mcall-sysv-noeabi — specify both -mcall-sysv and -mno-eabi options. The other bundle 💀.
  • -mcall-aixdesc — on System V.4 and embedded PowerPC systems, compile code for the AIX operating system 👑
  • -mcall-linux — on System V.4 and embedded PowerPC systems, compile code for the Linux-based GNU system 🐧
  • -mcall-freebsd — on System V.4 and embedded PowerPC systems, compile code for the FreeBSD operating system 😈
  • -mcall-netbsd — on System V.4 and embedded PowerPC systems, compile code for the NetBSD operating system 🎗️
  • -mcall-openbsd — on System V.4 and embedded PowerPC systems, compile code for the OpenBSD operating system 🐡
  • -mtraceback=traceback_type — select the type of traceback table 🌸. Valid values for traceback_type are full, part, and no. Three options, no chaos.
  • -maix-struct-return — return all structures in memory (as specified by the AIX ABI) 📦
  • -msvr4-struct-return — return structures smaller than 8 bytes in registers (as specified by the SVR4 ABI) ✨
  • -mabi=abi-type — extend the current ABI with a particular extension, or remove such extension 💅. Valid values are: altivec, no-altivec, ibmlongdouble, ieeelongdouble, elfv1, elfv2, and for AIX: vec-extabi, vec-default. That's the whole menu, memorize it iykyk.
  • -mabi=ibmlongdouble — change the current ABI to use IBM extended-precision long double 🧚. Ngl this is not likely to work if your system defaults to using IEEE extended-precision long double 😭. And if you change the long double type from IEEE extended-precision, the compiler will issue a warning unless you use the -Wno-psabi option. Also requires -mlong-double-128 to be enabled. So many conditions, but ok.
  • -mabi=ieeelongdouble — change the current ABI to use IEEE extended-precision long double 🦋. Mirror image, same caveat: not likely to work if your system defaults to using IBM extended-precision long double 😭. If you change the long double type from IBM extended-precision, the compiler will issue a warning unless you use the -Wno-psabi option. Requires -mlong-double-128 to be enabled. Symmetry ate 💅
  • -mabi=elfv1 — change the current ABI to use the ELFv1 ABI 👑. This is the default ABI for big-endian PowerPC 64-bit Linux. Warning time: overriding the default ABI requires special system support and is likely to fail in spectacular ways 🔥💀. Spectacular. Ways.
  • -mabi=elfv2 — change the current ABI to use the ELFv2 ABI ✨. This is the default ABI for little-endian PowerPC 64-bit Linux. Same warning, same drama: overriding the default ABI requires special system support and is likely to fail in spectacular ways 😭🔥
Bestie the elfv1/elfv2 warning is not a cute little suggestion, it's a "your build will explode in a beautiful and educational manner" situation. Respect the default 🫶
  • -mgnu-attribute, -mno-gnu-attribute — emit .gnu_attribute assembly directives to set tag/value pairs in a .gnu.attributes section that specify ABI variations in function parameters or return values 🎀. Very metadata of her.
  • -mprototype, -mno-prototype — on System V.4 and embedded PowerPC systems, assume that all calls to variable argument functions are properly prototyped 🌸. Otherwise (the -mno-prototype world), the compiler must insert an instruction before every non-prototyped call to set or clear bit 6 of the condition code register (CR) to indicate whether floating-point values are passed in the floating-point registers in case the function takes variable arguments 🙈. With -mprototype, only calls to prototyped variable argument functions set or clear the bit. Bit 6 stays booked and busy.
  • -msim — on embedded PowerPC systems, assume that the startup module is called sim-crt0.o and that the standard C libraries are libsim.a and libc.a 🧚. This is the default for powerpc-*-eabisim configurations. Sim girl summer.
  • -mmvme — on embedded PowerPC systems, assume that the startup module is called crt0.o and the standard C libraries are libmvme.a and libc.a 💜
  • -mads — on embedded PowerPC systems, assume that the startup module is called crt0.o and the standard C libraries are libads.a and libc.a 🌈
  • -myellowknife — on embedded PowerPC systems, assume that the startup module is called crt0.o and the standard C libraries are libyk.a and libc.a 🍓 (iconic name, no notes)
  • -mvxworks — on System V.4 and embedded PowerPC systems, specify that you are compiling for a VxWorks system ⭐
  • -memb — On embedded PowerPC systems, this sets the PPC_EMB bit in the ELF flags header to say “yes bestie, eabi extended relocations are being used.” ✨
  • -meabi, -mno-eabi — On System V.4 and embedded PowerPC systems, GCC does (or with -mno-eabi does not) adhere to the Embedded Applications Binary Interface (EABI), which is a set of modifications to the System V.4 specifications. Picking -meabi means the stack gets aligned to an 8-byte boundary, a function __eabi gets called from main to set up the EABI environment, and the -msdata option can use both r2 and r13 to point to two separate small data areas. Picking -mno-eabi means the stack is aligned to a 16-byte boundary, no EABI initialization function is called from main, and -msdata only uses r13 to point to a single small data area. The -meabi option is on by default if you configured GCC using one of the powerpc*-*-eabi* options. 🫶
  • -msdata=eabi — On System V.4 and embedded PowerPC systems, put small initialized const global and static data in the .sdata2 section, which is pointed to by register r2. Put small initialized non-const global and static data in the .sdata section, which is pointed to by register r13. Put small uninitialized global and static data in the .sbss section, which sits adjacent to .sdata. The -msdata=eabi option is incompatible with the -mrelocatable option, and it also sets the -memb option. 💅
  • -msdata=sysv — On System V.4 and embedded PowerPC systems, put small global and static data in the .sdata section, which is pointed to by register r13. Put small uninitialized global and static data in the .sbss section, which is adjacent to .sdata. The -msdata=sysv option is incompatible with the -mrelocatable option. 🦋
  • -msdata=default, -msdata — On System V.4 and embedded PowerPC systems, if -meabi is used, compile code the same as -msdata=eabi; otherwise compile code the same as -msdata=sysv. ✨
  • -msdata=data — On System V.4 and embedded PowerPC systems, put small global data in the .sdata section. Put small uninitialized global data in the .sbss section. But do not use register r13 to address small data. This is the default behavior unless other -msdata options are used. 👑
  • -msdata=none, -mno-sdata — On embedded PowerPC systems, put all initialized global and static data in the .data section, and all uninitialized data in the .bss section. Clean and simple, no small-data drama. 🌸
  • -mreadonly-in-sdata — Put read-only objects in the .sdata section as well. This is the default. 🎀
  • -mblock-move-inline-limit=num — Inline all block moves (such as calls to memcpy or structure copies) that are less than or equal to num bytes. The minimum value for num is 32 bytes on 32-bit targets and 64 bytes on 64-bit targets. The default value is target-specific. 🔥
  • -mblock-compare-inline-limit=num — Generate non-looping inline code for all block compares (such as calls to memcmp or structure compares) that are less than or equal to num bytes. If num is 0, all inline expansion (non-loop and loop) of block compare is disabled. The default value is target-specific. 💖
  • -mblock-compare-inline-loop-limit=num — Generate an inline expansion using loop code for all block compares that are less than or equal to num bytes, but greater than the limit for non-loop inline block compare expansion. If the block length is not constant, at most num bytes will be compared before memcmp is called to compare the remainder of the block. The default value is target-specific. 🧚
  • -mstring-compare-inline-limit=num — Compare at most num string bytes with inline code. If the difference or the end of the string is not found at the end of the inline compare, a call to strcmp or strncmp will take care of the rest of the comparison. The default is 64 bytes. 🌈
  • -G num — On embedded PowerPC systems, put global and static items less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS section. By default, num is 8. The -G num switch is also passed to the linker, and all modules should be compiled with the same -G num value. No chaotic mismatches, bestie. 💀
  • -mregnames, -mno-regnames — On System V.4 and embedded PowerPC systems, do (or do not) emit register names in the assembly language output using symbolic forms. 🎀
  • -mlongcall, -mno-longcall — By default, assume that all calls are far away, so a longer and more expensive calling sequence is required. This is required for calls farther than 32 megabytes (33,554,432 bytes) from the current location. A short call is generated if the compiler knows the call cannot be that far away. This setting can be overridden by the shortcall function attribute, or by #pragma longcall(0).

Some linkers are capable of detecting out-of-range calls and generating glue code on the fly. On these systems, long calls are unnecessary and generate slower code. As of this writing, the AIX linker can do this, as can the GNU linker for PowerPC/64. It is planned to add this feature to the GNU linker for 32-bit PowerPC systems as well.

On PowerPC64 ELFv2 and 32-bit PowerPC systems with newer GNU linkers, GCC can generate long calls using an inline PLT call sequence (see -mpltseq). PowerPC with -mbss-plt and PowerPC64 ELFv1 (big-endian) do not support inline PLT calls.

On Darwin/PPC systems, #pragma longcall generates jbsr callee, L42, plus a branch island (glue code). The two target addresses represent the callee and the branch island. The Darwin/PPC linker prefers the first address and generates bl callee if the PPC bl instruction reaches the callee directly; otherwise, the linker generates bl L42 to call the branch island. The branch island is appended to the body of the calling function; it computes the full 32-bit address of the callee and jumps to it.

On Mach-O (Darwin) systems, this option directs the compiler to emit the glue for every direct call, and the Darwin linker decides whether to use or discard it.

In the future, GCC may ignore all longcall specifications when the linker is known to generate glue. 🔮

  • -mpltseq, -mno-pltseq — Implement (or do not implement) -fno-plt and long calls using an inline PLT call sequence that supports lazy linking and long calls to functions in dlopen'd shared libraries. Inline PLT calls are only supported on PowerPC64 ELFv2 and 32-bit PowerPC systems with newer GNU linkers, and are enabled by default if the support is detected when configuring GCC, and, in the case of 32-bit PowerPC, if GCC is configured with --enable-secureplt. -mpltseq code and -mbss-plt 32-bit PowerPC relocatable objects may not be linked together. 🚨
  • -mtls-markers, -mno-tls-markers — Mark (or do not mark) calls to __tls_get_addr with a relocation specifying the function argument. The relocation allows the linker to reliably associate the function call with argument setup instructions for TLS optimization, which in turn allows GCC to better schedule the sequence. 🧵
  • -mrecip, -mno-recip — This option enables use of the reciprocal estimate and reciprocal square root estimate instructions with additional Newton-Raphson steps to increase precision instead of doing a divide or square root and divide for floating-point arguments. You should use the -ffast-math option when using -mrecip (or at least -funsafe-math-optimizations, -ffinite-math-only, -freciprocal-math and -fno-trapping-math). Note that while the throughput of the sequence is generally higher than the throughput of the non-reciprocal instruction, the precision of the sequence can be decreased by up to 2 ulp (i.e. the inverse of 1.0 equals 0.99999994) for reciprocal square roots. 😭
  • -mrecip=opt — This option controls which reciprocal estimate instructions may be used. opt is a comma-separated list of options, which may be preceded by a ! to invert the option:
    • all — Enable all estimate instructions.
    • default — Enable the default instructions, equivalent to -mrecip.
    • none — Disable all estimate instructions, equivalent to -mno-recip.
    • div — Enable the reciprocal approximation instructions for both single and double precision.
    • divf — Enable the single-precision reciprocal approximation instructions.
    • divd — Enable the double-precision reciprocal approximation instructions.
    • rsqrt — Enable the reciprocal square root approximation instructions for both single and double precision.
    • rsqrtf — Enable the single-precision reciprocal square root approximation instructions.
    • rsqrtd — Enable the double-precision reciprocal square root approximation instructions.

So, for example, -mrecip=all,!rsqrtd enables all of the reciprocal estimate instructions, except for the FRSQRTE, XSRSQRTEDP, and XVRSQRTEDP instructions which handle the double-precision reciprocal square root calculations. 💅

  • -mrecip-precision, -mno-recip-precision — Assume (or do not assume) that the reciprocal estimate instructions provide higher-precision estimates than is mandated by the PowerPC ABI. Selecting -mcpu=power6, -mcpu=power7 or -mcpu=power8 automatically selects -mrecip-precision. The double-precision square root estimate instructions are not generated by default on low-precision machines, since they do not provide an estimate that converges after three steps. 🌟
  • -mveclibabi=type — okay so this one tells GCC which ABI type to use for vectorizing intrinsics with an external library, and bestie, the only type supported at present is mass — that’s IBM’s Mathematical Acceleration Subsystem (MASS) libraries, used for vectorizing intrinsics via external libraries. GCC currently emits calls to acosd2, acosf4, acoshd2, acoshf4, asind2, asinf4, asinhd2, asinhf4, atan2d2, atan2f4, atand2, atanf4, atanhd2, atanhf4, cbrtd2, cbrtf4, cosd2, cosf4, coshd2, coshf4, erfcd2, erfcf4, erfd2, erff4, exp2d2, exp2f4, expd2, expf4, expm1d2, expm1f4, hypotd2, hypotf4, lgammad2, lgammaf4, log10d2, log10f4, log1pd2, log1pf4, log2d2, log2f4, logd2, logf4, powd2, powf4, sind2, sinf4, sinhd2, sinhf4, sqrtd2, sqrtf4, tand2, tanf4, tanhd2, and tanhf4 when generating code for power7. Both -ftree-vectorize and -funsafe-math-optimizations must also be enabled, and the MASS libraries must be specified at link time. 💖
  • -mfriz, -mno-friz — generate (or do not generate) the friz instruction when -funsafe-math-optimizations is used to optimize rounding of floating-point values to 64-bit integer and back to floating point. The friz instruction does not return the same value if the floating-point number is too large to fit in an integer. 🫶
  • -mpointers-to-nested-functions, -mno-pointers-to-nested-functions — generate (or do not generate) code to load up the static chain register (r11) when calling through a pointer on AIX and 64-bit Linux systems where a function pointer points to a 3-word descriptor giving the function address, TOC value to be loaded in register r2, and static chain value to be loaded in register r11. The -mpointers-to-nested-functions is on by default. You cannot call through pointers to nested functions or pointers to functions compiled in other languages that use the static chain if you use -mno-pointers-to-nested-functions. 😭
  • -msave-toc-indirect, -mno-save-toc-indirect — generate (or do not generate) code to save the TOC value in the reserved stack location in the function prologue if the function calls through a pointer on AIX and 64-bit Linux systems. If the TOC value is not saved in the prologue, it is saved just before the call through the pointer. The -mno-save-toc-indirect option is the default. ✨
  • -mcompat-align-parm, -mno-compat-align-parm — generate (or do not generate) code to pass structure parameters with a maximum alignment of 64 bits, for compatibility with older versions of GCC.

Older versions of GCC (prior to 4.9.0) incorrectly did not align a structure parameter on a 128-bit boundary when that structure contained a member requiring 128-bit alignment. This is corrected in more recent versions of GCC. This option may be used to generate code that is compatible with functions compiled with older versions of GCC.

The -mno-compat-align-parm option is the default.

  • -mstack-protector-guard=guard, -mstack-protector-guard-reg=reg, -mstack-protector-guard-offset=offset, -mstack-protector-guard-symbol=symbol — generate stack protection code using a canary at guard. Supported locations are global for global canary or tls for per-thread canary in the TLS block (the default with GNU libc version 2.4 or later).

With the latter choice the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which register to use as base register for reading the canary, and from what offset from that base register. The default for those is as specified in the relevant ABI. -mstack-protector-guard-symbol=symbol overrides the offset with a symbol reference to a canary in the TLS block. 💅

  • -mpcrel, -mno-pcrel — generate (or do not generate) pc-relative addressing. The -mpcrel option requires that the medium code model (-mcmodel=medium) and prefixed addressing (-mprefixed) options are enabled. 🦋
  • -mprefixed, -mno-prefixed — generate (or do not generate) addressing modes using prefixed load and store instructions. The -mprefixed option requires that the option -mcpu=power10 (or later) is enabled.
  • -mmma, -mno-mma — generate (or do not generate) the MMA instructions. The -mma option requires that the option -mcpu=power10 (or later) is enabled. 🌸
  • -mrop-protect, -mno-rop-protect — generate (or do not generate) ROP protection instructions when the target processor supports them. Currently this option disables the shrink-wrap optimization (-fshrink-wrap). 💀
  • -mprivileged, -mno-privileged — generate (or do not generate) code that will run in privileged state.
  • -mblock-ops-unaligned-vsx, -mno-block-ops-unaligned-vsx — generate (or do not generate) unaligned vsx loads and stores for inline expansion of memcpy and memmove. 🌈

🌸 RX Options 🌸

These command-line options are defined for RX targets:

  • -m64bit-doubles, -m32bit-doubles — make the double data type be 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. The default is -m32bit-doubles. Note that RX floating-point hardware only works on 32-bit values, which is why the default is -m32bit-doubles. 💖
  • -fpu, -nofpu — enables (-fpu) or disables (-nofpu) the use of RX floating-point hardware. The default is enabled for the RX600 series and disabled for the RX200 series.

Floating-point instructions are only generated for 32-bit floating-point values, however, so the FPU hardware is not used for doubles if the -m64bit-doubles option is used.

Note: If the -fpu option is enabled then -funsafe-math-optimizations is also enabled automatically. This is because the RX FPU instructions are themselves unsafe. 😭
  • -mcpu=name — selects the type of RX CPU to be targeted. Currently three types are supported, the generic RX600 and RX200 series hardware and the specific RX610 CPU. The default is RX600.

The only difference between RX600 and RX610 is that the RX610 does not support the MVTIPL instruction.

The RX200 series does not have a hardware floating-point unit and so -nofpu is enabled by default when this type is selected. 🎀

  • -mbig-endian-data, -mlittle-endian-data — store data (but not code) in the big-endian format. The default is -mlittle-endian-data, i.e. to store data in the little-endian format.
  • -msmall-data-limit=N — specifies the maximum size in bytes of global and static variables which can be placed into the small data area. Using the small data area can lead to smaller and faster code, but the size of area is limited and it is up to the programmer to ensure that the area does not overflow. Also when the small data area is used one of the RX’s registers (usually r13) is reserved for use pointing to this area, so it is no longer available for use by the compiler. This could result in slower and/or larger code if variables are pushed onto the stack instead of being held in this register.

Note, common variables (variables that have not been initialized) and constants are not placed into the small data area as they are assigned to other sections in the output executable.

The default value is zero, which disables this feature. Note, this feature is not enabled by default with higher optimization levels (-O2 etc) because of the potentially detrimental effects of reserving a register. It is up to the programmer to experiment and discover whether this feature is of benefit to their program. See the description of the -mpid option for a description of how the actual register to hold the small data area pointer is chosen. 🧚

  • -msim, -mno-sim — use the simulator runtime. The default is to use the libgloss board-specific runtime.
  • -mas100-syntax, -mno-as100-syntax — when generating assembler output use a syntax that is compatible with Renesas’s AS100 assembler. This syntax can also be handled by the GAS assembler, but it has some restrictions so it is not generated by default. ✨
  • -mmax-constant-size=N — specifies the maximum size, in bytes, of a constant that can be used as an operand in a RX instruction. Although the RX instruction set does allow constants of up to 4 bytes in length to be used in instructions, a longer value equates to a longer instruction. Thus in some circumstances it can be beneficial to restrict the size of constants that are used in instructions. Constants that are too big are instead placed into a constant pool and referenced via register indirection.

The value N can be between 0 and 4. A value of 0 (the default) or 4 means that constants of any size are allowed.

  • -mrelax — enable linker relaxation. Linker relaxation is a process whereby the linker attempts to reduce the size of a program by finding shorter versions of various instructions. Disabled by default. 💜
  • -mint-register=N — specify the number of registers to reserve for fast interrupt handler functions. The value N can be between 0 and 4. A value of 1 means that register r13 is reserved for the exclusive use of fast interrupt handlers. A value of 2 reserves r13 and r12. A value of 3 reserves r13, r12 and r11, and a value of 4 reserves r13 through r10. A value of 0, the default, does not reserve any registers. 🫶
  • -msave-acc-in-interrupts — specifies that interrupt handler functions should preserve the accumulator register. This is only necessary if normal code might use the accumulator register, for example because it performs 64-bit multiplications. The default is to ignore the accumulator as this makes the interrupt handlers faster. 💅
  • -mpid, -mno-pid — enables the generation of position independent data. When enabled any access to constant data is done via an offset from a base address held in a register. This allows the location of constant data to be determined at run time without requiring the executable to be relocated, which is a benefit to embedded applications with tight memory constraints. Data that can be modified is not affected by this option.

Note, using this feature reserves a register, usually r13, for the constant data base address. This can result in slower and/or larger code, especially in complicated functions. 🌟

Okay so picking up right in the middle of the register saga: the actual register chosen to hold the constant data base address depends on whether -msmall-data-limit and/or -mint-register command-line options are enabled. Starting with register r13 and proceeding downwards, registers are allocated first to satisfy the requirements of -mint-register, then -mpid and finally -msmall-data-limit. So yes, it is literally possible for the small data area register to be r8 if both -mint-register=4 and -mpid are specified on the command line. 🫶

By default this feature is not enabled. The default can be restored via the -mno-pid command-line option. 💅

  • -mno-warn-multiple-fast-interrupts / -mwarn-multiple-fast-interrupts — Prevents GCC from issuing a warning message if it finds more than one fast interrupt handler when it is compiling a file. The default is to issue a warning for each extra fast interrupt handler found, as the RX only supports one such interrupt. 😭
  • -mallow-string-insns / -mno-allow-string-insns — Enables or disables the use of the string manipulation instructions SMOVF, SCMPU, SMOVB, SMOVU, SUNTIL, SWHILE and also the RMPA instruction. These instructions may prefetch data, which is not safe to do if accessing an I/O register. (See section 12.2.7 of the RX62N Group User's Manual for more information). ✨

The default is to allow these instructions, but it is not possible for GCC to reliably detect all circumstances where a string instruction might be used to access an I/O register, so their use cannot be disabled automatically. Instead it is reliant upon the programmer to use the -mno-allow-string-insns option if their program accesses I/O space. 🎀

When the instructions are enabled GCC defines the C preprocessor symbol __RX_ALLOW_STRING_INSNS__, otherwise it defines the symbol __RX_DISALLOW_STRING_INSNS__. 🦋

  • -mjsr / -mno-jsr — Use only (or not only) JSR instructions to access functions. This option can be used when code size exceeds the range of BSR instructions. Note that -mno-jsr does not mean to not use JSR but instead means that any type of branch may be used. 💀
Note: The generic GCC command-line option -ffixed-reg has special significance to the RX port when used with the interrupt function attribute. This attribute indicates a function intended to process fast interrupts. GCC ensures that it only uses the registers r10, r11, r12 and/or r13 and only provided that the normal use of the corresponding registers have been restricted via the -ffixed-reg or -mint-register command-line options. 👑

🌈 S/390 and zSeries Options 🌈

These are the -m options defined for the S/390 and zSeries architecture. Main character architecture energy fr fr. 🎀

  • -mhard-float / -msoft-float — Use (do not use) the hardware floating-point instructions and registers for floating-point operations. When -msoft-float is specified, functions in libgcc.a are used to perform floating-point operations. When -mhard-float is specified, the compiler generates IEEE floating-point instructions. This is the default. 🔥
  • -mhard-dfp / -mno-hard-dfp — Use (do not use) the hardware decimal-floating-point instructions for decimal-floating-point operations. When -mno-hard-dfp is specified, functions in libgcc.a are used to perform decimal-floating-point operations. When -mhard-dfp is specified, the compiler generates decimal-floating-point hardware instructions. This is the default for -march=z9-ec or higher. ✨
  • -mlong-double-64 / -mlong-double-128 — These switches control the size of long double type. A size of 64 bits makes the long double type equivalent to the double type. This is the default. 💖
  • -mbackchain / -mno-backchain — Store (do not store) the address of the caller's frame as backchain pointer into the callee's stack frame. A backchain may be needed to allow debugging using tools that do not understand DWARF call frame information. When -mno-packed-stack is in effect, the backchain pointer is stored at the bottom of the stack frame; when -mpacked-stack is in effect, the backchain is placed into the topmost word of the 96/160 byte register save area. 🫶

In general, code compiled with -mbackchain is call-compatible with code compiled with -mno-backchain; however, use of the backchain for debugging purposes usually requires that the whole binary is built with -mbackchain. Note that the combination of -mbackchain, -mpacked-stack and -mhard-float is not supported. In order to build a linux kernel use -msoft-float. 😭

The default is to not maintain the backchain. 💅

  • -mpacked-stack / -mno-packed-stack — Use (do not use) the packed stack layout. When -mno-packed-stack is specified, the compiler uses all fields of the 96/160 byte register save area only for their default purpose; unused fields still take up stack space. When -mpacked-stack is specified, register save slots are densely packed at the top of the register save area; unused space is reused for other purposes, allowing for more efficient use of the available stack space. However, when -mbackchain is also in effect, the topmost word of the save area is always used to store the backchain, and the return address register is always saved two words below the backchain. 🌸

As long as the stack frame backchain is not used, code generated with -mpacked-stack is call-compatible with code generated with -mno-packed-stack. Note that some non-FSF releases of GCC 2.95 for S/390 or zSeries generated code that uses the stack frame backchain at run time, not just for debugging purposes. Such code is not call-compatible with code compiled with -mpacked-stack. Also, note that the combination of -mbackchain, -mpacked-stack and -mhard-float is not supported. In order to build a linux kernel use -msoft-float. 🦋

The default is to not use the packed stack layout. ⭐

  • -msmall-exec / -mno-small-exec — Generate (or do not generate) code using the bras instruction to do subroutine calls. This only works reliably if the total executable size does not exceed 64k. The default is to use the basr instruction instead, which does not have this limitation. 💀
  • -m64 / -m31 — When -m31 is specified, generate code compliant to the GNU/Linux for S/390 ABI. When -m64 is specified, generate code compliant to the GNU/Linux for zSeries ABI. This allows GCC in particular to generate 64-bit instructions. For the s390 targets, the default is -m31, while the s390x targets default to -m64. 👑
  • -mzarch / -mesa — When -mzarch is specified, generate code using the instructions available on z/Architecture. When -mesa is specified, generate code using the instructions available on ESA/390. Note that -mesa is not possible with -m64. When generating code compliant to the GNU/Linux for S/390 ABI, the default is -mesa. When generating code compliant to the GNU/Linux for zSeries ABI, the default is -mzarch. 🌈
  • -mhtm / -mno-htm — The -mhtm option enables a set of builtins making use of instructions available with the transactional execution facility introduced with the IBM zEnterprise EC12 machine generation S/390 System z Built-in Functions. -mhtm is enabled by default when using -march=zEC12. 🔥
  • -mvx / -mno-vx — When -mvx is specified, generate code using the instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option changes the ABI for some vector type values with regard to alignment and calling conventions. In case vector type values are being used in an ABI-relevant context a GAS .gnu_attribute command will be added to mark the resulting binary with the ABI used. -mvx is enabled by default when using -march=z13. ✨
  • -mzvector / -mno-zvector — The -mzvector option enables vector language extensions and builtins using instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option adds support for vector to be used as a keyword to define vector type variables and arguments. vector is only available when GNU extensions are enabled. It will not be expanded when requesting strict standard compliance e.g. with -std=c99. In addition to the GCC low-level builtins -mzvector enables a set of builtins added for compatibility with AltiVec-style implementations like Power and Cell. In order to make use of these builtins the header file vecintrin.h needs to be included. -mzvector is disabled by default. 🦋
  • -mmvcle / -mno-mvcle — Generate (or do not generate) code using the mvcle instruction to perform block moves. When -mno-mvcle is specified, use a mvc loop instead. This is the default unless optimizing for size. 🎀
  • -mdebug / -mno-debug — Print (or do not print) additional debug information when compiling. The default is to not print debug information. 💅
  • -march=cpu-type — Generate code that runs on cpu-type, which is the name of a system representing a certain processor type. Possible values for cpu-type are z900/arch5, z990/arch6, z9-109, z9-ec/arch7, z10/arch8, z196/arch9, zEC12, z13/arch11, z14/arch12, z15/arch13, z16/arch14, and native. 💖

The default is -march=z900. ⭐

Specifying native as cpu type can be used to select the best architecture option for the host processor. -march=native has no effect if GCC does not recognize the processor. 🫶

  • -mtune=cpu-type — Tune to cpu-type everything applicable about the generated code, except for the ABI and the set of available instructions. The list of cpu-type values is the same as for -march. The default is the value used for -march. 🌸
  • -mtpf-trace / -mno-tpf-trace — Generate code that adds (does not add) in TPF OS specific branches to trace routines in the operating system. This option is off by default, even when compiling for the TPF OS. 😭
  • -mtpf-trace-skip / -mno-tpf-trace-skip — Generate code that changes (does not change) the default branch targets enabled by -mtpf-trace to point to specialized trace routines providing the ability of selectively skipping function trace entries for the TPF OS. This option is off by default, even when compiling for the TPF OS and specifying -mtpf-trace. 💀
  • -mfused-madd, -mno-fused-madd — turns on (or off) the floating-point multiply-and-accumulate instructions. Ngl, these get generated by default whenever hardware floating point is being used, so you only need these if you're being picky about it 💅
  • -mwarn-framesize=framesize — yells at you (warning-style) if the current function's frame size goes over the framesize you gave. Important vibe check: this is a compile-time check, so it literally doesn't have to be a real problem when the program actually runs. It's here to sniff out functions that most probably cause a stack overflow, which makes it super useful in environments with a limited stack size — e.g. the linux kernel 👑
  • -mwarn-dynamicstack — throws a warning if the function calls alloca or uses dynamically-sized arrays. Which is generally a bad idea when your stack size is limited, just saying 🫣
  • -mstack-guard=stack-guard, -mstack-size=stack-size — if you hand these over, the S/390 back end drops extra instructions into the function prologue that trigger a trap if the stack size is stack-guard bytes above stack-size (and remember, bestie: the stack on S/390 grows downward 💀). If you skip -mstack-guard, the smallest power of 2 that's larger than the frame size of the compiled function gets chosen for you. These exist to help debug stack overflow problems, and the extra emitted code causes only a little overhead — so you can also run them in production-like systems without greater performance degradation. Rules though, fr fr: the values you give have to be exact powers of 2, and stack-size has to be greater than stack-guard without exceeding 64k. For efficiency, the extra code assumes the stack starts at an address aligned to the value given by stack-size. And -mstack-guard can only be used in conjunction with -mstack-size. no solo missions 🙅‍♀️
  • -mhotpatch=pre-halfwords,post-halfwords — with the hotpatch option enabled, a "hot-patching" function prologue is generated for all functions in the compilation unit. The function label gets prepended with the given number of two-byte NOP instructions (pre-halfwords, maximum 1000000). After the label, 2 * post-halfwords bytes are appended, using the largest NOP-like instructions the architecture allows (maximum 1000000). If both arguments are zero, hotpatching is disabled. And you can override this for individual functions with the hotpatch attribute ✨

🎯 Score Options 🎯

These options are defined for Score implementations:

  • -meb — compile code for big-endian mode. This is the default 👑
  • -mel — compile code for little-endian mode.
  • -mnhwloop — disable generation of bcnz instructions.
  • -muls — enable generation of unaligned load and store instructions.
  • -mmac — enable the use of multiply-accumulate instructions. Disabled by default.
  • -mscore5 — specify the SCORE5 as the target architecture.
  • -mscore5u — specify the SCORE5U of the target architecture.
  • -mscore7 — specify the SCORE7 as the target architecture. This is the default ⭐
  • -mscore7d — specify the SCORE7D as the target architecture.

🌸 SH Options 🌸

These -m options are defined for the SH implementations:

  • -m1 — generate code for the SH1.
  • -m2 — generate code for the SH2.
  • -m2e — generate code for the SH2e.
  • -m2a-nofpu — generate code for the SH2a without FPU, or for a SH2a-FPU in such a way that the floating-point unit is not used.
  • -m2a-single-only — generate code for the SH2a-FPU, in such a way that no double-precision floating-point operations are used.
  • -m2a-single — generate code for the SH2a-FPU assuming the floating-point unit is in single-precision mode by default.
  • -m2a — generate code for the SH2a-FPU assuming the floating-point unit is in double-precision mode by default.
  • -m3 — generate code for the SH3.
  • -m3e — generate code for the SH3e.
  • -m4-nofpu — generate code for the SH4 without a floating-point unit.
  • -m4-single-only — generate code for the SH4 with a floating-point unit that only supports single-precision arithmetic.
  • -m4-single — generate code for the SH4 assuming the floating-point unit is in single-precision mode by default.
  • -m4 — generate code for the SH4.
  • -m4-100 — generate code for SH4-100.
  • -m4-100-nofpu — generate code for SH4-100 in such a way that the floating-point unit is not used.
  • -m4-100-single — generate code for SH4-100 assuming the floating-point unit is in single-precision mode by default.
  • -m4-100-single-only — generate code for SH4-100 in such a way that no double-precision floating-point operations are used.
  • -m4-200 — generate code for SH4-200.
  • -m4-200-nofpu — generate code for SH4-200 in such a way that the floating-point unit is not used.
  • -m4-200-single — generate code for SH4-200 assuming the floating-point unit is in single-precision mode by default.
  • -m4-200-single-only — generate code for SH4-200 in such a way that no double-precision floating-point operations are used.
  • -m4-300 — generate code for SH4-300.
  • -m4-300-nofpu — generate code for SH4-300 in such a way that the floating-point unit is not used.
  • -m4-300-single — generate code for SH4-300 in such a way that no double-precision floating-point operations are used.
  • -m4-300-single-only — generate code for SH4-300 in such a way that no double-precision floating-point operations are used.
  • -m4-340 — generate code for SH4-340 (no MMU, no FPU).
  • -m4-500 — generate code for SH4-500 (no FPU). Passes -isa=sh4-nofpu to the assembler.
  • -m4a-nofpu — generate code for the SH4al-dsp, or for a SH4a in such a way that the floating-point unit is not used.
  • -m4a-single-only — generate code for the SH4a, in such a way that no double-precision floating-point operations are used.
  • -m4a-single — generate code for the SH4a assuming the floating-point unit is in single-precision mode by default.
  • -m4a — generate code for the SH4a.
  • -m4al — same as -m4a-nofpu, except that it implicitly passes -dsp to the assembler. Heads up: GCC doesn't generate any DSP instructions at the moment 🫠
  • -mb — compile code for the processor in big-endian mode.
  • -ml — compile code for the processor in little-endian mode.
  • -mdalign — align doubles at 64-bit boundaries. Watch out though: this changes the calling conventions, and thus some functions from the standard C library do not work unless you recompile it first with -mdalign 😭
  • -mrelax — shorten some address references at link time, when possible; uses the linker option -relax.
  • -mbigtable — use 32-bit offsets in switch tables. The default is to use 16-bit offsets.
  • -mbitops — enable the use of bit manipulation instructions on SH2A.
  • -mfmovd — enable the use of the instruction fmovd. Check -mdalign for alignment constraints 👀
  • -mrenesas — comply with the calling conventions defined by Renesas.
  • -mno-renesas — comply with the calling conventions defined for GCC before the Renesas conventions were available. This option is the default for all targets of the SH toolchain.
  • -mnomacsave — mark the MAC register as call-clobbered, even if -mrenesas is given.
  • -mieee, -mno-ieee — control the IEEE compliance of floating-point comparisons, which affects the handling of cases where the result of a comparison is unordered. By default -mieee is implicitly enabled. If -ffinite-math-only is enabled, -mno-ieee is implicitly set, which results in faster floating-point greater-equal and less-equal comparisons. The implicit settings can be overridden by specifying either -mieee or -mno-ieee.
  • -minline-ic_invalidate — inline code to invalidate instruction cache entries after setting up nested function trampolines. This option has no effect if -musermode is in effect and the selected code generation option (e.g. -m4) does not allow the use of the icbi instruction. If the selected code generation option does not allow the use of the icbi instruction, and -musermode is not in effect, the inlined code manipulates the instruction cache address array directly with an associative write. And that's the spicy part: this not only requires privileged mode at run time, but it also fails if the cache line had been mapped via the TLB and has become unmapped 💀
  • -misize — dump instruction size and location in the assembly code.
  • -mpadstruct — this option is deprecated. It pads structures to multiple of 4 bytes, which is incompatible with the SH ABI.
deprecated AND ABI-incompatible? she's giving legacy chaos, bestie. tread carefully 🙈
  • -matomic-model=model — sets the model of atomic operations and additional parameters as a comma separated list. For details on the atomic built-in functions see __atomic Builtins. The following models and parameters are supported:
    • none — disable compiler generated atomic sequences and emit library calls for atomic operations. This is the default if the target is not sh*-*-linux*.
    • soft-gusa — generate GNU/Linux compatible gUSA software atomic sequences for the atomic built-in functions. The generated atomic sequences require additional support from the interrupt/exception handling code of the system and are only suitable for SH3* and SH4* single-core systems. This option is enabled by default when the target is sh*-*-linux* and SH3* or SH4*. When the target is SH4A, this option also partially utilizes the hardware atomic instructions movli.l and movco.l to create more efficient code, unless strict is specified.
    • soft-tcb — generate software atomic sequences that use a variable in the thread control block. This is a variation of the gUSA sequences which can also be used on SH1* and SH2* targets. The generated atomic sequences require additional support from the interrupt/exception handling code of the system and are only suitable for single-core systems. When using this model, the gbr-offset= parameter has to be specified as well 🫶
  • soft-imask — makes software atomic sequences that briefly turn off interrupts by setting SR.IMASK = 1111 ✨ this model only works when the program is running in privileged mode and it's only suitable for single-core systems. You don't need extra support from the system's interrupt/exception handling code. It's on by default when the target is sh*-*-linux* and it's SH1* or SH2* 💅
  • hard-llcs — hardware atomic sequences using only the movli.l and movco.l instructions 🎀 this one's only available on SH4A and it's suitable for multi-core systems. Since the hardware instructions only support 32-bit atomic variable access, accessing 8- or 16-bit variables is emulated with 32-bit accesses. Code compiled with this is also compatible with other software atomic model interrupt/exception handling systems if it runs on an SH4A system. This model doesn't need extra support from the system's interrupt/exception handling code 👑
  • gbr-offset= — this parameter sets the offset, in bytes, of the variable in the thread control block structure that the generated atomic sequences should use when the soft-tcb model has been selected 🦋 for other models it's just ignored, no biggie. The value you give must be an integer multiple of four and in the range 0-1020 ⭐
  • strict — blocks mixed usage of multiple atomic models, even compatible ones, and makes the compiler generate atomic sequences of the specified model only 🔥
  • -mtas — generates the tas.b opcode for __atomic_test_and_set 💀 heads up though: depending on your particular hardware and software configuration this can degrade overall performance, because of the operand cache line flushes that the tas.b instruction implies 😭 and on multi-core SH4A processors tas.b must be used with caution since it can cause data corruption for certain cache configurations 🙈
  • -mprefergot — when generating position-independent code, emit function calls using the Global Offset Table instead of the Procedure Linkage Table 🌈
  • -musermode, -mno-usermode — don't allow (allow) the compiler to generate privileged mode code 🫶 specifying -musermode also implies -mno-inline-ic_invalidate if the inlined code wouldn't work in user mode. -musermode is the default when the target is sh*-*-linux*. If the target is SH1* or SH2* then -musermode has no effect, because there's literally no user mode to speak of 💀
  • *-multcost=number* — sets the cost to assume for a multiply insn 💜
  • *-mdiv=strategy* — sets the division strategy used for integer division operations. strategy can be one of these icons:
    • call-div1 — calls a library function that uses the single-step division instruction div1 to do the operation 🎀 division by zero calculates an unspecified result and does not trap. This is the default except for SH4, SH2A and SHcompact.
    • call-fp — calls a library function that does the operation in double precision floating point ✨ division by zero causes a floating-point exception 😭 this is the default for SHcompact with FPU. Specifying this for targets that don't have a double precision FPU defaults to call-div1.
    • call-table — calls a library function that uses a lookup table for small divisors and the div1 instruction with case distinction for larger divisors 🌸 division by zero calculates an unspecified result and does not trap. This is the default for SH4. Specifying this for targets that don't have dynamic shift instructions defaults to call-div1.

When no division strategy has been specified, the default strategy gets picked based on the current target 👑 for SH2A the default strategy is to use the divs and divu instructions instead of library function calls.

  • -maccumulate-outgoing-args — reserve space once for outgoing arguments in the function prologue instead of around every single call 💖 generally a glow-up for both performance and size. Also needed for unwinding so the stack frame doesn't change around conditional code.
  • *-mdivsi3_libfunc=name* — sets the name of the library function used for 32-bit signed division to name 🦋 this only affects the name used in the call division strategies, and the compiler still expects the same sets of input/output/clobbered registers as if this option weren't there, no cap.
  • *-mfixed-range=register-range* — generates code treating the given register range as fixed registers ⭐ a fixed register is one the register allocator can't use, which is super useful when compiling kernel code. A register range is two registers separated by a dash, and you can specify multiple register ranges separated by a comma.
  • *-mbranch-cost=num* — assume num is the cost for a branch instruction 🔥 higher numbers make the compiler try to generate more branch-free code if it can. If you don't specify it, the value is picked depending on the processor type you're compiling for.
  • -mzdcbranch, -mno-zdcbranch — assume (don't assume) that zero displacement conditional branch instructions bt and bf are fast 💅 with -mzdcbranch the compiler prefers zero displacement branch code sequences. Enabled by default when generating code for SH4 and SH4A, and you can explicitly disable it with -mno-zdcbranch.
  • -mcbranch-force-delay-slot — forces use of delay slots for conditional branches, which stuffs the delay slot with a nop if no suitable instruction can be found 💀 by default this is disabled. You can enable it to work around hardware bugs like the ones found in the original SH7055 🙈
  • -mfused-madd, -mno-fused-madd — generate code that uses (doesn't use) the floating-point multiply and accumulate instructions 🎀 these are generated by default if hardware floating point is used. The machine-dependent -mfused-madd option is now mapped to the machine-independent -ffp-contract=fast option, and -mno-fused-madd is mapped to -ffp-contract=off.
  • -mfsca, -mno-fsca — allow or disallow the compiler to emit the fsca instruction for sine and cosine approximations ✨ -mfsca must be used together with -funsafe-math-optimizations. It's enabled by default when generating code for SH4A. Using -mno-fsca disables sine and cosine approximations even if -funsafe-math-optimizations is in effect.
  • -mfsrra, -mno-fsrra — allow or disallow the compiler to emit the fsrra instruction for reciprocal square root approximations 🌸 -mfsrra must be used together with -funsafe-math-optimizations and -ffinite-math-only. It's enabled by default when generating code for SH4A. Using -mno-fsrra disables reciprocal square root approximations even if -funsafe-math-optimizations and -ffinite-math-only are in effect.
  • -mpretend-cmove — prefer zero-displacement conditional branches for conditional move instruction patterns 🦋 this can give you faster code on the SH4 processor.
  • -mfdpic — generate code using the FDPIC ABI 👑

☀️ Solaris 2 Options

These -m options are supported on Solaris 2, bestie:

  • -mclear-hwcap — -mclear-hwcap tells the compiler to remove the hardware capabilities generated by the Solaris assembler 🎀 this is only necessary when object files use ISA extensions not supported by the current machine, but then check at runtime whether or not to use them.
  • -mimpure-text — -mimpure-text, used in addition to -shared, tells the compiler not to pass -z text to the linker when linking a shared object 💅 with this option you can link position-dependent code into a shared object, iconic.

-mimpure-text suppresses the relocations remain against allocatable but non-writable sections linker error message 😭 but the necessary relocations trigger copy-on-write, and the shared object isn't actually shared across processes. Instead of using -mimpure-text, you should compile all source code with -fpic or -fPIC ⭐

These switches are supported in addition to the above on Solaris 2:

  • -pthreads — this is a synonym for -pthread 🫶

🌞 SPARC Options

These -m options are supported on the SPARC:

  • -mno-app-regs, -mapp-regs — specify -mapp-regs to generate output using the global registers 2 through 4, which the SPARC SVR4 ABI reserves for applications 🔥 like global register 1, each global register 2 through 4 is then treated as an allocable register that's clobbered by function calls. This is the default.

To be fully SVR4 ABI-compliant at the cost of some performance loss, specify -mno-app-regs 💅 you should compile libraries and system software with this option.

  • -mflat, -mno-flat — with -mflat, the compiler doesn't generate save/restore instructions and uses a "flat" or single register window model 🦋 this model is compatible with the regular register window model. The local registers and the input registers (0--5) are still treated as "call-saved" registers and get saved on the stack as needed.

With -mno-flat (the default), the compiler generates save/restore instructions (except for leaf functions) — this is the normal operating mode ✨

  • -mfpu, -mhard-float — generate output containing floating-point instructions 💖 this is the default.
  • -mno-fpu, -msoft-float — generate output containing library calls for floating point 🎀 warning: the requisite libraries are not available for all SPARC targets 😭 normally the facilities of the machine's usual C compiler are used, but that can't be done directly in cross-compilation. You have to make your own arrangements to provide suitable library functions for cross-compilation. The embedded targets sparc-*-aout and sparclite-*-* do provide software floating-point support, so that's something.

-msoft-float changes the calling convention in the output file 💀 so it's only useful if you compile all of a program with this option. In particular, you need to compile libgcc.a, the library that comes with GCC, with -msoft-float for this to work.

  • -mhard-quad-float — generate output containing quad-word (long double) floating-point instructions 👑
  • -msoft-quad-float — bestie, this makes the compiler spit out library calls for quad-word (long double) floating-point instructions instead of, y'know, actual instructions. The functions it calls are the ones specified in the SPARC ABI. And yes, this is the default. 💅

Okay so real talk: as of this writing, there are no SPARC implementations that have hardware support for the quad-word floating-point instructions. Like, none. Zero. They all invoke a trap handler for one of these instructions, and then the trap handler emulates the effect of the instruction. And because of that trap handler overhead? It's much slower than just calling the ABI library routines. Which is exactly why -msoft-quad-float is the default. It's giving "the slow way is actually the fast way" 😭

  • -mno-unaligned-doubles, -munaligned-doubles — assume that doubles have 8-byte alignment. That's the default, no cap. ✨

With -munaligned-doubles, GCC assumes doubles have 8-byte alignment only if they're contained in another type, or if they have an absolute address. Otherwise, it assumes they've got 4-byte alignment. Specifying this option avoids some rare compatibility problems with code generated by other compilers. Why isn't it the default? Because it results in a performance loss, especially for floating-point code. 🙈

  • -muser-mode, -mno-user-mode — don't generate code that can only run in supervisor mode. This is relevant only for the "casa" instruction emitted for the LEON3 processor. This is the default. 🎀
  • -mfaster-structs, -mno-faster-structs — with -mfaster-structs, the compiler assumes that structures should have 8-byte alignment. This enables the use of pairs of "ldd" and "std" instructions for copies in structure assignment, in place of twice as many "ld" and "st" pairs. BUT — and this is a big but — the use of this changed alignment directly violates the SPARC ABI. 🫢 So it's intended only for use on targets where the developer acknowledges that their resulting code is not directly in line with the rules of the ABI. Like, you're choosing to be a little lawless. I respect it, but know what you're doing.
  • -mstd-struct-return, -mno-std-struct-return — with -mstd-struct-return, the compiler generates checking code in functions returning structures or unions to detect size mismatches between the two sides of function calls, as per the 32-bit ABI. Very much a vibe check on your struct sizes. 👑

The default is -mno-std-struct-return. This option has no effect in 64-bit mode.

  • -mlra, -mno-lra — enable Local Register Allocation. This is the default for SPARC since GCC 7, so -mno-lra needs to be passed to get old Reload. Nostalgia trip, but make it registers. 💀
  • *-mcpu=cpu_type* — set the instruction set, register set, and instruction scheduling parameters for machine type cpu_type. Supported values for cpu_type are v7, cypress, v8, supersparc, hypersparc, leon, leon3, leon3v7, leon5, sparclite, f930, f934, sparclite86x, sparclet, tsc701, v9, ultrasparc, ultrasparc3, niagara, niagara2, niagara3, niagara4, niagara7 and m8.

Native Solaris and GNU/Linux toolchains also support the value native, which selects the best architecture option for the host processor. -mcpu=native has no effect if GCC does not recognize the processor. (Rude of it, honestly.)

Default instruction scheduling parameters are used for values that select an architecture and not an implementation. These are v7, v8, sparclite, sparclet, v9.

Here's the whole girliepop roster of each supported architecture and their supported implementations:

v7 — cypress, leon3v7

v8 — supersparc, hypersparc, leon, leon3, leon5

sparclite — f930, f934, sparclite86x

sparclet — tsc701

v9 — ultrasparc, ultrasparc3, niagara, niagara2, niagara3, niagara4, niagara7, m8

By default (unless configured otherwise), GCC generates code for the V7 variant of the SPARC architecture. With -mcpu=cypress, the compiler additionally optimizes it for the Cypress CY7C602 chip, as used in the SPARCStation/SPARCServer 3xx series. This is also appropriate for the older SPARCStation 1, 2, IPX etc. Vintage icon behavior 🎀

With -mcpu=v8, GCC generates code for the V8 variant of the SPARC architecture. The only difference from V7 code is that the compiler emits the integer multiply and integer divide instructions which exist in SPARC-V8 but not in SPARC-V7. With -mcpu=supersparc, the compiler additionally optimizes it for the SuperSPARC chip, as used in the SPARCStation 10, 1000 and 2000 series.

With -mcpu=sparclite, GCC generates code for the SPARClite variant of the SPARC architecture. This adds the integer multiply, integer divide step and scan ("ffs") instructions which exist in SPARClite but not in SPARC-V7. With -mcpu=f930, the compiler additionally optimizes it for the Fujitsu MB86930 chip, which is the original SPARClite, with no FPU. With -mcpu=f934, the compiler additionally optimizes it for the Fujitsu MB86934 chip, which is the more recent SPARClite with FPU. ✨

With -mcpu=sparclet, GCC generates code for the SPARClet variant of the SPARC architecture. This adds the integer multiply, multiply/accumulate, integer divide step and scan ("ffs") instructions which exist in SPARClet but not in SPARC-V7. With -mcpu=tsc701, the compiler additionally optimizes it for the TEMIC SPARClet chip.

With -mcpu=v9, GCC generates code for the V9 variant of the SPARC architecture. This adds 64-bit integer and floating-point move instructions, 3 additional floating-point condition code registers and conditional move instructions. With -mcpu=ultrasparc, the compiler additionally optimizes it for the Sun UltraSPARC I/II/IIi chips. With -mcpu=ultrasparc3, the compiler additionally optimizes it for the Sun UltraSPARC III/III+/IIIi/IIIi+/IV/IV+ chips. With -mcpu=niagara, the compiler additionally optimizes it for Sun UltraSPARC T1 chips. With -mcpu=niagara2, the compiler additionally optimizes it for Sun UltraSPARC T2 chips. With -mcpu=niagara3, the compiler additionally optimizes it for Sun UltraSPARC T3 chips. With -mcpu=niagara4, the compiler additionally optimizes it for Sun UltraSPARC T4 chips. With -mcpu=niagara7, the compiler additionally optimizes it for Oracle SPARC M7 chips. With -mcpu=m8, the compiler additionally optimizes it for Oracle M8 chips. That's a whole era of silicon, bestie 🌈

  • -mtune=cpu_type — set the instruction scheduling parameters for machine type cpu_type, but *do not set the instruction set or register set that the option -mcpu=cpu_type* does. It's the scheduler-only version, iykyk.

The same values for -mcpu=cpu_type can be used for -mtune=cpu_type, but the only useful values are those that select a particular CPU implementation. Those are cypress, supersparc, hypersparc, leon, leon3, leon3v7, leon5, f930, f934, sparclite86x, tsc701, ultrasparc, ultrasparc3, niagara, niagara2, niagara3, niagara4, niagara7 and m8. With native Solaris and GNU/Linux toolchains, native can also be used.

  • -mv8plus, -mno-v8plus — with -mv8plus, GCC generates code for the SPARC-V8+ ABI. The difference from the V8 ABI is that the global and out registers are considered 64 bits wide. This is enabled by default on Solaris in 32-bit mode for all SPARC-V9 processors. Glow-up for your registers 💅
  • -mvis, -mno-vis — with -mvis, GCC generates code that takes advantage of the UltraSPARC Visual Instruction Set extensions. The default is -mno-vis.
  • -mvis2, -mno-vis2 — with -mvis2, GCC generates code that takes advantage of version 2.0 of the UltraSPARC Visual Instruction Set extensions. The default is -mvis2 when targeting a cpu that supports such instructions, such as UltraSPARC-III and later. Setting -mvis2 also sets -mvis. Chain reaction, cute ✨
  • -mvis3, -mno-vis3 — with -mvis3, GCC generates code that takes advantage of version 3.0 of the UltraSPARC Visual Instruction Set extensions. The default is -mvis3 when targeting a cpu that supports such instructions, such as niagara-3 and later. Setting -mvis3 also sets -mvis2 and -mvis.
  • -mvis4, -mno-vis4 — with -mvis4, GCC generates code that takes advantage of version 4.0 of the UltraSPARC Visual Instruction Set extensions. The default is -mvis4 when targeting a cpu that supports such instructions, such as niagara-7 and later. Setting -mvis4 also sets -mvis3, -mvis2 and -mvis.
  • -mvis4b, -mno-vis4b — with -mvis4b, GCC generates code that takes advantage of version 4.0 of the UltraSPARC Visual Instruction Set extensions, plus the additional VIS instructions introduced in the Oracle SPARC Architecture 2017. The default is -mvis4b when targeting a cpu that supports such instructions, such as m8 and later. Setting -mvis4b also sets -mvis4, -mvis3, -mvis2 and -mvis. The whole friend group gets invited 🫶
  • -mcbcond, -mno-cbcond — with -mcbcond, GCC generates code that takes advantage of the UltraSPARC Compare-and-Branch-on-Condition instructions. The default is -mcbcond when targeting a CPU that supports such instructions, such as Niagara-4 and later.
  • -mfmaf, -mno-fmaf — with -mfmaf, GCC generates code that takes advantage of the UltraSPARC Fused Multiply-Add Floating-point instructions. The default is -mfmaf when targeting a CPU that supports such instructions, such as Niagara-3 and later. Fused multiply-add ate, honestly 🔥
  • -mfsmuld, -mno-fsmuld — with -mfsmuld, GCC generates code that takes advantage of the Floating-point Multiply Single to Double (FsMULd) instruction. The default is -mfsmuld when targeting a CPU supporting the architecture versions V8 or V9 with FPU except -mcpu=leon.
  • -mpopc, -mno-popc — with -mpopc, GCC generates code that takes advantage of the UltraSPARC Population Count instruction. The default is -mpopc when targeting a CPU that supports such an instruction, such as Niagara-2 and later.
  • -msubxc, -mno-subxc — with -msubxc, GCC generates code that takes advantage of the UltraSPARC Subtract-Extended-with-Carry instruction. The default is -msubxc when targeting a CPU that supports such an instruction, such as Niagara-7 and later.
  • -mfix-at697f — enable the documented workaround for the single erratum of the Atmel AT697F processor (which corresponds to erratum #13 of the AT697E processor). Fixing the one (1) oopsie 💅
  • -mfix-ut699 — enable the documented workarounds for the floating-point errata and the data cache nullify errata of the UT699 processor. Two for one, we love to see it.
  • -mfix-ut700 — enable the documented workaround for the back-to-back store errata of the UT699E/UT700 processor.
  • -mfix-gr712rc — enable the documented workaround for the back-to-back store errata of the GR712RC processor.

These -m options are supported in addition to the above on SPARC-V9 processors in 64-bit environments:


  • -m32, -m64 — bestie, this is your “how big is the world” switch. -m32 generates code for a 32-bit environment, which sets int, long and pointer to 32 bits. -m64 generates code for a 64-bit environment, where int is still 32 bits but long and pointer get bumped up to 64 bits. ✨
  • -mcmodel=which — set the code model to one of these, and yes you literally have to pick one:
    • medlow — the Medium/Low code model: 64-bit addresses, and programs must be linked in the low 32 bits of memory. Programs can be statically or dynamically linked.
    • medmid — the Medium/Middle code model: 64-bit addresses, programs must be linked in the low 44 bits of memory, the text and data segments must be less than 2GB in size, and the data segment must be located within 2GB of the text segment.
    • medany — the Medium/Anywhere code model: 64-bit addresses, programs may be linked anywhere in memory, the text and data segments must be less than 2GB in size, and the data segment must be located within 2GB of the text segment.
    • embmedany — the Medium/Anywhere code model for embedded systems: 64-bit addresses, the text and data segments must be less than 2GB in size, both starting anywhere in memory (determined at link time). The global register %g4 points to the base of the data segment. Programs are statically linked and PIC is not supported. So if you need PIC, this is not the vibe — plan accordingly 💀
  • -mmemory-model=mem-model — sets the memory model in force on the processor to one of:
    • default — the default memory model for the processor and operating system.
    • rmo — Relaxed Memory Order.
    • pso — Partial Store Order.
    • tso — Total Store Order.
    • sc — Sequential Consistency.

These memory models are formally defined in Appendix D of the SPARC-V9 architecture manual, as set in the processor's PSTATE.MM field. iykyk 🦋

  • -mstack-bias, -mno-stack-bias — with -mstack-bias, GCC assumes that the stack pointer, and frame pointer if present, are offset by -2047, which must be added back when making stack frame references. This is the default in 64-bit mode. Otherwise, assume no such offset is present. No cap, this one matters 🎀

✨ Options for System V ✨

These additional options are available on System V Release 4 for compatibility with other compilers on those systems, bestie:

  • -G — create a shared object. It is recommended that -symbolic or -shared be used instead. The manpage itself is telling you to use the newer ones, so like… listen to it 🫶
  • -Qy — identify the versions of each tool used by the compiler, in a .ident assembler directive in the output.
  • -Qn — refrain from adding .ident directives to the output file (this is the default).
  • -YP,dirs — search the directories dirs, and no others, for libraries specified with -l.
  • -Ym,dir — look in the directory dir to find the M4 preprocessor. The assembler uses this option.

🔥 TILE-Gx Options 🔥

These -m options are supported on the TILE-Gx:

  • -mcmodel=small — generate code for the small model. The distance for direct calls is limited to 500M in either direction. PC-relative addresses are 32 bits. Absolute addresses support the full address range.
  • -mcmodel=large — generate code for the large model. There is no limitation on call distance, pc-relative addresses, or absolute addresses. Go big or go home, literally 💅
  • -mcpu=name — selects the type of CPU to be targeted. Currently the only supported type is tilegx.
  • -m32, -m64 — generate code for a 32-bit or 64-bit environment. The 32-bit environment sets int, long, and pointer to 32 bits. The 64-bit environment sets int to 32 bits and long and pointer to 64 bits.
  • -mbig-endian, -mlittle-endian — generate code in big/little endian mode, respectively.

🌸 TILEPro Options 🌸

These -m options are supported on the TILEPro:

  • -mcpu=name — selects the type of CPU to be targeted. Currently the only supported type is tilepro.
  • -m32 — generate code for a 32-bit environment, which sets int, long, and pointer to 32 bits. This is the only supported behavior so the flag is essentially ignored. It's giving “we support this on paper” energy, but okay 🫶

💜 V850 Options 💜

These -m options are defined for V850 implementations:

  • -mlong-calls, -mno-long-calls — treat all calls as being far away (near). If calls are assumed to be far away, the compiler always loads the function's address into a register, and calls indirect through the pointer.
  • -mno-ep, -mep — do not optimize (do optimize) basic blocks that use the same index pointer 4 or more times to copy pointer into the ep register, and use the shorter sld and sst instructions. The -mep option is on by default if you optimize.
  • -mno-prolog-function, -mprolog-function — do not use (do use) external functions to save and restore registers at the prologue and epilogue of a function. The external functions are slower, but use less code space if more than one function saves the same number of registers. The -mprolog-function option is on by default if you optimize.
  • -mspace — try to make the code as small as possible. At present, this just turns on the -mep and -mprolog-function options. Tiny code, big vibes ✨
  • -mtda=n — put static or global variables whose size is n bytes or less into the tiny data area that register ep points to. The tiny data area can hold up to 256 bytes in total (128 bytes for byte references).
  • -msda=n — put static or global variables whose size is n bytes or less into the small data area that register gp points to. The small data area can hold up to 64 kilobytes.
  • -mzda=n — put static or global variables whose size is n bytes or less into the first 32 kilobytes of memory.
  • -mv850 — specify that the target processor is the V850.
  • -mv850e3v5 — specify that the target processor is the V850E3V5. The preprocessor constant __v850e3v5__ is defined if this option is used.
  • -mv850e2v4 — specify that the target processor is the V850E3V5. This is an alias for the -mv850e3v5 option.
  • -mv850e2v3 — specify that the target processor is the V850E2V3. The preprocessor constant __v850e2v3__ is defined if this option is used.
  • -mv850e2 — specify that the target processor is the V850E2. The preprocessor constant __v850e2__ is defined if this option is used.
  • -mv850e1 — specify that the target processor is the V850E1. The preprocessor constants __v850e1__ and __v850e__ are defined if this option is used.
  • -mv850es — specify that the target processor is the V850ES. This is an alias for the -mv850e1 option.
  • -mv850e — specify that the target processor is the V850E. The preprocessor constant __v850e__ is defined if this option is used.

If neither -mv850 nor -mv850e nor -mv850e1 nor -mv850e2 nor -mv850e2v3 nor -mv850e3v5 are defined then a default target processor is chosen and the relevant __v850*__ preprocessor constant is defined.

The preprocessor constants __v850 and __v851__ are always defined, regardless of which processor variant is the target. Iconic, honestly 👑

  • -mdisable-callt, -mno-disable-callt — this option suppresses generation of the CALLT instruction for the v850e, v850e1, v850e2, v850e2v3 and v850e3v5 flavors of the v850 architecture.

This option is enabled by default when the RH850 ABI is in use (see -mrh850-abi), and disabled by default when the GCC ABI is in use. If CALLT instructions are being generated then the C preprocessor symbol __V850_CALLT__ is defined.

  • -mrelax, -mno-relax — pass on (or do not pass on) the -mrelax command-line option to the assembler.
  • -mlong-jumps, -mno-long-jumps — disable (or re-enable) the generation of PC-relative jump instructions.
  • -msoft-float, -mhard-float — disable (or re-enable) the generation of hardware floating point instructions. This option is only significant when the target architecture is V850E2V3 or higher. If hardware floating point instructions are being generated then the C preprocessor symbol __FPU_OK__ is defined, otherwise the symbol __NO_FPU__ is defined.
  • -mloop — enables the use of the e3v5 LOOP instruction. The use of this instruction is not enabled by default when the e3v5 architecture is selected because its use is still experimental. Experimental, so like… handle with care 🧚
  • -mrh850-abi, -mghs — enables support for the RH850 version of the V850 ABI. This is the default. With this version of the ABI the following rules apply:
    • Integer sized structures and unions are returned via a memory pointer rather than a register.
    • Large structures and unions (more than 8 bytes in size) are passed by value.
    • Functions are aligned to 16-bit boundaries.
    • The -m8byte-align command-line option is supported.
    • The -mdisable-callt command-line option is enabled by default. The -mno-disable-callt command-line option is not supported.

When this version of the ABI is enabled the C preprocessor symbol __V850_RH850_ABI__ is defined.

  • -mgcc-abi — enables support for the old GCC version of the V850 ABI. With this version of the ABI the following rules apply:
    • Integer sized structures and unions are returned in register r10.
    • Large structures and unions (more than 8 bytes in size) are passed by reference.
    • Functions are aligned to 32-bit boundaries, unless optimizing for size.
    • The -m8byte-align command-line option is not supported.
    • The -mdisable-callt command-line option is supported but not enabled by default.

When this version of the ABI is enabled the C preprocessor symbol __V850_GCC_ABI__ is defined.

  • -m8byte-align, -mno-8byte-align — enables support for double and long long types to be aligned on 8-byte boundaries. The default is to restrict the alignment of all objects to at most 4-bytes. When -m8byte-align is in effect the C preprocessor symbol __V850_8BYTE_ALIGN__ is defined.
  • -mbig-switch — generate code suitable for big switch tables. Use this option only if the assembler/linker complain about out of range branches within a switch table.
  • -mapp-regs — this option causes r2 and r5 to be used in the code generated by the compiler. This setting is the default.
  • -mno-app-regs — this option causes r2 and r5 to be treated as fixed registers.

🌈 VAX Options 🌈

These -m options are defined for the VAX:

  • -munix — pls don't emit certain jump instructions (aobleq and friends) that the Unix assembler for the VAX literally cannot handle across long ranges. it's giving "the assembler said no" energy 💀
  • -mgnu — okay opposite vibe: DO output those jump instructions, assuming you're using the GNU assembler. slay 🫶
  • -mg — generate code for G-format floating-point numbers instead of D-format. that's it, that's the whole thing ✨
  • -mlra
  • -mno-lra — enable Local Register Allocation. ngl this is still experimental for the VAX, so by default the compiler uses standard reload. don't come for me if it's weird, it's literally labeled experimental 🎀

🌸 Visium Options 🌸

  • -mdebug — if your program does file I/O and is destined to run on an MCM target, link it with this. it causes the libraries libc.a and libdebug.a to be linked. run the program on the target under the control of the GDB remote debugging stub 💅
  • -msim — if your program does file I/O and is destined to run on the simulator, link it with this option. this causes libraries libc.a and libsim.a to be linked ✨
  • -mfpu
  • -mhard-float — generate code containing floating-point instructions. this is the default, bestie 👑
  • -mno-fpu
  • -msoft-float — generate code containing library calls for floating-point.
⚠️ careful: -msoft-float changes the calling convention in the output file, so it's only useful if you compile all of a program with this option. in particular, you need to compile libgcc.a — the library that comes with GCC — with -msoft-float for this to work. no cap, all of it or none of it 🙈
  • *-mcpu=cpu_type* — set the instruction set, register set, and instruction scheduling parameters for machine type cpu_type. supported values for cpu_type are mcm, gr5 and gr6.

mcm is a synonym of gr5, present for backward compatibility. (legacy icon behavior, we respect it 💜)

by default (unless configured otherwise), GCC generates code for the GR5 variant of the Visium architecture.

with -mcpu=gr6, GCC generates code for the GR6 variant of the Visium architecture. the only difference from GR5 code is that the compiler will generate block move instructions. block moves?? she's moving different 💅

  • *-mtune=cpu_type* — set the instruction scheduling parameters for machine type cpu_type, but do not set the instruction set or register set that -mcpu=cpu_type would. tuning only, no commitment ✨
  • -msv-mode — generate code for the supervisor mode, where there are no restrictions on the access to general registers. this is the default 🫶
  • -muser-mode — generate code for the user mode, where access to some general registers is forbidden: on the GR5, registers r24 to r31 cannot be accessed in this mode; on the GR6, only registers r29 to r31 are affected. so like, some doors are locked, iykyk 🔒

🎀 VMS Options 🎀

these -m options are defined for the VMS implementations:

  • -mvms-return-codes — return VMS condition codes from main. the default is to return POSIX-style condition (e.g. error) codes. pick your era, bestie 🌈
  • *-mdebug-main=prefix* — flag the first routine whose name starts with prefix as the main routine for the debugger. first one wins, periodt 🏁
  • -mmalloc64 — default to 64-bit memory allocation routines. big allocations energy 🔥
  • *-mpointer-size=size* — set the default size of pointers. possible options for size are 32 or short for 32 bit pointers, 64 or long for 64 bit pointers, and no for supporting only 32 bit pointers. the later option disables pragma pointer_size. yes the manpage says "later", it means "latter", we're not editing the original's vibes 💀

🦋 VxWorks Options 🦋

the options in this section are defined for all VxWorks targets. options specific to the target hardware are listed with the other options for that target. (yes, go look over there for the hardware-specific ones 👀)

  • -mrtp — GCC can generate code for both VxWorks kernels and real time processes (RTPs). this option switches from the former to the latter. it also defines the preprocessor macro __RTP__. we love a macro defined on the sly ✨
  • -non-static — link an RTP executable against shared libraries rather than static libraries. the options -static and -shared can also be used for RTPs; -static is the default 🎀
  • -Bstatic
  • -Bdynamic — these options are passed down to the linker. they are defined for compatibility with Diab. middleman behavior, but make it iconic 💅
  • -Xbind-lazy — enable lazy binding of function calls. this option is equivalent to -Wl,-z,now and is defined for compatibility with Diab. yes, "lazy" maps to now, i don't make the rules 😭
  • -Xbind-now — disable lazy binding of function calls. this option is the default and is defined for compatibility with Diab 🫶

💜 x86 Options 💜

these -m options are defined for the x86 family of computers. buckle up bestie, this is the long one 🎢

  • -march=cpu-type — generate instructions for the machine type cpu-type. in contrast to -mtune=cpu-type, which merely tunes the generated code for the specified cpu-type, -march=cpu-type allows GCC to generate code that may *not run at all on processors other than the one indicated. specifying -march=cpu-type* implies -mtune=cpu-type, except where noted otherwise.
⚠️ fr fr: this one can produce code that flat-out won't run on other chips. it's giving "main character only on this CPU" 💀

the choices for cpu-type are:

  • native — this selects the CPU to generate code for at compilation time by determining the processor type of the compiling machine. using -march=native enables all instruction subsets supported by the local machine (hence the result might not run on different machines). using -mtune=native produces code optimized for the local machine under the constraints of the selected instruction set. self-obsessed compiler, honestly obsessed 🪞
  • x86-64 — a generic CPU with 64-bit extensions.
  • x86-64-v2
  • x86-64-v3
  • x86-64-v4 — these choices for cpu-type select the corresponding micro-architecture level from the x86-64 psABI. on ABIs other than the x86-64 psABI they select the same CPU features as the x86-64 psABI documents for the particular micro-architecture level.

since these cpu-type values do not have a corresponding -mtune setting, using -march with these values enables generic tuning. specific tuning can be enabled using the -mtune=other-cpu-type option with an appropriate other-cpu-type value. (so you gotta pair it up manually, matchmaker style 💘)

  • i386 — original Intel i386 CPU.
  • i486 — Intel i486 CPU. (no scheduling is implemented for this chip. we simply don't schedule here 💀)
  • i586
  • pentium — Intel Pentium CPU with no MMX support.
  • lakemont — Intel Lakemont MCU, based on Intel Pentium CPU.
  • pentium-mmx — Intel Pentium MMX CPU, based on Pentium core with MMX instruction set support.
  • pentiumpro — Intel Pentium Pro CPU.
  • i686 — when used with -march, the Pentium Pro instruction set is used, so the code runs on all i686 family chips. when used with -mtune, it has the same meaning as generic. dual identity icon ✨
  • pentium2 — Intel Pentium II CPU, based on Pentium Pro core with MMX and FXSR instruction set support.
  • pentium3
  • pentium3m — Intel Pentium III CPU, based on Pentium Pro core with MMX, FXSR and SSE instruction set support.
  • pentium-m — Intel Pentium M; low-power version of Intel Pentium III CPU with MMX, SSE, SSE2 and FXSR instruction set support. used by Centrino notebooks. laptop legend 🎀
  • pentium4
  • pentium4m — Intel Pentium 4 CPU with MMX, SSE, SSE2 and FXSR instruction set support.
  • prescott — improved version of Intel Pentium 4 CPU with MMX, SSE, SSE2, SSE3 and FXSR instruction set support.
  • nocona — improved version of Intel Pentium 4 CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3 and FXSR instruction set support.
  • core2 — Intel Core 2 CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, CX16, SAHF and FXSR instruction set support.
  • nehalem — Intel Nehalem CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF and FXSR instruction set support.
  • westmere — Intel Westmere CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR and PCLMUL instruction set support.
  • sandybridge — Intel Sandy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE and PCLMUL instruction set support.
  • ivybridge — Intel Ivy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND and F16C instruction set support.
  • haswell — Intel Haswell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE and HLE instruction set support.
  • broadwell — Intel Broadwell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX and PREFETCHW instruction set support.
  • skylake — Intel Skylake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES and SGX instruction set support.
  • bonnell — Intel Bonnell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support.
  • silvermont — Intel Silvermont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW and RDRND instruction set support.
  • goldmont — Intel Goldmont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT and FSGSBASE instruction set support.
  • goldmont-plus — Intel Goldmont Plus CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT, FSGSBASE, PTWRITE, RDPID and SGX instruction set support.
  • tremont — Intel Tremont, bestie. 64-bit extensions plus MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT, FSGSBASE, PTWRITE, RDPID, SGX, CLWB, GFNI-SSE, MOVDIRI, MOVDIR64B, CLDEMOTE and WAITPKG instruction set support. ✨
  • knl — Intel Knight's Landing, the icon. 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AVX512PF, AVX512ER, AVX512F, AVX512CD and PREFETCHWT1 instruction set support. 💫
  • knm — Intel Knights Mill, knl's louder sibling. 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AVX512PF, AVX512ER, AVX512F, AVX512CD and PREFETCHWT1, AVX5124VNNIW, AVX5124FMAPS and AVX512VPOPCNTDQ instruction set support.
  • skylake-avx512 — Intel Skylake Server. 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ and AVX512CD instruction set support. 🦋
  • cannonlake — Intel Cannonlake Server. 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA and SHA instruction set support.
  • icelake-client — Intel Icelake Client, she's giving main character. 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2 , VPCLMULQDQ, AVX512BITALG, RDPID and AVX512VPOPCNTDQ instruction set support. 💅
  • icelake-server — Intel Icelake Server, client's big sister fr fr. 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2 , VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD and CLWB instruction set support.
  • cascadelake — Intel Cascadelake. 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD and AVX512VNNI instruction set support. 🔥
  • cooperlake — Intel cooperlake (yes, lowercase in the manual, we don't make the rules). 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VNNI and AVX512BF16 instruction set support.
  • tigerlake — Intel Tigerlake, highkey a vibe. 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, MOVDIRI, MOVDIR64B, CLWB, AVX512VP2INTERSECT and KEYLOCKER instruction set support. 🐯
  • sapphirerapids — Intel sapphirerapids, the whole entire buffet. 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2 VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD, CLWB, MOVDIRI, MOVDIR64B, AVX512VP2INTERSECT, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512FP16 and AVX512BF16 instruction set support. 💎
  • alderlake — Intel Alderlake. 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT, FSGSBASE, PTWRITE, RDPID, SGX, GFNI-SSE, CLWB, MOVDIRI, MOVDIR64B, CLDEMOTE, WAITPKG, ADCX, AVX, AVX2, BMI, BMI2, F16C, FMA, LZCNT, PCONFIG, PKU, VAES, VPCLMULQDQ, SERIALIZE, HRESET, KL, WIDEKL and AVX-VNNI instruction set support.
  • rocketlake — Intel Rocketlake. 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3 , SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID and AVX512VPOPCNTDQ instruction set support. 🚀

Okay so now we're switching teams — AMD era bestie, let's go 🫶

  • k6 — AMD K6, a lil vintage icon. MMX instruction set support.
  • k6-2
  • k6-3 — improved versions of the AMD K6, now with MMX and 3DNow! instruction set support. Glow-up fr.
  • athlon
  • athlon-tbird — AMD Athlon with MMX, 3dNOW!, enhanced 3DNow! and SSE prefetch instructions support.
  • athlon-4
  • athlon-xp
  • athlon-mp — improved AMD Athlon with MMX, 3DNow!, enhanced 3DNow! and the full SSE instruction set support. She ate.
  • k8
  • opteron
  • athlon64
  • athlon-fx — processors based on the AMD K8 core with x86-64 instruction set support, including the AMD Opteron, Athlon 64, and Athlon 64 FX processors. This supersets MMX, SSE, SSE2, 3DNow!, enhanced 3DNow! and 64-bit instruction set extensions. ✨
  • k8-sse3
  • opteron-sse3
  • athlon64-sse3 — improved versions of the AMD K8 cores, now with SSE3 instruction set support.
  • amdfam10
  • barcelona — CPUs based on AMD Family 10h cores with x86-64 instruction set support. This supersets MMX, SSE, SSE2, SSE3, SSE4A, 3DNow!, enhanced 3DNow!, ABM and 64-bit instruction set extensions.
  • bdver1 — CPUs based on AMD Family 15h cores with x86-64 instruction set support. This supersets FMA4, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.
  • bdver2 — AMD Family 15h core based CPUs with x86-64 instruction set support. This supersets BMI, TBM, F16C, FMA, FMA4, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.
  • bdver3 — AMD Family 15h core based CPUs with x86-64 instruction set support. This supersets BMI, TBM, F16C, FMA, FMA4, FSGSBASE, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.
  • bdver4 — AMD Family 15h core based CPUs with x86-64 instruction set support. This supersets BMI, BMI2, TBM, F16C, FMA, FMA4, FSGSBASE, AVX, AVX2, XOP, LWP, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions. 🔥
  • znver1 — AMD Family 17h core based CPUs with x86-64 instruction set support. This supersets BMI, BMI2, F16C, FMA, FSGSBASE, AVX, AVX2, ADCX, RDSEED, MWAITX, SHA, CLZERO, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM, XSAVEC, XSAVES, CLFLUSHOPT, POPCNT, and 64-bit instruction set extensions. ✨
  • znver2 — AMD Family 17h core based CPUs with x86-64 instruction set support. This supersets BMI, BMI2, CLWB, F16C, FMA, FSGSBASE, AVX, AVX2, ADCX, RDSEED, MWAITX, SHA, CLZERO, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM, XSAVEC, XSAVES, CLFLUSHOPT, POPCNT, RDPID, WBNOINVD, and 64-bit instruction set extensions.
  • znver3 — AMD Family 19h core based CPUs with x86-64 instruction set support. This supersets BMI, BMI2, CLWB, F16C, FMA, FSGSBASE, AVX, AVX2, ADCX, RDSEED, MWAITX, SHA, CLZERO, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM, XSAVEC, XSAVES, CLFLUSHOPT, POPCNT, RDPID, WBNOINVD, PKU, VPCLMULQDQ, VAES, and 64-bit instruction set extensions. 👑
  • btver1 — CPUs based on AMD Family 14h cores with x86-64 instruction set support. This supersets MMX, SSE, SSE2, SSE3, SSSE3, SSE4A, CX16, ABM and 64-bit instruction set extensions.
  • btver2 — CPUs based on AMD Family 16h cores with x86-64 instruction set support. This includes MOVBE, F16C, BMI, AVX, PCLMUL, AES, SSE4.2, SSE4.1, CX16, ABM, SSE4A, SSSE3, SSE3, SSE2, SSE, MMX and 64-bit instruction set extensions.
  • winchip-c6 — IDT WinChip C6, the little legend. Dealt with in same way as i486, with additional MMX instruction set support. 🎀
  • winchip2 — IDT WinChip 2 CPU, handled exactly like i486 but with bonus MMX and 3DNow! instruction set support. 💅
  • c3 — VIA C3 CPU, MMX + 3DNow! instruction set support. (No scheduling is implemented for this chip, so don't expect it to get fancy with instruction ordering, bestie.)
  • c3-2 — VIA C3-2 (Nehemiah/C5XL) CPU, MMX + SSE instruction set support. (Again: no scheduling is implemented for this chip. 😭)
  • c7 — VIA C7 (Esther) CPU, with MMX, SSE, SSE2 and SSE3 instruction set support. (No scheduling is implemented for this chip.)
  • samuel-2 — VIA Eden Samuel 2 CPU, MMX + 3DNow! instruction set support. (No scheduling is implemented for this chip.)
  • nehemiah — VIA Eden Nehemiah CPU, MMX + SSE instruction set support. (No scheduling is implemented for this chip.)
  • esther — VIA Eden Esther CPU, MMX, SSE, SSE2 and SSE3 instruction set support. (No scheduling is implemented for this chip.)
  • eden-x2 — VIA Eden X2 CPU, x86-64, MMX, SSE, SSE2 and SSE3 instruction set support. (No scheduling is implemented for this chip.)
  • eden-x4 — VIA Eden X4 CPU, x86-64, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, AVX and AVX2 instruction set support. (No scheduling is implemented for this chip. She has the whole instruction buffet and still no scheduler, iconic honestly.)
  • nano — generic VIA Nano CPU, x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)
  • nano-1000 — VIA Nano 1xxx CPU, x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)
  • nano-2000 — VIA Nano 2xxx CPU, x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)
  • nano-3000 — VIA Nano 3xxx CPU, x86-64, MMX, SSE, SSE2, SSE3, SSSE3 and SSE4.1 instruction set support. (No scheduling is implemented for this chip.)
  • nano-x2 — VIA Nano Dual Core CPU, x86-64, MMX, SSE, SSE2, SSE3, SSSE3 and SSE4.1 instruction set support. (No scheduling is implemented for this chip.)
  • nano-x4 — VIA Nano Quad Core CPU, x86-64, MMX, SSE, SSE2, SSE3, SSSE3 and SSE4.1 instruction set support. (No scheduling is implemented for this chip.)
  • geode — AMD Geode embedded processor, MMX + 3DNow! instruction set support. 🦋

✨ -mtune=cpu-type — the vibes-tuning option ✨

Okay so -mtune=cpu-type tunes everything applicable about the generated code to cpu-type — except for the ABI and the set of available instructions. 🎀

So like, picking a specific cpu-type schedules things appropriately for that particular chip, but the compiler does not generate any code that cannot run on the default machine type — unless you also use a -march=cpu-type option. For example, if GCC is configured for i686-pc-linux-gnu then -mtune=pentium4 generates code that is tuned for Pentium 4 but still runs on i686 machines. Slay, backwards compatibility. 🫶

The choices for cpu-type are the same as for -march. In addition, -mtune supports 2 extra choices for cpu-type:

generic 💜

Produce code optimized for the most common IA32/AMD64/EM64T processors. If you know the CPU on which your code will run, then you should use the corresponding -mtune or -march option instead of -mtune=generic. But, if you do not know exactly what CPU users of your application will have, then you should use this option.

As new processors are deployed in the marketplace, the behavior of this option will change. Therefore, if you upgrade to a newer version of GCC, code generation controlled by this option will change to reflect the processors that are most common at the time that version of GCC is released. (Yes bestie, it's a moving target, that's the whole point. 🙈)

There is no -march=generic option because -march indicates the instruction set the compiler can use, and there is no generic instruction set applicable to all processors. In contrast, -mtune indicates the processor (or, in this case, collection of processors) for which the code is optimized. 💅

intel 🌈

Produce code optimized for the most current Intel processors, which are Haswell and Silvermont for this version of GCC. If you know the CPU on which your code will run, then you should use the corresponding -mtune or -march option instead of -mtune=intel. But, if you want your application performs better on both Haswell and Silvermont, then you should use this option.

As new Intel processors are deployed in the marketplace, the behavior of this option will change. Therefore, if you upgrade to a newer version of GCC, code generation controlled by this option will change to reflect the most current Intel processors at the time that version of GCC is released.

There is no -march=intel option because -march indicates the instruction set the compiler can use, and there is no common instruction set applicable to all processors. In contrast, -mtune indicates the processor (or, in this case, collection of processors) for which the code is optimized.

🌸 -mcpu=cpu-type 🌸

A deprecated synonym for -mtune. That's it, that's the whole thing. She's retired but still hanging around the group chat. 💀

🎀 -mfpmath=unit — where the floats live 🎀

Generate floating-point arithmetic for selected unit unit. The choices for unit are:

  • 387 — Use the standard 387 floating-point coprocessor present on the majority of chips and emulated otherwise. Code compiled with this option runs almost everywhere. The temporary results are computed in 80-bit precision instead of the precision specified by the type, resulting in slightly different results compared to most of other chips. See -ffloat-store for more detailed description.

This is the default choice for non-Darwin x86-32 targets. 👑

  • sse — Use scalar floating-point instructions present in the SSE instruction set. This instruction set is supported by Pentium III and newer chips, and in the AMD line by Athlon-4, Athlon XP and Athlon MP chips. The earlier version of the SSE instruction set supports only single-precision arithmetic, thus the double and extended-precision arithmetic are still done using 387. A later version, present only in Pentium 4 and AMD x86-64 chips, supports double-precision arithmetic too.

For the x86-32 compiler, you must use -march=cpu-type, -msse or -msse2 switches to enable SSE extensions and make this option effective. For the x86-64 compiler, these extensions are enabled by default.

The resulting code should be considerably faster in the majority of cases and avoid the numerical instability problems of 387 code, but may break some existing code that expects temporaries to be 80 bits. ⚠️

This is the default choice for the x86-64 compiler, Darwin x86-32 targets, and the default choice for x86-32 targets with the SSE2 instruction set when -ffast-math is enabled.

  • sse,387
  • sse+387
  • both — Attempt to utilize both instruction sets at once. This effectively doubles the amount of available registers, and on chips with separate execution units for 387 and SSE the execution resources too. Use this option with care, as it is still experimental, because the GCC register allocator does not model separate functional units well, resulting in unstable performance. 😭 (Experimental means experimental, bestie — don't come crying to me when the performance is all over the place.)
-masm=dialect — Output assembly instructions using selected dialect. Also affects which dialect is used for basic asm and extended asm. Supported choices (in dialect order) are att or intel. The default is att. Darwin does not support intel.

💜 -mieee-fp / -mno-ieee-fp 💜

Control whether or not the compiler uses IEEE floating-point comparisons. These correctly handle the case where the result of a comparison is unordered. 🦋

✨ -m80387 / -mhard-float ✨

Generate output containing 80387 instructions for floating point.

🥀 -mno-80387 / -msoft-float 🥀

Generate output containing library calls for floating point.

Warning: the requisite libraries are not part of GCC. Normally the facilities of the machine's usual C compiler are used, but this cannot be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation. 🫶 (You're on your own for that one, no cap.)

On machines where a function returns floating-point results in the 80387 register stack, some floating-point opcodes may be emitted even if -msoft-float is used.

-mno-fp-ret-in-387 💅

Do not use the FPU registers for return values of functions.

The usual calling convention has functions return values of types float and double in an FPU register, even if there is no FPU. The idea is that the operating system should emulate an FPU.

The option -mno-fp-ret-in-387 causes such values to be returned in ordinary CPU registers instead. 🤯

-mno-fancy-math-387 🎀

Some 387 emulators do not support the sin, cos and sqrt instructions for the 387. Specify this option to avoid generating those instructions. This option is overridden when -march indicates that the target CPU always has an FPU and so the instruction does not need emulation. These instructions are not generated unless you also use the -funsafe-math-optimizations switch. 🔥

-malign-double / -mno-align-double ⭐

Control whether GCC aligns double, long double, and long long variables on a two-word boundary or a one-word boundary. Aligning double variables on a two-word boundary produces code that runs somewhat faster on a Pentium at the expense of more memory. Trade-offs, bestie, it's giving budget management. 💸

On x86-64, -malign-double is enabled by default.

Warning: if you use the -malign-double switch, structures containing the above types are aligned differently than the published application binary interface specifications for the x86-32 and are not binary compatible with structures in code compiled without that switch. 💀 Fr fr, this is the kind of thing that bites you later.

-m96bit-long-double / -m128bit-long-double 🦋

These switches control the size of long double type. The x86-32 application binary interface specifies the size to be 96 bits, so -m96bit-long-double is the default in 32-bit mode.

Modern architectures (Pentium and newer) lowkey prefer long double aligned on an 8- or 16-byte boundary, bestie. But in arrays or structures that conform to the ABI? Yeah, that's just not possible 😭. So bestie, when you pass -m128bit-long-double, it aligns long double to a 16-byte boundary by padding the long double with an extra 32-bit zero. Chef's kiss padding 💅

In the x86-64 compiler, -m128bit-long-double is literally the default choice, because its ABI specifies that long double is aligned on a 16-byte boundary ✨

Not me having to say this though — notice that neither of these options enable any extra precision over the x87 standard of 80 bits for a long double. Like, none. Zero. Nada 🫶

⚠️ Warning: if you override the default value for your target ABI, this changes the size of structures and arrays containing long double variables, as well as modifying the function calling convention for functions taking long double. Hence they are not binary-compatible with code compiled without that switch. fr fr, respect the ABI 💀
  • -mlong-double-64, -mlong-double-80, -mlong-double-128 — these switches control the size of the long double type, iconic behavior honestly 👑
    • A size of 64 bits makes the long double type equivalent to the double type. This is the default for 32-bit Bionic C library.
    • A size of 128 bits makes the long double type equivalent to the __float128 type. This is the default for 64-bit Bionic C library.
⚠️ Warning: if you override the default value for your target ABI, this changes the size of structures and arrays containing long double variables, as well as modifying the function calling convention for functions taking long double. Hence they are not binary-compatible with code compiled without that switch. Same warning, same energy, no cap 🙈
  • -malign-data=type — controls how GCC aligns variables ✨ Supported values for type are:
    • compat — uses increased alignment value compatible with GCC 4.8 and earlier
    • abi — uses alignment value as specified by the psABI
    • cacheline — uses increased alignment value to match the cache line size

compat is the default, periodt 💅

  • -mlarge-data-threshold=threshold — when -mcmodel=medium is specified, data objects larger than threshold get placed in the large data section 🎀 This value must be the same across all objects linked into the binary, and it defaults to 65535. Keep it consistent or suffer, iykyk 💀
  • -mrtd — use a different function-calling convention, where functions that take a fixed number of arguments return with the ret num instruction, which pops their arguments while returning 😮 This saves one instruction in the caller, since there's no need to pop the arguments there. Efficient! Slay 💅

You can specify that an individual function is called with this calling sequence with the function attribute stdcall. You can also override the -mrtd option by using the function attribute cdecl.

⚠️ Warning: this calling convention is incompatible with the one normally used on Unix, so you cannot use it if you need to call libraries compiled with the Unix compiler 😭

Also, you must provide function prototypes for all functions that take variable numbers of arguments (including printf); otherwise incorrect code is generated for calls to those functions 🫶

In addition, seriously incorrect code results if you call a function with too many arguments. (Normally, extra arguments are harmlessly ignored.) Not so harmlessly here bestie 💀

  • -mregparm=num — control how many registers are used to pass integer arguments 🌸 By default, no registers are used to pass arguments, and at most 3 registers can be used. You can control this behavior for a specific function by using the function attribute regparm ✨
⚠️ Warning: if you use this switch, and num is nonzero, then you must build all modules with the same value, including any libraries. This includes the system libraries and startup modules. No mixing, bestie 🙈
  • -msseregparm — use SSE register passing conventions for float and double arguments and return values 🦋 You can control this behavior for a specific function by using the function attribute sseregparm.
⚠️ Warning: if you use this switch then you must build all modules with the same value, including any libraries. This includes the system libraries and startup modules. Same rule, same drama 💀
  • -mvect8-ret-in-mem — return 8-byte vectors in memory instead of MMX registers 👀 This is the default on VxWorks to match the ABI of the Sun Studio compilers until version 12. Only use this option if you need to remain compatible with existing code produced by those previous compiler versions or older versions of GCC. Legacy vibes only, ngl 🎀
  • -mpc32, -mpc64, -mpc80 — set 80387 floating-point precision to 32, 64 or 80 bits 💖
    • When -mpc32 is specified, the significands of results of floating-point operations are rounded to 24 bits (single precision)
    • -mpc64 rounds the significands of results of floating-point operations to 53 bits (double precision)
    • -mpc80 rounds the significands of results of floating-point operations to 64 bits (extended double precision), which is the default ✨

When this option is used, floating-point operations in higher precisions are not available to the programmer without setting the FPU control word explicitly. Like, you gotta do it yourself, bestie 😭

Setting the rounding of floating-point operations to less than the default 80 bits can speed some programs by 2% or more 🔥 But heads up: some mathematical libraries assume that extended-precision (80-bit) floating-point operations are enabled by default; routines in such libraries could suffer significant loss of accuracy, typically through so-called "catastrophic cancellation", when this option is used to set the precision to less than extended precision. Catastrophic is literally the right word here 💀

  • -mstackrealign — realign the stack at entry 🫶 On the x86, the -mstackrealign option generates an alternate prologue and epilogue that realigns the run-time stack if necessary. This supports mixing legacy codes that keep 4-byte stack alignment with modern codes that keep 16-byte stack alignment for SSE compatibility ✨ See also the attribute force_align_arg_pointer, applicable to individual functions.
  • -mpreferred-stack-boundary=num — attempt to keep the stack boundary aligned to a 2 raised to num byte boundary 🌸 If -mpreferred-stack-boundary is not specified, the default is 4 (16 bytes or 128 bits).
⚠️ Warning: when generating code for the x86-64 architecture with SSE extensions disabled, -mpreferred-stack-boundary=3 can be used to keep the stack boundary aligned to 8 byte boundary. Since x86-64 ABI require 16 byte stack alignment, this is ABI incompatible and intended to be used in controlled environment where stack space is important limitation. This option leads to wrong code when functions compiled with 16 byte stack alignment (such as functions from a standard library) are called with misaligned stack. In this case, SSE instructions may lead to misaligned memory access traps. In addition, variable arguments are handled incorrectly for 16 byte aligned objects (including x87 long double and __int128), leading to wrong results. You must build all modules with -mpreferred-stack-boundary=3, including any libraries. This includes the system libraries and startup modules. Like, don't do this casually, bestie 😭
  • -mincoming-stack-boundary=num — assume the incoming stack is aligned to a 2 raised to num byte boundary 🦋 If -mincoming-stack-boundary is not specified, the one specified by -mpreferred-stack-boundary is used.

On Pentium and Pentium Pro, double and long double values should be aligned to an 8-byte boundary (see -malign-double) or suffer significant run time performance penalties 😬 On Pentium III, the Streaming SIMD Extension (SSE) data type __m128 may not work properly if it is not 16-byte aligned.

To ensure proper alignment of this values on the stack, the stack boundary must be as aligned as that required by any value stored on the stack 💅 Further, every function must be generated such that it keeps the stack aligned. Thus calling a function compiled with a higher preferred stack boundary from a function compiled with a lower preferred stack boundary most likely misaligns the stack. It is recommended that libraries that use callbacks always use the default setting ✨

This extra alignment does consume extra stack space, and generally increases code size. Code that is sensitive to stack space usage, such as embedded systems and operating system kernels, may want to reduce the preferred alignment to -mpreferred-stack-boundary=2 🎀 Tight spaces, tiny stacks, we respect it.

okay bestie, brace yourself 🫶 — the next chunk of the x86 switch zoo is long. like, "scroll for three business days" long. here's the whole squad, verbatim, no cap:

-mmmx
-msse
-msse2
-msse3
-mssse3
-msse4
-msse4a
-msse4.1
-msse4.2
-mavx
-mavx2
-mavx512f
-mavx512pf
-mavx512er
-mavx512cd
-mavx512vl
-mavx512bw
-mavx512dq
-mavx512ifma
-mavx512vbmi
-msha
-maes
-mpclmul
-mclflushopt
-mclwb
-mfsgsbase
-mptwrite
-mrdrnd
-mf16c
-mfma
-mpconfig
-mwbnoinvd
-mfma4
-mprfchw
-mrdpid
-mprefetchwt1
-mrdseed
-msgx
-mxop
-mlwp
-m3dnow
-m3dnowa
-mpopcnt
-mabm
-madx
-mbmi
-mbmi2
-mlzcnt
-mfxsr
-mxsave
-mxsaveopt
-mxsavec
-mxsaves
-mrtm
-mhle
-mtbm
-mmwaitx
-mclzero
-mpku
-mavx512vbmi2
-mavx512bf16
-mavx512fp16
-mgfni
-mvaes
-mwaitpkg
-mvpclmulqdq
-mavx512bitalg
-mmovdiri
-mmovdir64b
-menqcmd
-muintr
-mtsxldtrk
-mavx512vpopcntdq
-mavx512vp2intersect
-mavx5124fmaps
-mavx512vnni
-mavxvnni
-mavx5124vnniw
-mcldemote
-mserialize
-mamx-tile
-mamx-int8
-mamx-bf16
-mhreset
-mkl
-mwidekl

so what do these actually do? ✨ These switches enable the use of instructions in the MMX, SSE, SSE2, SSE3, SSSE3, SSE4, SSE4A, SSE4.1, SSE4.2, AVX, AVX2, AVX512F, AVX512PF, AVX512ER, AVX512CD, AVX512VL, AVX512BW, AVX512DQ, AVX512IFMA, AVX512VBMI, SHA, AES, PCLMUL, CLFLUSHOPT, CLWB, FSGSBASE, PTWRITE, RDRND, F16C, FMA, PCONFIG, WBNOINVD, FMA4, PREFETCHW, RDPID, PREFETCHWT1, RDSEED, SGX, XOP, LWP, 3DNow!, enhanced 3DNow!, POPCNT, ABM, ADX, BMI, BMI2, LZCNT, FXSR, XSAVE, XSAVEOPT, XSAVEC, XSAVES, RTM, HLE, TBM, MWAITX, CLZERO, PKU, AVX512VBMI2, GFNI, VAES, WAITPKG, VPCLMULQDQ, AVX512BITALG, MOVDIRI, MOVDIR64B, AVX512BF16, ENQCMD, AVX512VPOPCNTDQ, AVX5124FMAPS, AVX512VNNI, AVX5124VNNIW, SERIALIZE, UINTR, HRESET, AMXTILE, AMXINT8, AMXBF16, KL, WIDEKL, AVXVNNI, AVX512FP16 or CLDEMOTE extended instruction sets. and yep, every single one of them has a matching -mno- option that turns the instruction off again. balanced, as all things should be ⚖️

these extensions are also available as built-in functions: see x86 Built-in Functions for the details on which functions these switches enable and disable. iykyk 🔍

want SSE/SSE2 instructions generated automatically out of floating-point code (as opposed to 387 instructions)? that's -mfpmath=sse, bestie. go look at it 👀

GCC depresses SSEx instructions when -mavx is used. instead it generates the new AVX instructions, or an AVX equivalence for all SSEx instructions, whenever it needs them. it's giving "glow up, but the old self is still in there somewhere" 💅

these options let GCC use these extended instructions in generated code, even without -mfpmath=sse. but — and this is the important bit — applications that perform run-time CPU detection must compile separate files for each supported architecture, using the appropriate flags. specifically: the file containing the CPU detection code should be compiled without these options. don't forget, or it gets weird 😭


  • -mdump-tune-features — tells GCC to dump the names of the x86 performance tuning features and their default settings. those names are then usable in -mtune-ctrl=feature-list. free real estate 🎁
  • -mtune-ctrl=feature-list — fine-grain control of x86 code generation features, bestie. feature-list is a comma-separated list of feature names (peep -mdump-tune-features for the names). when you specify a feature, it gets turned on unless it's preceded with ^ — in which case it gets turned off. and now the warning label 🚨: -mtune-ctrl=feature-list is intended to be used by GCC developers. using it may lead you into code paths not covered by testing and can potentially result in compiler ICEs or runtime errors. dangerous territory, you've been warned 💀
  • -mno-default — tells GCC to turn off all tunable features. see also -mtune-ctrl=feature-list and -mdump-tune-features. nuke it from orbit 🌈
  • -mcld — makes GCC emit a cld instruction in the prologue of functions that use string instructions. why do we care? because string instructions depend on the DF flag to pick between autoincrement or autodecrement mode 🧭 the ABI says the DF flag is cleared on function entry — but some operating systems violate that spec by not clearing the DF flag in their exception dispatchers 😤 so the exception handler can get invoked with the DF flag set, which leads to the wrong direction mode when string instructions are used. this option can be enabled by default on 32-bit x86 targets by configuring GCC with the --enable-cld configure option, and you can suppress generation of cld instructions with the -mno-cld compiler option in that case 🎀
  • -mvzeroupper — tells GCC to emit a vzeroupper instruction before a transfer of control flow out of the function, which minimizes the AVX to SSE transition penalty and removes unnecessary zeroupper intrinsics. efficiency queen 👑
  • -mprefer-avx128 — tells GCC to use 128-bit AVX instructions instead of 256-bit AVX instructions in the auto-vectorizer. small but mighty 🐣
  • -mprefer-vector-width=opt — tells GCC to use opt-bit vector width in instructions instead of the default on the selected platform.
  • -mmove-max=bits — sets the maximum number of bits that can be moved from memory to memory efficiently to bits. the valid bits are 128, 256 and 512 📦
  • -mstore-max=bits — sets the maximum number of bits that can be stored to memory efficiently to bits. the valid bits are 128, 256 and 512 🗃️

speaking of that opt value, here's what it can be 🦋

  • none — no extra limitations applied to GCC other than those defined by the selected platform.
  • 128 — prefer 128-bit vector width for instructions.
  • 256 — prefer 256-bit vector width for instructions.
  • 512 — prefer 512-bit vector width for instructions.

  • -mcx16 — lets GCC generate CMPXCHG16B instructions in 64-bit code to implement compare-and-exchange operations on 16-byte aligned 128-bit objects. super useful for atomic updates of data structures that are bigger than one machine word 🧱 the compiler uses this instruction to implement __sync Builtins. however — for __atomic Builtins operating on 128-bit integers, a library call is always used. noted, no cap 📌
  • -msahf — enables generation of SAHF instructions in 64-bit code. history lesson time 🌸 early Intel Pentium 4 CPUs with Intel 64 support, prior to the introduction of Pentium 4 G1 step in December 2005, lacked the LAHF and SAHF instructions that AMD64 supports. those two are load and store instructions, respectively, for certain status flags. in 64-bit mode, SAHF is used to optimize the fmod, drem and remainder built-in functions — see Other Builtins for the deets 🔍
  • -mmovbe — enables use of the movbe instruction to implement __builtin_bswap32 and __builtin_bswap64. byte-swap slay 🔄
  • -mshstk — the -mshstk option enables shadow stack built-in functions from x86 Control-flow Enforcement Technology (CET). 🛡️
  • -mcrc32 — enables the built-in functions __builtin_ia32_crc32qi, __builtin_ia32_crc32hi, __builtin_ia32_crc32si and __builtin_ia32_crc32di so they generate the crc32 machine instruction 🧮
  • -mmwait — enables the built-in functions __builtin_ia32_monitor and __builtin_ia32_mwait so they generate the monitor and mwait machine instructions 👀
  • -mrecip — enables use of RCPSS and RSQRTSS instructions (plus their vectorized variants RCPPS and RSQRTPS) with an additional Newton-Raphson step to bump up precision, instead of DIVSS and SQRTSS (and their vectorized variants), for single-precision floating-point arguments. ⚡ but heads up: these instructions are generated only when -funsafe-math-optimizations is enabled together with -ffinite-math-only and -fno-trapping-math. and while the throughput of the sequence is higher than the throughput of the non-reciprocal instruction, the precision of the sequence can be decreased by up to 2 ulp — i.e. the inverse of 1.0 equals 0.99999994 😭 so like... fast but slightly delulu. remember that.

also note: GCC already implements 1.0f/sqrtf(x) in terms of RSQRTSS (or RSQRTPS) with -ffast-math (or the option combo above), and doesn't need -mrecip for that 🙌

also also note: GCC emits the above sequence with an additional Newton-Raphson step for vectorized single-float division and vectorized sqrtf(x) already with -ffast-math (or the above option combination), and doesn't need -mrecip for those either. double covered 💜

  • -mrecip=opt — controls which reciprocal estimate instructions may be used. opt is a comma-separated list of options, and any of them may be preceded by a ! to invert it 🙃
    • all — enable all estimate instructions.
    • default — enable the default instructions, equivalent to -mrecip.
    • none — disable all estimate instructions, equivalent to -mno-recip.
    • div — enable the approximation for scalar division.
    • vec-div — enable the approximation for vectorized division.
    • sqrt — enable the approximation for scalar square root.
    • vec-sqrt — enable the approximation for vectorized square root.

so for example, -mrecip=all,!sqrt enables all of the reciprocal approximations except for square root. see? the ! is doing the lord's work 🎀

  • -mveclibabi=type — specifies the ABI type to use for vectorizing intrinsics using an external library. supported values for type are svml for the Intel short vector math library and acml for the AMD math core library 🌸 to use this option, both -ftree-vectorize and -funsafe-math-optimizations have to be enabled, and an SVML- or ACML-ABI-compatible library must be specified at link time. all three boxes, or nothing, bestie ☑️

GCC currently emits calls to vmldExp2, vmldLn2, vmldLog102, vmldPow2, vmldTanh2, vmldTan2, vmldAtan2, vmldAtanh2, vmldCbrt2, vmldSinh2, vmldSin2, vmldAsinh2, vmldAsin2, vmldCosh2, vmldCos2, vmldAcosh2, vmldAcos2, vmlsExp4, vmlsLn4, vmlsLog104, vmlsPow4, vmlsTanh4, vmlsTan4, vmlsAtan4, vmlsAtanh4, vmlsCbrt4, vmlsSinh4, vmlsSin4, vmlsAsinh4, vmlsAsin4, vmlsCosh4, vmlsCos4, vmlsAcosh4 and vmlsAcos4 for the corresponding function type when -mveclibabi=svml is used 🧚

and it emits calls to __vrd2_sin, __vrd2_cos, __vrd2_exp, __vrd2_log, __vrd2_log2, __vrd2_log10, __vrs4_sinf, __vrs4_cosf, __vrs4_expf, __vrs4_logf, __vrs4_log2f, __vrs4_log10f and __vrs4_powf for the corresponding function type when -mveclibabi=acml is used. that's the whole roster, bestie, all accounted for 🍓

  • -mabi=name — tells GCC which calling convention to build for, bestie 💅. The allowed values are sysv (the ABI used on GNU/Linux and other systems) and ms (the Microsoft ABI). Default? It just knows: Microsoft ABI when you're targeting Microsoft Windows, SysV ABI on literally everything else ✨. And if you wanna control it per-function instead of globally, use the function attributes ms_abi and sysv_abi. Slay.
  • -mforce-indirect-call — forces every single call to a function to be indirect 😳. Sounds unhinged but it's iconic when you're using Intel Processor Trace, because it generates more precise timing information for function calls. Not me making your calls take the scenic route 🦋.
  • -mmanual-endbr — inserts the ENDBR instruction at function entry only via the cf_check function attribute 🔥. Super useful when you pair it with -fcf-protection=branch to control ENDBR insertion at the function entry. Manual vibes only 💅.
  • -mcall-ms2sysv-xlogues — okay so here's the lore 🫶: because of differences in 64-bit ABIs, any Microsoft ABI function that calls a System V ABI function must consider RSI, RDI and XMM6-15 as clobbered. By default the code for saving and restoring those registers is emitted inline, which gives you fairly lengthy prologues and epilogues 😭. With -mcall-ms2sysv-xlogues, GCC emits prologues and epilogues that use stubs in the static portion of libgcc for those saves and restores — so function size goes down, at the cost of a few extra instructions. Trade-offs, babes ✨.
  • -mtls-dialect=type — generates code to access thread-local storage using the gnu or gnu2 conventions 🌸. gnu is the conservative default; gnu2 is more efficient, but it may add compile- and run-time requirements that cannot be satisfied on all systems. Efficiency queen but she has demands 💀.
  • -mpush-args, -mno-push-args — use PUSH operations to store outgoing parameters 🎀. This method is shorter and usually equally fast as the method using SUB/MOV operations, and it's enabled by default. In some cases disabling it may improve performance because of improved scheduling and reduced dependencies. Sometimes less push is more push, iykyk.
  • -maccumulate-outgoing-args — if enabled, the maximum amount of space required for outgoing arguments is computed in the function prologue ✨. This is faster on most modern CPUs thanks to reduced dependencies, improved scheduling, and reduced stack usage when the preferred stack boundary isn't equal to 2. The drawback? A notable increase in code size 🫠. Also, this switch implies -mno-push-args.
  • -mthreads — supports thread-safe exception handling on MinGW 🌈. Programs that rely on thread-safe exception handling must compile and link all code with the -mthreads option. When compiling, -mthreads defines -D_MT; when linking, it links in a special thread helper library -lmingwthrd which cleans up per-thread exception-handling data. Teamwork makes the dream work 🫶.
  • -mms-bitfields, -mno-ms-bitfields — enable/disable bit-field layout compatible with the native Microsoft Windows compiler 👑

If packed is used on a structure, or if bit-fields are used, it may be that the Microsoft ABI lays out the structure differently than the way GCC normally does 😭. Particularly when moving packed data between functions compiled with GCC and the native Microsoft compiler (either via function call or as data in a file), it may be necessary to access either format.

This option is enabled by default for Microsoft Windows targets 💖. This behavior can also be controlled locally by use of variable or type attributes. For more information, see x86 Variable Attributes and x86 Type Attributes.

The Microsoft structure layout algorithm is fairly simple with the exception of the bit-field packing 🎀. The padding and alignment of members of structures and whether a bit-field can straddle a storage-unit boundary are determined by these rules:

  1. Structure members are stored sequentially in the order in which they are declared: the first member has the lowest memory address and the last member the highest.
  2. Every data object has an alignment requirement. The alignment requirement for all data except structures, unions, and arrays is either the size of the object or the current packing size (specified with either the aligned attribute or the pack pragma), whichever is less. For structures, unions, and arrays, the alignment requirement is the largest alignment requirement of its members. Every object is allocated an offset so that:
offset % alignment_requirement == 0
  1. Adjacent bit-fields are packed into the same 1-, 2-, or 4-byte allocation unit if the integral types are the same size and if the next bit-field fits into the current allocation unit without crossing the boundary imposed by the common alignment requirements of the bit-fields.

MSVC interprets zero-length bit-fields in the following ways 👀:

  1. If a zero-length bit-field is inserted between two bit-fields that are normally coalesced, the bit-fields are not coalesced.

For example:

struct
 {
   unsigned long bf_1 : 12;
   unsigned long : 0;
   unsigned long bf_2 : 12;
 } t1;

The size of t1 is 8 bytes with the zero-length bit-field. If the zero-length bit-field were removed, t1's size would be 4 bytes 😳.

  1. If a zero-length bit-field is inserted after a bit-field, foo, and the alignment of the zero-length bit-field is greater than the member that follows it, bar, bar is aligned as the type of the zero-length bit-field.

For example:

struct
 {
   char foo : 4;
   short : 0;
   char bar;
 } t2;

struct
 {
   char foo : 4;
   short : 0;
   double bar;
 } t3;

For t2, bar is placed at offset 2, rather than offset 1. Accordingly, the size of t2 is 4. For t3, the zero-length bit-field does not affect the alignment of bar or, as a result, the size of the structure.

Taking this into account, it is important to note the following:

  1. If a zero-length bit-field follows a normal bit-field, the type of the zero-length bit-field may affect the alignment of the structure as a whole 🌸. For example, t2 has a size of 4 bytes, since the zero-length bit-field follows a normal bit-field, and is of type short.
  2. Even if a zero-length bit-field is not followed by a normal bit-field, it may still affect the alignment of the structure:
struct
 {
   char foo : 6;
   long : 0;
 } t4;

Here, t4 takes up 4 bytes.

  1. Zero-length bit-fields following non-bit-field members are ignored:
struct
 {
   char foo;
   long : 0;
   char bar;
 } t5;

Here, t5 takes up 2 bytes ✨.

  • -mno-align-stringops — don't align the destination of inlined string operations 🦋. This switch reduces code size and improves performance in case the destination is already aligned — but GCC doesn't know about it 😭. She's doing her best.
  • -minline-all-stringops — by default GCC inlines string operations only when the destination is known to be aligned to at least a 4-byte boundary. This enables more inlining and increases code size, but may improve performance of code that depends on fast memcpy and memset for short lengths 🔥. The option enables inline expansion of strlen for all pointer alignments. All the inlining, no crumbs 💅.
  • -minline-stringops-dynamically — for string operations of unknown size, use run-time checks with inline code for small blocks and a library call for large blocks 🎀. Small block gets the fast lane, big block gets sent to the library.
  • -mstringop-strategy=alg — overrides the internal decision heuristic for the particular algorithm to use for inlining string operations ⭐. The allowed values for alg are:
    • rep_byte
    • rep_4byte
    • rep_8byte — expand using i386 rep prefix of the specified size.
    • byte_loop
    • loop
    • unrolled_loop — expand into an inline loop.
    • libcall — always use a library call.
  • -mmemcpy-strategy=strategy — overrides the internal decision heuristic to decide if __builtin_memcpy should be inlined and what inline algorithm to use when the expected size of the copy operation is known 👀. strategy is a comma-separated list of alg:max_size:dest_align triplets. alg is specified in -mstringop-strategy, max_size specifies the max byte size with which inline algorithm alg is allowed. For the last triplet, the max_size must be -1 🫠. The max_size of the triplets in the list must be specified in increasing order. The minimal byte size for alg is 0 for the first triplet and max_size + 1 of the preceding range.
  • -mmemset-strategy=strategy — the option is similar to -mmemcpy-strategy= except that it's there to control __builtin_memset expansion 🧚. Same energy, different builtin.
  • -momit-leaf-frame-pointer — don't keep the frame pointer in a register for leaf functions 🌿. This avoids the instructions to save, set up, and restore frame pointers and makes an extra register available in leaf functions ✨. Heads up though: the option -fomit-leaf-frame-pointer removes the frame pointer for leaf functions, which might make debugging harder 😭. Power at a price.
  • -mtls-direct-seg-refs, -mno-tls-direct-seg-refs — controls whether TLS variables may be accessed with offsets from the TLS segment register (%gs for 32-bit, %fs for 64-bit), or whether the thread base pointer must be added 💜. Whether or not this is valid depends on the operating system, and whether it maps the segment to cover the entire TLS area. For systems that use the GNU C Library, the default is on ✅.
  • -msse2avx, -mno-sse2avx — specify that the assembler should encode SSE instructions with VEX prefix 🦋. The option -mavx turns this on by default. VEX prefix said "I'm the main character now" 💅.
  • -mfentry, -mno-fentry — if profiling is active (-pg), put the profiling counter call before the prologue 🔥. Note: on x86 architectures the attribute ms_hook_prologue isn't possible at the moment for -mfentry and -pg 💀. Don't shoot the messenger, it's literally in the docs.
  • -mrecord-mcount, -mno-record-mcount — ok so if profiling is active (-pg), this generates a __mcount_loc section that's literally full of pointers to each profiling call 💅 it's giving "automatic patching" energy, so you can patch calls in and out later without touching anything by hand. iconic.
  • -mnop-mcount, -mno-nop-mcount — again, if profiling is active (-pg), this one generates the calls to the profiling functions as NOPs instead. why? so they can be patched in later dynamically, bestie ✨ heads up tho: this is likely only useful together with -mrecord-mcount, so don't come crying if you skip that one 🙈
  • -minstrument-return=type — instruments the function exit in -pg -mfentry instrumented functions by calling whatever function you point at. note that it only instruments true returns ending with ret, and not sibling calls ending with jump — the way it's picky about that is so real 😭 valid types are: none (don't instrument, periodt), call (generate a call to __return__), or nop5 (generate a 5 byte nop) 🎀
  • -mrecord-return, -mno-record-return — generates a __return_loc section that points to all the return instrumentation code. cute, organized, we love a paper trail 🌸
  • -mfentry-name=name — sets the name of the __fentry__ symbol that gets called at function entry for -pg -mfentry functions. you're literally renaming the vibe 💫
  • -mfentry-section=name — sets the name of the section that records the -mrecord-mcount calls. the default is __mcount_loc 🎯
  • -mskip-rax-setup, -mno-skip-rax-setup — when you're generating code for x86-64 with SSE extensions disabled, -mskip-rax-setup lets you skip setting up the RAX register when there are no variable arguments passed in vector registers. sounds innocent, right? 😬
Warning: since the RAX register is used to avoid unnecessarily saving vector registers on the stack when passing variable arguments, the impacts of this option are that callees may waste some stack space, misbehave, or literally jump to a random location 💀 GCC 4.4 or newer doesn't have those issues, regardless of the RAX register value. so like… old compilers only, bestie.
  • -m8bit-idiv, -mno-8bit-idiv — on some processors (Intel Atom, I'm looking at you 👀), an 8-bit unsigned integer divide is much faster than a 32-bit/64-bit one. this option generates a run-time check: if both the dividend and the divisor are within the range of 0 to 255, an 8-bit unsigned integer divide is used instead of the 32-bit/64-bit one. speed demon behavior, fr fr 🔥
  • -mavx256-split-unaligned-load, -mavx256-split-unaligned-store — splits 32-byte AVX unaligned load and store. that's it, that's the whole thing 🦋
  • -mstack-protector-guard=guard — generates stack protection code using the canary at guard. supported locations are global for a global canary, or tls for a per-thread canary in the TLS block (which is the default 🌈). this option has effect only when -fstack-protector or -fstack-protector-all is specified, so like, don't expect it to do anything on its own 🙃
  • -mstack-protector-guard-reg=reg, -mstack-protector-guard-offset=offset — with that tls choice, these two further specify which segment register (%fs or %gs) to use as the base register for reading the canary, and from what offset from that base register. the default for those is as specified in the relevant ABI 📎
  • -mgeneral-regs-only — generates code that uses only the general-purpose registers. it literally prevents the compiler from using floating-point, vector, mask, and bound registers. minimalist queen 👑
  • -mrelax-cmpxchg-loop — relaxes the cmpxchg loop by emitting an early load and compare before the cmpxchg, and executing pause if the loaded value isn't what you expected. this reduces excessive cacheline bouncing, and it works for all atomic logic fetch builtins that generate a compare-and-swap loop. less bouncing = more slaying 💅
  • -mindirect-branch=choice — converts indirect call and jump using choice. the default is keep, which keeps indirect call and jump unmodified. thunk converts indirect call and jump to call and return thunk. thunk-inline converts indirect call and jump to an inlined call and return thunk. thunk-extern converts indirect call and jump to an external call and return thunk that's provided in a separate object file. you can control this behavior for a specific function by using the function attribute "indirect_branch" ✨
Note: -mcmodel=large is incompatible with -mindirect-branch=thunk and -mindirect-branch=thunk-extern, since the thunk function may not be reachable in the large code model 😭
Note: -mindirect-branch=thunk-extern is compatible with -fcf-protection=branch, since the external thunk can be made to enable the control-flow check 🫶
  • -mfunction-return=choice — converts function return using choice. the default is keep, which keeps function return unmodified. thunk converts function return to call and return thunk. thunk-inline converts function return to an inlined call and return thunk. thunk-extern converts function return to an external call and return thunk that's provided in a separate object file. you can control this for a specific function with the function attribute "function_return" 🎀
Note: -mindirect-return=thunk-extern is compatible with -fcf-protection=branch, since the external thunk can be made to enable the control-flow check ⭐
Note: -mcmodel=large is incompatible with -mfunction-return=thunk and -mfunction-return=thunk-extern, since the thunk function may not be reachable in the large code model 😤
  • -mindirect-branch-register — forces indirect call and jump via register. no detours, straight through the register 💫
  • -mharden-sls=choice — generates code to mitigate against straight line speculation (SLS) using choice. the default is none, which disables all SLS hardening. return enables SLS hardening for function returns. indirect-jmp enables SLS hardening for indirect jumps. all enables all SLS hardening 🛡️
  • -mindirect-branch-cs-prefix — adds a CS prefix to call and jmp to indirect thunk when the branch target is in the r8-r15 registers, so that the call and jmp instruction length is 6 bytes. why 6? so they can be replaced at run-time with lfence; call *%r8-r15 or lfence; jmp *%r8-r15 🔥

okay and now for the plot twist: these -m switches are supported in addition to the above on x86-64 processors in 64-bit environments 👑

  • -m32 — generates code for a 32-bit environment. it sets int, long, and pointer types to 32 bits, and generates code that runs on any i386 system 🧚
  • -m64 — generates code for a 64-bit environment. it sets int to 32 bits and long and pointer types to 64 bits, and generates code for the x86-64 architecture. Darwin-only tea: with -m64 it also turns off the -fno-pic and -mdynamic-no-pic options ☕
  • -mx32 — sets int, long, and pointer types to 32 bits, and generates code for the x86-64 architecture 🦋
  • -m16 — the same as -m32, except that it outputs the .code16gcc assembly directive at the beginning of the assembly output, so the binary can run in 16-bit mode 🎀
  • -miamcu — generates code that conforms to Intel MCU psABI. it requires the -m32 option to be turned on, no exceptions bestie 🙅
  • -mno-red-zone — do not use a so-called "red zone" for x86-64 code. the red zone is mandated by the x86-64 ABI — it's a 128-byte area beyond the location of the stack pointer that isn't modified by signal or interrupt handlers, so it can be used for temporary data without adjusting the stack pointer. -mno-red-zone disables this red zone. bye bye red zone 🚫
  • -mcmodel=small — generates code for the small code model: the program and its symbols must be linked in the lower 2 GB of the address space. pointers are 64 bits. programs can be statically or dynamically linked. this is the default code model, so it's basically the main character 👑
  • -mcmodel=kernel — generates code for the kernel code model. the kernel runs in the negative 2 GB of the address space, and this model has to be used for Linux kernel code. mandatory, no discussion 🐧
  • -mcmodel=medium — generates code for the medium model: the program is linked in the lower 2 GB of the address space. small symbols are also placed there. symbols with sizes larger than -mlarge-data-threshold get put into large data or BSS sections and can be located above 2 GB. programs can be statically or dynamically linked 🌈
  • -mcmodel=large — generates code for the large model. this model makes no assumptions about addresses and sizes of sections. go big or go home 😤
  • -maddress-mode=long — generates code for long address mode. this is only supported for 64-bit and x32 environments, and it's the default address mode for 64-bit environments 📏
  • -maddress-mode=short — generates code for short address mode. this is only supported for 32-bit and x32 environments, and it's the default address mode for 32-bit and x32 environments 📐
  • -mneeded, -mno-needed — emits a GNU_PROPERTY_X86_ISA_1_NEEDED GNU property for the Linux target, to indicate the micro-architecture ISA level required to execute the binary. little post-it note for the loader, iykyk 🗒️
  • -mno-direct-extern-access — without -fpic or -fPIC, always use the GOT pointer to access external symbols. with -fpic or -fPIC, treat access to protected symbols as local symbols. the default is -mdirect-extern-access 💅
Warning: shared libraries compiled with -mno-direct-extern-access and executables compiled with -mdirect-extern-access may not be binary compatible if protected symbols are used in both the shared libraries and the executable. do not mix and match, bestie, I'm begging 😭

🪟 x86 Windows Options 🪟

these additional options are available for Microsoft Windows targets:

  • -mconsole — specifies that a console application is to be generated, by instructing the linker to set the PE header subsystem type that console applications require. available for Cygwin and MinGW targets, and it's enabled by default on those targets. convenient ✨
  • -mdll — available for Cygwin and MinGW targets. it specifies that a DLL — a dynamic link library — is to be generated, which enables the selection of the required runtime startup object and entry point. very demure, very DLL 🎀
  • -mnop-fun-dllimport — available for Cygwin and MinGW targets. it specifies that the dllimport attribute should be ignored. nope, not today 🙈
  • -mthreads — available for MinGW targets. it specifies that MinGW-specific thread support is to be used. threads, but make it MinGW 💫
  • -municode — available for MinGW-w64 targets. it causes the UNICODE preprocessor macro to be predefined, and chooses Unicode-capable runtime startup code. unicode girlies rise 🌍
  • -mwin32 — available for Cygwin and MinGW targets. it specifies that the typical Microsoft Windows predefined macros are to be set in the pre-processor, but it does not influence the choice of runtime library/startup code. macros yes, runtime no 🚧
  • -mwindows — Cygwin and MinGW only, bestie 💅. This one says "make me a GUI app," and it does that by telling the linker to set the PE header subsystem type all properly. Windowed vibes only, no console era.
  • -fno-set-stack-executable — MinGW targets only. It means the executable flag for the stack that nested functions use is not set. Why do we care? Because binaries running in kernel mode on Microsoft Windows genuinely need this — the User32 API, which is the thing you'd normally use to set executable privileges, just isn't available there. So yeah, it's a whole situation. 😭
  • -fwritable-relocated-rdata — available for MinGW and Cygwin targets 🫶. Says: relocated data hanging out in a read-only section gets moved into the ".data" section instead. This is necessary for older runtimes that don't support modifying ".rdata" sections for pseudo-relocation. Legacy runtime support, we love to see it.
  • -mpe-aligned-commons — Cygwin and MinGW targets. Tells GCC to use the GNU extension to the PE file format that allows COMMON variables to be aligned correctly when generating code ✨. It's enabled by default if GCC figures out during configuration that the target assembler supports the feature. So it might already be doing this for you, ngl.

See also under x86 Options for standard options — don't forget to check over there, bestie 👀.


🦋 Xstormy16 Options 🦋

These options are defined for Xstormy16. Yes, that's the whole vibe:

  • -msim — choose startup files and a linker script suitable for the simulator. Simulator era 💅.

🎀 Xtensa Options 🎀

These options are supported for Xtensa targets — and there are a lot of them, so buckle up:

  • -mconst16, -mno-const16 — enable or disable use of CONST16 instructions for loading constant values. Important lore: the CONST16 instruction is currently not a standard option from Tensilica. When it's enabled, CONST16 instructions are always used in place of the standard L32R instructions. And the use of CONST16 is enabled by default only if the L32R instruction isn't available. iykyk.
  • -mfused-madd, -mno-fused-madd — enable or disable fused multiply/add and multiply/subtract instructions in the floating-point option. Heads up: this has no effect if the floating-point option isn't also enabled. Disabling these forces the compiler to use separate instructions for the multiply and the add/subtract. Why would you want that? Because fused multiply add/subtract instructions don't round the intermediate result, so they can produce results with more bits of precision than the IEEE standard specifies 😳. So if you need strict IEEE 754-compliant results, this is your girl. Disabling them also makes sure your program output isn't sensitive to the compiler's ability to combine multiply and add/subtract operations. Consistency, periodt.
  • -mserialize-volatile, -mno-serialize-volatile — when enabled, GCC inserts MEMW instructions before volatile memory references to guarantee sequential consistency. Default is -mserialize-volatile. Use -mno-serialize-volatile to omit the MEMW instructions. Simple as that 💖.
  • -mforce-no-pic — for targets like GNU/Linux where all user-mode Xtensa code has to be position-independent code (PIC), this option disables PIC so you can compile kernel code. Kernel girlies, this one's for you 🔥.
  • -mtext-section-literals, -mno-text-section-literals — control the treatment of literal pools. Default is -mno-text-section-literals, which places literals in a separate section in the output file. That's lowkey iconic: it lets the literal pool go in a data RAM/ROM, and it also lets the linker combine literal pools from separate object files to drop redundant literals and improve code size. With -mtext-section-literals, the literals get interspersed in the text section so they stay as close as possible to their references — which may be necessary for large assembly files. Literals for each function are placed right before that function. Proximity era 💫.
  • -mauto-litpools, -mno-auto-litpools — also control the treatment of literal pools. Default is -mno-auto-litpools, which places literals in a separate section in the output file unless -mtext-section-literals is used. With -mauto-litpools, the assembler intersperses the literals in the text section. The compiler does not produce explicit ".literal" directives and loads literals into registers with MOVI instructions instead of L32R, so the assembler can do relaxation and place literals as needed. This lets the assembler create several literal pools per function and assemble very big functions — which may not be possible with -mtext-section-literals. Big function energy 🌸.
  • -mtarget-align, -mno-target-align — when enabled, GCC tells the assembler to automatically align instructions to reduce branch penalties, at the expense of some code density. The assembler tries to widen density instructions to align branch targets and the instructions following call instructions. If there aren't enough preceding safe density instructions to align a target, no widening happens — no forced slay. Default is -mtarget-align. Note: these options do not affect the treatment of auto-aligned instructions like LOOP, which the assembler always aligns, either by widening density instructions or by inserting NOP instructions. It's got main character energy and it will not be told otherwise.
  • -mlongcalls, -mno-longcalls — when enabled, GCC tells the assembler to translate direct calls into indirect calls unless it can determine that the target of a direct call is in the range allowed by the call instruction. This typically happens for calls to functions in other source files. Specifically, the assembler translates a direct CALL instruction into an L32R followed by a CALLX instruction. Default is -mno-longcalls. Use this in programs where the call target can potentially be out of range 📞. One thing though: this option is implemented in the assembler, not the compiler — so the assembly code generated by GCC still shows direct call instructions. Look at the disassembled object code to see the actual instructions, bestie. And note that the assembler uses an indirect call for every cross-file call, not just the ones that really are out of range. Yeah. Every single one. 💀
  • -mabi=name — generate code for the specified ABI. Permissible values are: call0, windowed. The default ABI is chosen by the Xtensa core configuration ✨.
  • -mabi=call0 — when this is enabled, function parameters are passed in registers a2 through a7, registers a12 through a15 are caller-saved, and register a15 may be used as a frame pointer. When this version of the ABI is enabled, the C preprocessor symbol __XTENSA_CALL0_ABI__ is defined 🎀.
  • -mabi=windowed — when this is enabled, function parameters are passed in registers a10 through a15, and the called function rotates the register window by 8 registers on entry so its arguments are found in registers a2 through a7. Register a7 may be used as a frame pointer. The register window is rotated 8 registers back upon return. When this version of the ABI is enabled, the C preprocessor symbol __XTENSA_WINDOWED_ABI__ is defined. Window rotation is such a flex 🌀.

👑 zSeries Options 👑

These are listed under

🌸 ENVIRONMENT 🌸

okay bestie so this whole section is about the env vars that change how gcc behaves 💅 like, some of them literally just tell it where to go look for files, others are vibe-setters for the whole compile environment. both valid.

lowkey important heads-up first: you can ALSO tell gcc where to search with options like -B, -I and -L. and those win. like, options come first, then environment variables, then whatever gcc was configured with at build time. that's the order, no cap 🫶

💖 LANG, LC_CTYPE, LC_MESSAGES, LC_ALL

these four control how gcc handles localization info, so it can vibe with different national conventions 🌍 gcc checks the LC_CTYPE and LC_MESSAGES locale categories if it's been configured to do so. they can be set to literally any value your installation supports. a typical one is en_GB.UTF-8 for English in the United Kingdom, encoded in UTF-8 ✨

LC_CTYPE is the character-classification one. gcc uses it to figure out character boundaries in a string — which you need for some multibyte encodings that contain quote and escape characters that would otherwise get read as a string end or an escape. messy, honestly 😭

LC_MESSAGES is which language the diagnostic messages come out in.

and if LC_ALL is set, it overrides both LC_CTYPE and LC_MESSAGES. otherwise those two default to whatever LANG is. and if like, none of them are set? gcc just defaults to traditional C English behavior. classic 👑

🫧 TMPDIR

if TMPDIR is set, that's the directory used for temporary files. gcc holds the output of one compilation stage there while it's waiting to be the input to the next stage — like, the output of the preprocessor is the input to the compiler proper. pipeline things 🎀

🔍 GCC_COMPARE_DEBUG

setting GCC_COMPARE_DEBUG is nearly equivalent to passing -fcompare-debug to the compiler driver. go read that option's docs for the details, iykyk 💅

🌈 GCC_EXEC_PREFIX

if GCC_EXEC_PREFIX is set, it's a prefix used in the names of the subprograms the compiler executes. no slash gets added when the prefix is combined with a subprogram name — but you can hand it a prefix that already ends in a slash if that's your thing ✨

if it's not set, gcc tries to figure out a sensible prefix based on the pathname it was invoked with.

and if gcc can't find the subprogram using the prefix you gave? it goes looking in the usual places instead. no drama 🦋

the default value of GCC_EXEC_PREFIX is prefix/lib/gcc/, where prefix is the prefix of the installed compiler. in many cases prefix is the value of "prefix" when you ran the configure script.

other prefixes given with -B take priority over this one, bestie. respect the hierarchy 🫶

this prefix is also used for finding files like crt0.o that are used for linking.

and here's the weird-but-real part — it's used in an unusual way when finding header file search directories 👀 for each of the standard directories whose name normally begins with /usr/local/lib/gcc (more precisely, begins with the value of GCC_INCLUDE_DIR), gcc tries replacing that beginning with the specified prefix to make an alternate directory name. so with -Bfoo/, gcc searches foo/bar just before it searches the standard directory /usr/local/lib/bar. and if a standard directory begins with the configured prefix, then the value of prefix gets replaced by GCC_EXEC_PREFIX when looking for header files. chaotic but iconic 💀

🧚 COMPILER_PATH

the value of COMPILER_PATH is a colon-separated list of directories, basically like PATH. gcc tries those directories when searching for subprograms, if it can't find them using GCC_EXEC_PREFIX 💜

📚 LIBRARY_PATH

same deal: LIBRARY_PATH is a colon-separated list of directories, much like PATH. when configured as a native compiler, gcc tries those directories when hunting for special linker files, if GCC_EXEC_PREFIX didn't come through. and linking with gcc also uses these directories when looking for ordinary libraries for the -l option — but directories given with -L come first, always 💅

🌟 LANG

(yeah it's back, different job, don't @ me)

this variable passes locale info to the compiler. one way that info gets used is deciding the character set for parsing character literals, string literals and comments in C and C++. when the compiler is configured to allow multibyte characters, these LANG values are recognized:

  • C-JIS — recognize JIS characters.
  • C-SJIS — recognize SJIS characters.
  • C-EUCJP — recognize EUCJP characters.

if LANG isn't defined, or it's some other value entirely, the compiler uses mblen and mbtowc as defined by the default locale to recognize and translate multibyte characters ✨

🩹 GCC_EXTRA_DIAGNOSTIC_OUTPUT

if GCC_EXTRA_DIAGNOSTIC_OUTPUT is set to one of these values, extra text gets emitted to stderr whenever fix-it hints are emitted 🎀 and just so we're clear: -fdiagnostics-parseable-fixits and -fno-diagnostics-parseable-fixits take precedence over this environment variable.

  • fixits-v1 — emit parseable fix-it hints, equivalent to -fdiagnostics-parseable-fixits. in particular, columns are expressed as a count of bytes, starting at byte 1 for the initial column.
  • fixits-v2 — same as "fixits-v1", but columns are expressed as display columns, per -fdiagnostics-column-unit=display.

and there are some extra environment variables that change how the preprocessor acts 👀

🦋 CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH, OBJC_INCLUDE_PATH

each one's value is a list of directories separated by a special character, much like PATH, to look through for header files. that special character, "PATH_SEPARATOR", is target-dependent and decided at GCC build time. for Microsoft Windows-based targets it's a semicolon, and for almost literally every other target it's a colon 💅

CPATH is a list of directories searched as if you'd said -I, but after any paths given with -I options on the command line. and this one applies no matter which language is being preprocessed 🌈

the remaining ones only apply when preprocessing the particular language they name. each is a list of directories searched as if given with -isystem, but after any paths given with -isystem options on the command line.

in all of these variables, an empty element tells the compiler to search its current working directory — and empty elements can sit at the beginning or the end of a path. for instance, if CPATH is :/special/include, that does the same thing as -I. -I/special/include ✨

🍓 DEPENDENCIES_OUTPUT

if this is set, its value says how to output dependencies for Make, based on the non-system header files the compiler processed. system header files get ignored in the dependency output 🫶

the value can be just a file name — in which case the Make rules get written to that file, and the target name is guessed from the source file name. or the value can have the form file target, in which case the rules are written to file using target as the target name.

in other words: this env var is equivalent to combining -MM and -MF, with an optional -MT switch thrown in too 💜

🧚 SUNPRO_DEPENDENCIES

same as DEPENDENCIES_OUTPUT (see right above 👆), except system header files are not ignored — so it implies -M rather than -MM. however, the dependence on the main input file is left out. little trade-off, no biggie 🌸

⏰ SOURCE_DATE_EPOCH

if this is set, its value is a UNIX timestamp used in place of the current date and time in the __DATE__ and __TIME__ macros, so the embedded timestamps become reproducible 🔥 reproducible builds girlies rise

the value of SOURCE_DATE_EPOCH has to be a UNIX timestamp — defined as the number of seconds (excluding leap seconds) since 01 Jan 1970 00:00:00, represented in ASCII. it's identical to the output of date +%s on GNU/Linux and other systems that support the %s extension in the date command.

and bestie, the value should be a known timestamp, like the last modification time of the source or package — and it should be set by the build process 🎀


💀 BUGS 💀

for instructions on reporting bugs, see <https://gcc.gnu.org/bugs/>. please actually read them before you @ us, love u 🙈


📎 FOOTNOTES 📎

  1. on some systems, gcc -shared needs to build supplementary stub code for constructors to work. on multi-libbed systems, gcc -shared must select the correct support libraries to link against. failing to supply the correct flags may lead to subtle defects. supplying them when they're not actually necessary is innocuous — so like, harmless. no cap 🫶

👀 SEE ALSO 👀

gpl(7), gfdl(7), fsf-funding(7), cpp(1), gcov(1), as(1), ld(1), gdb(1), dbx(1) and the Info entries for gcc, cpp, as, ld, binutils and gdb. go read them, they're iconic 🧚


👑 AUTHOR 👑

see the Info entry for gcc, or <https://gcc.gnu.org/onlinedocs/gcc/Contributors.html>, for contributors to GCC 💖


Copyright (c) 1988-2022 Free Software Foundation, Inc.

permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "GNU General Public License" and "Funding Free Software", the Front-Cover texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). a copy of the license is included in the gfdl(7) man page ✨

(a) the FSF's Front-Cover Text is:

     A GNU Manual

(b) the FSF's Back-Cover Text is:

     You have freedom to copy and modify this GNU Manual, like GNU
     software.  Copies published by the Free Software Foundation raise
     funds for GNU development.

and that's the whole page, bestie 🎀 this was gcc-12.2.0, dated 2022-08-19, and you made it all the way to the end of GCC(1) — genuinely iconic behavior, go compile something beautiful 💅✨🦋

📦 where this page comes from