GCC(1)

๐Ÿ“ฆ
version 11.5.0 ยท 2 versions
, in ubuntu noble

okay so real talk bestie โ€” this is the manual page for GCC(1), the GNU project C and C++ compiler, and it is iconic. It's also long, so buckle up, hydrate, and let's go. ๐Ÿ’–


๐ŸŒธ NAME ๐ŸŒธ

gcc โ€” the GNU project C and C++ compiler. That's the whole name section. Short, sweet, main character energy. ๐Ÿ’…


โœจ SYNOPSIS โœจ

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

not me listing only the most useful options up there โ€” the rest of them are literally right below, keep scrolling, bestie. And heads up: g++ accepts mostly the same options as gcc. ๐Ÿซถ


๐Ÿ’– DESCRIPTION ๐Ÿ’–

So when you invoke GCC, it normally does preprocessing, compilation, assembly and linking. All four. In a row. Slay. โœจ

The "overall options" let you stop that whole process at an intermediate stage. For example, the -c option says do not run the linker. And then what you get as output is object files output by the assembler. Cute, right?

Other options get passed on to one or more stages of processing. Some options control the preprocessor, others control the compiler itself. And yet other options control the assembler and the linker โ€” but most of those are not documented here, because honestly you rarely need to use any of them. ๐Ÿ™ˆ

Most of the command-line options 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. And if the description for a particular option doesn't mention a source language? Then you can use that option with all supported languages. Periodt. ๐Ÿ’…

The usual way to run GCC is to run the executable called gcc, or machine-gcc when you're cross-compiling, or machine-gcc-version to run a specific version of GCC. And when you compile C++ programs, you should invoke GCC as g++ instead. iykyk. ๐ŸŒˆ

The gcc program accepts options and file names as operands. Now โ€” many options have multi-letter names, and therefore multiple single-letter options may not be grouped: -dv is very different from -d -v. Do not do the grouping thing. I'm serious. ๐Ÿ˜ญ

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. And if you want the full listing and explanation of the binary and decimal byte size prefixes, go refer to the NIST, IEC, and other relevant national and international standards. ๐Ÿ“š (yes, the standards bodies. they ate.)


๐Ÿ‘‘ OPTIONS ๐Ÿ‘‘

๐Ÿงš Option Summary ๐Ÿงš

Here's the whole summary of all the options, grouped by type. The explanations live in the sections that follow. ๐Ÿฆ‹

๐ŸŽ€ 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
  • -fgnu89-inline
  • -fpermitted-flt-eval-methods=standard
  • -aux-info filename
  • -fallow-parameterless-variadic-functions
  • -fno-asm
  • -fno-builtin
  • -fno-builtin-function
  • -fgimple
  • -fhosted
  • -ffreestanding
  • -fopenacc
  • -fopenacc-dim=geom
  • -fopenmp
  • -fopenmp-simd
  • -fms-extensions
  • -fplan9-extensions
  • -fsso-struct=endianness
  • -fallow-single-precision
  • -fcond-mismatch
  • -flax-vector-conversions
  • -fsigned-bitfields
  • -fsigned-char
  • -funsigned-bitfields
  • -funsigned-char

๐ŸŽ€ 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
  • -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
  • -Wno-mismatched-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

๐Ÿ’– Warning Options ๐Ÿ’–

okay bestie, deep breath. this is the list. the one that goes on for so long your terminal scrollback gives up. every single one of these is a warning flag, and we're gonna walk through the whole roll call together, no skipping, no "eh you get the idea". you get all of it. ๐Ÿซถ


๐ŸŒธ the opening acts ๐ŸŒธ

  • -fsyntax-only
  • -fmax-errors=n
  • -Wpedantic
  • -pedantic-errors
  • -w
  • -Wextra
  • -Wall

๐Ÿฆ‹ the a-through-b chapter ๐Ÿฆ‹

  • -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
  • -Wno-attributes
  • -Wattribute-alias=n
  • -Wno-attribute-alias
  • -Wno-attribute-warning
  • -Wbool-compare
  • -Wbool-operation
  • -Wno-builtin-declaration-mismatch
  • -Wno-builtin-macro-redefined

โœจ the C and C++ compat girlies โœจ

not me getting emotional over how many standards there are. every era gets its own flag, and honestly? iconic.

  • -Wc90-c99-compat
  • -Wc99-c11-compat
  • -Wc11-c2x-compat
  • -Wc++-compat
  • -Wc++11-compat
  • -Wc++14-compat
  • -Wc++17-compat
  • -Wc++20-compat
  • -Wcast-align
  • -Wcast-align=strict
  • -Wcast-function-type
  • -Wcast-qual
  • -Wchar-subscripts
  • -Wclobbered
  • -Wcomment
  • -Wconversion
  • -Wno-coverage-mismatch
  • -Wno-cpp
  • -Wdangling-else
  • -Wdate-time

๐ŸŽ€ the d-through-f saga ๐ŸŽ€

  • -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=*
  • -Wexpansion-to-defined
  • -Wfatal-errors
  • -Wfloat-conversion
  • -Wfloat-equal
bestie -Werror is right there in the middle of the list like it's not the single most plot-twist flag in the whole section. the audacity. ๐Ÿ’€

๐ŸŒˆ the format era ๐ŸŒˆ

  • -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

๐Ÿ’œ the i-through-m run ๐Ÿ’œ

  • -Wno-implicit-function-declaration
  • -Wno-implicit-int
  • -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

๐Ÿ“ the missing-everything chapter ๐Ÿ“

look at all these -Wmissing- girlies. they're all just out here noticing what you forgot to write. supportive, honestly.

  • -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
  • -Wopenmp-simd
  • -Wno-overflow
  • -Woverlength-strings
  • -Wno-override-init-side-effects
  • -Wpacked
  • -Wno-packed-bitfield-compat

๐Ÿงš the p-through-s glow-up ๐Ÿงš

  • -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

๐Ÿ’… the shift/sizeof/sign situation ๐Ÿ’…

  • -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

๐Ÿ‘‘ the s-through-u finale ๐Ÿ‘‘

  • -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
  • -Wtsan
  • -Wtype-limits
  • -Wundef
  • -Wuninitialized
  • -Wunknown-pragmas
  • -Wunsuffixed-float-constants
  • -Wunused

๐ŸŒŸ the unused-and-beyond send-off ๐ŸŒŸ

and that's the whole warning roster. yes, all of it. we ate. ๐Ÿ”ฅ

  • -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

๐Ÿ”ฌ Static Analyzer Options ๐Ÿ”ฌ

next up: the static analyzer squad. these ones are the deep-dive girlies, the ones that actually sit down and read your whole program like it's a group chat they got added to late. ๐Ÿ•ต๏ธโ€โ™€๏ธ

๐Ÿง  the core analyzer flags ๐Ÿง 

  • -fanalyzer
  • -fanalyzer-call-summaries
  • -fanalyzer-checker=name
  • -fno-analyzer-feasibility
  • -fanalyzer-fine-grained
  • -fanalyzer-state-merge
  • -fanalyzer-state-purge
  • -fanalyzer-transitivity
  • -fanalyzer-verbose-edges
  • -fanalyzer-verbose-state-changes
  • -fanalyzer-verbosity=level

๐Ÿ—‚๏ธ the dump crew ๐Ÿ—‚๏ธ

  • -fdump-analyzer
  • -fdump-analyzer-stderr
  • -fdump-analyzer-callgraph
  • -fdump-analyzer-exploded-graph
  • -fdump-analyzer-exploded-nodes
  • -fdump-analyzer-exploded-nodes-2
  • -fdump-analyzer-exploded-nodes-3
  • -fdump-analyzer-feasibility
  • -fdump-analyzer-json
  • -fdump-analyzer-state-purge
  • -fdump-analyzer-supergraph

๐Ÿšจ the analyzer warning list ๐Ÿšจ

  • -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-array-index
  • -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 for the C and Objective-C besties specifically. if that's not your language, no worries, scroll on. if it is? hi, this is your section. ๐Ÿ’Œ

  • -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 ๐Ÿ›

and now the debugging section, aka the "what actually happened in my program" corner. -g girlies rise up. ๐Ÿซก

๐ŸŽฌ the g-family basics ๐ŸŽฌ

  • -g
  • -glevel
  • -gdwarf
  • -gdwarf-version
  • -ggdb
  • -grecord-gcc-switches
  • -gno-record-gcc-switches
  • -gstabs
  • -gstabs+
  • -gstrict-dwarf
  • -gno-strict-dwarf

๐Ÿ“ the location-tracking era ๐Ÿ“

  • -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

๐Ÿ—œ๏ธ the other debug formats + compression ๐Ÿ—œ๏ธ

  • -gvms
  • -gxcoff
  • -gxcoff+
  • -gz[=type]
  • -gsplit-dwarf
  • -gdescribe-dies
  • -gno-describe-dies

๐Ÿ”ง the f-prefixed debug knobs ๐Ÿ”ง

  • -fdebug-prefix-map=old=new
  • -fdebug-types-section
  • -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

โœจ Optimization Options โœจ

okay bestie, this is the optimization menu and it's literally a whole buffet of compiler glow-up flags. no cap, there are so many. Let's go through every single one, fr fr.

  • -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
  • -fauto-profile
  • -fauto-profile[=path]
  • -fauto-inc-dec
  • -fbranch-probabilities
  • -fcaller-saves
  • -fcombine-stack-adjustments
  • -fconserve-stack
  • -fcompare-elim
  • -fcprop-registers
  • -fcrossjumping
  • -fcse-follow-jumps
  • -fcse-skip-blocks
  • -fcx-fortran-rules
  • -fcx-limited-range
  • -fdata-sections
  • -fdce
  • -fdelayed-branch
  • -fdelete-null-pointer-checks
  • -fdevirtualize
  • -fdevirtualize-speculatively
  • -fdevirtualize-at-ltrans
  • -fdse
  • -fearly-inlining
  • -fipa-sra
  • -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
  • -fipa-modref
  • -fipa-cp
  • -fipa-cp-clone
  • -fipa-bit-cp
  • -fipa-vrp
  • -fipa-pta
  • -fipa-profile
  • -fipa-pure-const
  • -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
  • -fkeep-static-consts
  • -flimit-function-alignment
  • -flive-range-shrinkage
  • -floop-block
  • -floop-interchange
  • -floop-strip-mine
  • -floop-unroll-and-jam
  • -floop-nest-optimize
  • -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
  • -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
  • -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-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
  • -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
  • -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
  • -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
  • -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

๐ŸŽ€ Program Instrumentation Options ๐ŸŽ€

next up, instrumentation. this is where you spy on your program but in a cute way. ๐Ÿ‘€

  • -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]
  • -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]
  • -fstack-protector
  • -fstack-protector-all
  • -fstack-protector-strong
  • -fstack-protector-explicit
  • -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,...

๐ŸŒธ Preprocessor Options ๐ŸŒธ

preprocessor time! it's giving 'before the main event' energy. ๐Ÿ’…

  • -Aquestion=answer
  • -A-question[=answer]
  • -C
  • -CC
  • -Dmacro[=defn]
  • -dD
  • -dI
  • -dM
  • -dN
  • -dU
  • -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
  • -no-integrated-cpp
  • -P
  • -pthread
  • -remap
  • -traditional
  • -traditional-cpp
  • -trigraphs
  • -Umacro
  • -undef
  • -Wp,option
  • -Xpreprocessor option

โœจ Assembler Options โœจ

assembler options, short and sweet. โœจ

  • -Wa,option
  • -Xassembler option

๐Ÿ‘‘ Linker Options ๐Ÿ‘‘

<link>linker options, the final boss of building.</link> ๐Ÿ‘‘

  • object-file-name
  • -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
  • -shared
  • -shared-libgcc
  • -symbolic
  • -T script
  • -Wl,option
  • -Xlinker option
  • -u symbol
  • -z keyword

๐Ÿ—บ๏ธ Directory Options ๐Ÿ—บ๏ธ

directory options, for when you need to tell the compiler where stuff is. ๐Ÿ—บ๏ธ

  • -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

๐Ÿ”ฅ Code Generation Options ๐Ÿ”ฅ

code generation options, this is where the magic happens. ๐Ÿ”ฅ

  • -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

๐Ÿง Developer Options ๐Ÿง

developer options, for when you want to peek behind the curtain. ๐Ÿง

  • -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
  • -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]

๐Ÿ’โ€โ™€๏ธ Machine-Dependent Options ๐Ÿ’โ€โ™€๏ธ

machine-dependent options, because every architecture is a little different.

AArch64 Options

  • -mabi=name
  • -mbig-endian
  • -mlittle-endian
  • -mgeneral-regs-only
  • -mcmodel=tiny
  • -mcmodel=small
  • -mcmodel=large
  • -mstrict-align
  • -mno-strict-align
  • -momit-leaf-frame-pointer
  • -mtls-dialect=desc
  • -mtls-dialect=traditional
  • -mtls-size=size
  • -mfix-cortex-a53-835769
  • -mfix-cortex-a53-843419
  • -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
  • -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

๐ŸŒธ Adapteva Epiphany Options

okay so if you're out here targeting Epiphany, this is your whole lil kit, bestie โ€” every single one of these, no skips:

  • -mhalf-reg-file
  • -mprefer-short-insn-regs
  • -mbranch-cost=num
  • -mcmove
  • -mnops=num
  • -msoft-cmpsf
  • -msplit-lohi
  • -mpost-inc
  • -mpost-modify
  • -mstack-offset=num
  • -mround-nearest
  • -mlong-calls
  • -mshort-calls
  • -msmall16
  • -mfp-mode=mode
  • -mvect-double
  • -max-vect-align=num
  • -msplit-vecmove-early
  • -m1reg-reg

๐Ÿ’œ AMD GCN Options

short, sweet, absolutely serving:

  • -march=gpu
  • -mtune=gpu
  • -mstack-size=bytes

๐Ÿฆ‹ ARC Options

ARC has so many of these it's giving encyclopedia, but we're listing all of them because that's the vibe ๐Ÿ’…

  • -mbarrel-shifter
  • -mjli-always
  • -mcpu=cpu
  • -mA6
  • -mARC600
  • -mA7
  • -mARC700
  • -mdpfp
  • -mdpfp-compact
  • -mdpfp-fast
  • -mno-dpfp-lrsr
  • -mea
  • -mno-mpy
  • -mmul32x16
  • -mmul64
  • -matomic
  • -mnorm
  • -mspfp
  • -mspfp-compact
  • -mspfp-fast
  • -msimd
  • -msoft-float
  • -mswap
  • -mcrc
  • -mdsp-packa
  • -mdvbf
  • -mlock
  • -mmac-d16
  • -mmac-24
  • -mrtsc
  • -mswape
  • -mtelephony
  • -mxy
  • -misize
  • -mannotate-align
  • -marclinux
  • -marclinux_prof
  • -mlong-calls
  • -mmedium-calls
  • -msdata
  • -mirq-ctrl-saved
  • -mrgf-banked-regs
  • -mlpc-width=width
  • -G num
  • -mvolatile-cache
  • -mtp-regno=regno
  • -malign-call
  • -mauto-modify-reg
  • -mbbit-peephole
  • -mno-brcc
  • -mcase-vector-pcrel
  • -mcompact-casesi
  • -mno-cond-exec
  • -mearly-cbranchsi
  • -mexpand-adddi
  • -mindexed-loads
  • -mlra
  • -mlra-priority-none
  • -mlra-priority-compact
  • mlra-priority-noncompact
  • -mmillicode
  • -mmixed-code
  • -mq-class
  • -mRcq
  • -mRcw
  • -msize-level=level
  • -mtune=cpu
  • -mmultcost=num
  • -mcode-density-frame
  • -munalign-prob-threshold=probability
  • -mmpy-option=multo
  • -mdiv-rem
  • -mcode-density
  • -mll64
  • -mfpu=fpu
  • -mrf16
  • -mbranch-index
not me pointing out that mlra-priority-noncompact is sitting there with no dash, exactly as written, because we do not fix things around here ๐Ÿซถ

๐ŸŽ€ ARM Options

the ARM roster, iconic as always:

  • -mapcs-frame
  • -mno-apcs-frame
  • -mabi=name
  • -mapcs-stack-check
  • -mno-apcs-stack-check
  • -mapcs-reentrant
  • -mno-apcs-reentrant
  • -mgeneral-regs-only
  • -msched-prolog
  • -mno-sched-prolog
  • -mlittle-endian
  • -mbig-endian
  • -mbe8
  • -mbe32
  • -mfloat-abi=name
  • -mfp16-format=name
  • -mthumb-interwork
  • -mno-thumb-interwork
  • -mcpu=name
  • -march=name
  • -mfpu=name
  • -mtune=name
  • -mprint-tune-info
  • -mstructure-size-boundary=n
  • -mabort-on-noreturn
  • -mlong-calls
  • -mno-long-calls
  • -msingle-pic-base
  • -mno-single-pic-base
  • -mpic-register=reg
  • -mnop-fun-dllimport
  • -mpoke-function-name
  • -mthumb
  • -marm
  • -mflip-thumb
  • -mtpcs-frame
  • -mtpcs-leaf-frame
  • -mcaller-super-interworking
  • -mcallee-super-interworking
  • -mtp=name
  • -mtls-dialect=dialect
  • -mword-relocations
  • -mfix-cortex-m3-ldrd
  • -munaligned-access
  • -mneon-for-64bits
  • -mslow-flash-data
  • -masm-syntax-unified
  • -mrestrict-it
  • -mverbose-cost-dump
  • -mpure-code
  • -mcmse
  • -mfix-cmse-cve-2021-35465
  • -mfdpic

๐ŸŒˆ AVR Options

tiny chip, big personality:

  • -mmcu=mcu
  • -mabsdata
  • -maccumulate-args
  • -mbranch-cost=cost
  • -mcall-prologues
  • -mgas-isr-prologues
  • -mint8
  • -mdouble=bits
  • -mlong-double=bits
  • -mn_flash=size
  • -mno-interrupts
  • -mmain-is-OS_task
  • -mrelax
  • -mrmw
  • -mstrict-X
  • -mtiny-stack
  • -mfract-convert-truncate
  • -mshort-calls
  • -nodevicelib
  • -nodevicespecs
  • -Waddr-space-convert
  • -Wmisspelled-isr

๐Ÿงš Blackfin Options

  • -mcpu=cpu[-sirevision]
  • -msim
  • -momit-leaf-frame-pointer
  • -mno-omit-leaf-frame-pointer
  • -mspecld-anomaly
  • -mno-specld-anomaly
  • -mcsync-anomaly
  • -mno-csync-anomaly
  • -mlow-64k
  • -mno-low64k
  • -mstack-check-l1
  • -mid-shared-library
  • -mno-id-shared-library
  • -mshared-library-id=n
  • -mleaf-id-shared-library
  • -mno-leaf-id-shared-library
  • -msep-data
  • -mno-sep-data
  • -mlong-calls
  • -mno-long-calls
  • -mfast-fp
  • -minline-plt
  • -mmulticore
  • -mcorea
  • -mcoreb
  • -msdram
  • -micplb

โญ C6X Options

  • -mbig-endian
  • -mlittle-endian
  • -march=cpu
  • -msim
  • -msdata=sdata-type

๐Ÿ“ CRIS Options

  • -mcpu=cpu
  • -march=cpu
  • -mtune=cpu
  • -mmax-stack-frame=n
  • -metrax4
  • -metrax100
  • -mpdebug
  • -mcc-init
  • -mno-side-effects
  • -mstack-align
  • -mdata-align
  • -mconst-align
  • -m32-bit
  • -m16-bit
  • -m8-bit
  • -mno-prologue-epilogue
  • -melf
  • -maout
  • -sim
  • -sim2
  • -mmul-bug-workaround
  • -mno-mul-bug-workaround

๐Ÿ’ซ CR16 Options

  • -mmac
  • -mcr16cplus
  • -mcr16c
  • -msim
  • -mint32
  • -mbit-ops
  • -mdata-model=model

๐ŸŒธ C-SKY Options

  • -march=arch
  • -mcpu=cpu
  • -mbig-endian
  • -EB
  • -mlittle-endian
  • -EL
  • -mhard-float
  • -msoft-float
  • -mfpu=fpu
  • -mdouble-float
  • -mfdivdu
  • -mfloat-abi=name
  • -melrw
  • -mistack
  • -mmp
  • -mcp
  • -mcache
  • -msecurity
  • -mtrust
  • -mdsp
  • -medsp
  • -mvdsp
  • -mdiv
  • -msmart
  • -mhigh-registers
  • -manchor
  • -mpushpop
  • -mmultiple-stld
  • -mconstpool
  • -mstack-size
  • -mccrt
  • -mbranch-cost=n
  • -mcse-cc
  • -msched-prolog
  • -msim

๐ŸŽ€ Darwin Options

this list is long long, but every single one is here, periodt:

  • -all_load
  • -allowable_client
  • -arch
  • -arch_errors_fatal
  • -arch_only
  • -bind_at_load
  • -bundle
  • -bundle_loader
  • -client_name
  • -compatibility_version
  • -current_version
  • -dead_strip
  • -dependency-file
  • -dylib_file
  • -dylinker_install_name
  • -dynamic
  • -dynamiclib
  • -exported_symbols_list
  • -filelist
  • -flat_namespace
  • -force_cpusubtype_ALL
  • -force_flat_namespace
  • -headerpad_max_install_names
  • -iframework
  • -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
  • -F
  • -gused
  • -gfull
  • -mmacosx-version-min=version
  • -mkernel
  • -mone-byte-bool
yes bestie, -sectobjectsymbols, -segs_read_only_addr and -segs_read_write_addr each show up twice in that list, and we're keeping both of each because that's literally what's written ๐Ÿ˜ญ

๐Ÿฆ‹ DEC Alpha Options

  • -mno-fp-regs
  • -msoft-float
  • -mieee
  • -mieee-with-inexact
  • -mieee-conformant
  • -mfp-trap-mode=mode
  • -mfp-rounding-mode=mode
  • -mtrap-precision=mode
  • -mbuild-constants
  • -mcpu=cpu-type
  • -mtune=cpu-type
  • -mbwx
  • -mmax
  • -mfix
  • -mcix
  • -mfloat-vax
  • -mfloat-ieee
  • -mexplicit-relocs
  • -msmall-data
  • -mlarge-data
  • -msmall-text
  • -mlarge-text
  • -mmemory-latency=time

๐Ÿ’œ eBPF Options

  • -mbig-endian
  • -mlittle-endian
  • -mkernel=version
  • -mframe-limit=bytes
  • -mxbpf

๐Ÿงš FR30 Options

  • -msmall-model
  • -mno-lsim

๐Ÿ“ FT32 Options

  • -msim
  • -mlra
  • -mnodiv
  • -mft32b
  • -mcompress
  • -mnopm

๐ŸŒˆ FRV Options

  • -mgpr-32
  • -mgpr-64
  • -mfpr-32
  • -mfpr-64
  • -mhard-float
  • -msoft-float
  • -malloc-cc
  • -mfixed-cc
  • -mdword
  • -mno-dword
  • -mdouble
  • -mno-double
  • -mmedia
  • -mno-media
  • -mmuladd
  • -mno-muladd
  • -mfdpic
  • -minline-plt
  • -mgprel-ro
  • -multilib-library-pic
  • -mlinked-fp
  • -mlong-calls
  • -malign-labels
  • -mlibrary-pic
  • -macc-4
  • -macc-8
  • -mpack
  • -mno-pack
  • -mno-eflags
  • -mcond-move
  • -mno-cond-move
  • -moptimize-membar
  • -mno-optimize-membar
  • -mscc
  • -mno-scc
  • -mcond-exec
  • -mno-cond-exec
  • -mvliw-branch
  • -mno-vliw-branch
  • -mmulti-cond-exec
  • -mno-multi-cond-exec
  • -mnested-cond-exec
  • -mno-nested-cond-exec
  • -mtomcat-stats
  • -mTLS
  • -mtls
  • -mcpu=cpu

โญ GNU/Linux Options

  • -mglibc
  • -muclibc
  • -mmusl
  • -mbionic
  • -mandroid
  • -tno-android-cc
  • -tno-android-ld

๐ŸŽ€ H8/300 Options

  • -mrelax
  • -mh
  • -ms
  • -mn
  • -mexr
  • -mno-exr
  • -mint32
  • -malign-300

๐Ÿ’ซ HPPA Options

  • -march=architecture-type
  • -mcaller-copies
  • -mdisable-fpregs
  • -mdisable-indexing
  • -mfast-indirect-calls
  • -mgas
  • -mgnu-ld
  • -mhp-ld
  • -mfixed-range=register-range
  • -mjump-in-delay
  • -mlinker-opt
  • -mlong-calls
  • -mlong-load-store
  • -mno-disable-fpregs
  • -mno-disable-indexing
  • -mno-fast-indirect-calls
  • -mno-gas
  • -mno-jump-in-delay
  • -mno-long-load-store
  • -mno-portable-runtime
  • -mno-soft-float
  • -mno-space-regs
  • -msoft-float
  • -mpa-risc-1-0
  • -mpa-risc-1-1
  • -mpa-risc-2-0
  • -mportable-runtime
  • -mschedule=cpu-type
  • -mspace-regs
  • -msio
  • -mwsio
  • -munix=unix-std
  • -nolibdld
  • -static
  • -threads

๐ŸŒธ IA-64 Options

  • -mbig-endian
  • -mlittle-endian
  • -mgnu-as
  • -mgnu-ld
  • -mno-pic
  • -mvolatile-asm-stop
  • -mregister-names
  • -msdata
  • -mno-sdata
  • -mconstant-gp
  • -mauto-pic
  • -mfused-madd
  • -minline-float-divide-min-latency
  • -minline-float-divide-max-throughput
  • -mno-inline-float-divide
  • -minline-int-divide-min-latency
  • -minline-int-divide-max-throughput
  • -mno-inline-int-divide
  • -minline-sqrt-min-latency
  • -minline-sqrt-max-throughput
  • -mno-inline-sqrt
  • -mdwarf2-asm
  • -mearly-stop-bits
  • -mfixed-range=register-range
  • -mtls-size=tls-size
  • -mtune=cpu-type
  • -milp32
  • -mlp64
  • -msched-br-data-spec
  • -msched-ar-data-spec
  • -msched-control-spec
  • -msched-br-in-data-spec
  • -msched-ar-in-data-spec
  • -msched-in-control-spec
  • -msched-spec-ldc
  • -msched-spec-control-ldc
  • -msched-prefer-non-data-spec-insns
  • -msched-prefer-non-control-spec-insns
  • -msched-stop-bits-after-every-cycle
  • -msched-count-spec-in-critical-path
  • -msel-sched-dont-check-control-spec
  • -msched-fp-mem-deps-zero-cost
  • -msched-max-memory-insns-hard-limit
  • -msched-max-memory-insns=max-insns

๐Ÿฆ‹ LM32 Options

  • -mbarrel-shift-enabled
  • -mdivide-enabled
  • -mmultiply-enabled
  • -msign-extend-enabled
  • -muser-enabled

๐Ÿงš M32R/D Options

  • -m32r2
  • -m32rx
  • -m32r
  • -mdebug
  • -malign-loops
  • -mno-align-loops
  • -missue-rate=number
  • -mbranch-cost=number
  • -mmodel=code-size-model-type
  • -msdata=sdata-type
  • -mno-flush-func
  • -mflush-func=name
  • -mno-flush-trap
  • -mflush-trap=number
  • -G num

๐Ÿ“ M32C Options

  • -mcpu=cpu
  • -msim
  • -memregs=number

๐Ÿ’œ M680x0 Options

  • -march=arch
  • -mcpu=cpu
  • -mtune=tune
  • -m68000
  • -m68020
  • -m68020-40
  • -m68020-60
  • -m68030
  • -m68040
  • -m68060
  • -mcpu32
  • -m5200
  • -m5206e
  • -m528x
  • -m5307
  • -m5407
  • -mcfv4e
  • -mbitfield
  • -mno-bitfield
  • -mc68000
  • -mc68020
  • -mnobitfield
  • -mrtd
  • -mno-rtd
  • -mdiv
  • -mno-div
  • -mshort
  • -mno-short
  • -mhard-float
  • -m68881
  • -msoft-float
  • -mpcrel
  • -malign-int
  • -mstrict-align
  • -msep-data
  • -mno-sep-data
  • -mshared-library-id=n
  • -mid-shared-library
  • -mno-id-shared-library
  • -mxgot
  • -mno-xgot
  • -mlong-jump-table-offsets

๐ŸŒˆ MCore Options

  • -mhardlit
  • -mno-hardlit
  • -mdiv
  • -mno-div
  • -mrelax-immediates
  • -mno-relax-immediates
  • -mwide-bitfields
  • -mno-wide-bitfields
  • -m4byte-functions
  • -mno-4byte-functions
  • -mcallgraph-data
  • -mno-callgraph-data
  • -mslow-bytes
  • -mno-slow-bytes
  • -mno-lsim
  • -mlittle-endian
  • -mbig-endian
  • -m210
  • -m340
  • -mstack-increment

โญ MeP Options

  • -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

  • -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

okay so this is the part where every CPU family on planet earth gets its own lil flag drop ๐Ÿ’… like a group chat where every member is a different architecture and they ALL want to talk. Same rules as always: every single flag is here, character for character, no cap. Don't @ me if you don't know what a MIPS is, you will by the end. ๐Ÿฆ‹

๐Ÿ’– MIPS Options ๐Ÿ’–

MIPS said "let me just list literally everything" and honestly? iconic. ๐Ÿ‘‘

-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
-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 ๐ŸŒˆ

Knuth's lil baby architecture, we love to see it. โœจ

-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 ๐ŸŽ€

-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 ๐Ÿฆ‹

tiny list, tiny architecture, big vibes.

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

๐Ÿ’œ MSP430 Options ๐Ÿ’œ

the microcontroller bestie ๐Ÿ’… all those = flags are just waiting for you to fill in the blank.

-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 โญ

-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 ๐Ÿ“

-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 ๐Ÿงš

short and sweet, GPU girlies rise ๐ŸŒธ

-m64  -mmainkernel  -moptimize

๐Ÿ’… OpenRISC Options ๐Ÿ’…

-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

๐Ÿ‘‘ PDP-11 Options ๐Ÿ‘‘

vintage queen. the original. she was there first. ๐Ÿ’–

-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 ๐ŸŒธ

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

๐Ÿ’– PowerPC Options ๐Ÿ’–

bestie this one is just a redirect, no cap: See RS/6000 and PowerPC Options. ๐Ÿ‘€

๐Ÿ”ฅ PRU Options ๐Ÿ”ฅ

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

๐Ÿซถ RISC-V Options ๐Ÿซถ

open source royalty, she ate and left no crumbs โœจ

-mbranch-cost=N-instruction
-mplt  -mno-plt
-mabi=ABI-string
-mfdiv  -mno-fdiv  -mdiv  -mno-div
-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 ๐ŸŒˆ

-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 โญ

the big one. the main character of this entire section, lowkey. look how long she is. ๐Ÿ˜ญ

-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 ๐ŸŽ€

-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 ๐Ÿฆ‹

mainframe baddies, we see you ๐Ÿ’œ

-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 ๐Ÿ’–

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

๐ŸŒธ SH Options ๐ŸŒธ

-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 ๐Ÿ’…

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

๐Ÿ”ฅ SPARC Options ๐Ÿ”ฅ

-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

โœจ System V Options โœจ

short king energy.

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

๐Ÿงš TILE-Gx Options ๐Ÿงš

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

๐ŸŒˆ TILEPro Options ๐ŸŒˆ

two whole flags, she's low maintenance, we stan ๐Ÿ’–

-mcpu=cpu  -m32

๐Ÿฆ‹ V850 Options ๐Ÿฆ‹

bestie here's the whole V850 menu โ€” the manpage just drops the names and dips, no descriptions, no notes, so that's exactly what you're getting ๐Ÿ’…

  • -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

๐ŸŒธ VAX Options ๐ŸŒธ

  • -mg, -mgnu, -munix

๐ŸŽ€ Visium Options ๐ŸŽ€

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

๐Ÿ’œ VMS Options ๐Ÿ’œ

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

๐ŸŒˆ VxWorks Options ๐ŸŒˆ

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

๐Ÿ”ฅ x86 Options ๐Ÿ”ฅ

okay so this is THE list, the main character of option lists, no cap. every single one of these is real and here they all are:

  • -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
  • -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, -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, -mdaz-ftz, -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, -mindirect-branch=choice, -mfunction-return=choice, -mindirect-branch-register, -mharden-sls=choice, -mindirect-branch-cs-prefix, -mneeded

๐ŸชŸ x86 Windows Options ๐ŸชŸ

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

โญ Xstormy16 Options โญ

  • -msim

๐Ÿงš 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

๐Ÿ‘‘ zSeries Options ๐Ÿ‘‘

See S/390 and zSeries Options.


โœจ Options Controlling the Kind of Output โœจ

okay bestie, so a full compile is lowkey a four-stage glow-up and it ALWAYS goes in this order: preprocessing, then compilation proper, then assembly, then linking. no skipping ahead, no doing the steps out of order, the pipeline said what it said ๐Ÿ’…

GCC can preprocess and compile a whole bunch of files either into a bunch of separate assembler input files, or into one single assembler input file. then each assembler input file spits out an object file, and linking takes all those object files โ€” the freshly compiled ones and the ones you handed in as input โ€” and smooshes them into one executable file. it's giving assembly line but make it iconic.

for any input file you give it, the file name suffix is what decides which kind of compilation happens:

  • 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. heads up: you must link with the libobjc library for an Objective-C program to actually work.
  • file.mi โ€” Objective-C source code that should not be preprocessed.
  • file.mm, file.M โ€” Objective-C++ source code. again: you must link with the libobjc library for an Objective-C++ program to work. and yes, .M means a literal capital M, not a vibe.
  • file.mii โ€” Objective-C++ source code that should not be preprocessed.
  • file.h โ€” 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 (when you pass 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. in .cxx the last two letters have to both be literally x, and .C is a literal capital C. the compiler is picky like that, and honestly? respect.
  • file.mm, file.M โ€” Objective-C++ source code that must be preprocessed.
  • file.mii โ€” Objective-C++ source code that should not be preprocessed.
  • 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.brig โ€” BRIG files (binary representation of HSAIL).
  • file.d โ€” D source code.
  • file.di โ€” D interface file.
  • file.dd โ€” D documentation code (Ddoc).
  • file.ads โ€” Ada source code file that contains 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 also go by specs.
  • file.adb โ€” Ada source code file containing a library unit body (a subprogram or package body). these ones 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 gets treated this way.

and you can also just say what language it is with the -x option:

  • -x language โ€” Specify explicitly the language for the following input files (rather than letting the compiler choose a default based on 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
        brig
  • -x none โ€” Turn off any specification of a language, so that subsequent files are handled according to their file name suffixes (as they are if -x has not been used at all).

if you only want some of the stages, you tell gcc where to start with -x (or with filename suffixes), and then you tell it where to stop with one of -c, -S, or -E. and lowkey watch out: some combos instruct gcc to do absolutely nothing at all โ€” like -x cpp-output -E for example. do with that information what you will ๐Ÿ™ˆ

  • -c โ€” Compile or assemble the source files, but do not link. the linking stage simply does not happen. 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 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 gets sent to the standard output.

Input files that don't require preprocessing are ignored.

  • -o file โ€” Place the primary output in file. this applies to whatever sort of output is being produced โ€” executable file, object file, assembler file, preprocessed C code, doesn't matter, it's all going in there.

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. slay.

okay so real talk about -o โ€” it names the primary output, yeah, but bestie it is so much more than that. It also runs the naming of your auxiliary outputs and your dump outputs. Peep the examples below. ๐Ÿ‘€

Unless something overrides it, both auxiliary outputs and dump outputs get dropped in the same directory as the primary output. The naming tea goes like this:

  • In auxiliary outputs, the suffix of the input file gets swapped out for the suffix of the auxiliary output file type. ๐Ÿ’…
  • In dump outputs, the suffix of the dump file gets appended to the input file suffix.
  • In compilation commands, the base name of both auxiliary and dump outputs is the base name of the primary output.
  • In compile and link commands, the primary output name โ€” minus the executable suffix โ€” gets combined with the input file name.
  • If those two share the same base name (suffix not invited to the party), the result of the combination is that base name. Otherwise? They get concatenated, separated by a dash. Periodt.

So like, this:

gcc -c foo.c ...

will use foo.o as the primary output and place aux outputs and dumps right next to it โ€” e.g. aux file foo.dwo for -gsplit-dwarf, and dump file foo.c.???r.final for -fdump-rtl-final. Iconic behaviour honestly. โœจ

But if you explicitly specify a non-linker output file, then aux and dump files by default take that 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 is different though โ€” it prefixes the aux and dump outputs instead:

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 and only exception to all of the above is when the executable shares its base name with the single input:

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

in which case aux outputs get named dir/foo.* and dump outputs get named dir/foo.c.*. ๐Ÿฆ‹

And if you wanna adjust the location and names of auxiliary and dump outputs yourself, the options -dumpbase, -dumpbase-ext, -dumpdir, -save-temps=cwd, and -save-temps=obj are your girls.


๐ŸŒธ -dumpbase dumpbase

This option sets the base name for auxiliary and dump output files. It does NOT touch the name of the primary output file, okay? Mind the boundaries. ๐Ÿซถ

Intermediate outputs, when they're preserved, are not regarded as primary outputs โ€” they're 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 to save-foo.i, compiles to save-foo.s (now an intermediate, so like, an 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) get the input name suffix, and aux output files (those requested by other non-dump options, e.g. -save-temps, -gsplit-dwarf, -fcallgraph-info) get them without it. ๐Ÿ˜Œ

You can get that same suffix differentiation for dump and aux outputs with an explicitly-given -dumpbase basename.suf by also specifying -dumpbase-ext .suf.

If dumpbase is explicitly specified with any directory component, then any dumppfx specification (e.g. -dumpdir or -save-temps=*) gets 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. She said overriding, and she meant it. ๐Ÿ’€

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. Sneaky but slay.

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 the trailing auxdropsuf from dumpbase before appending any suffixes. If it's 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 doesn't 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 gonna 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. The options -save-temps=cwd and -save-temps=obj override this default, just like an explicit -dumpdir option does. And 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 an 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. Now contrast that with the single-input compilation:

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

which, 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 that 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 here 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 the 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 ...

Auxiliary outputs are named foo.*, and dump outputs foo.c.*, in the current working directory as ultimately requested by -save-temps=cwd. ๐Ÿ’–


okay bestie, let's wrap our heads around this dump data flow because it's giving organized chaos โœจ. So picture it: the primary output name gets split into a directory part and a basename part; dumppfx gets set to the directory part, unless something overrides it with -dumpdir or -save-temps=*, and dumpbase gets set to the basename part, unless -dumpbase overrides it. If you've got multiple inputs or you're linking, this dumpbase can get combined with dumppfx and taken from each input file. Auxiliary output names for each input? They're made by combining dumppfx, dumpbase minus its suffix, and the auxiliary output suffix; dump output names are only different because they keep the suffix from dumpbase. periodt ๐Ÿ’…

Now when auxiliary and dump outputs get created during LTO recompilation, a combo of dumppfx and dumpbaseโ€”either as given or derived from the linker output name but not from inputs, even in cases where that combo wouldn't normally be used that wayโ€”gets passed down with a trailing period replacing the compiler-added dash (if there was one) as a -dumpdir option to lto-wrapper. And because lto-wrapper is involved in linking, it doesn't normally get any -dumpbase and -dumpbase-ext, and it straight-up ignores them. so real ๐Ÿ™ˆ

When it runs sub-compilers, lto-wrapper appends LTO stage names to the dumppfx it received, makes sure it contains a directory component so it overrides any -dumpdir, and passes that as -dumpbase to the sub-compilers. slay ๐Ÿฆ‹


  • -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. the receipts, bestie ๐Ÿ‘‘
  • -### โ€” 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. script girlies, this one's for you ๐ŸŽ€
  • --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. the ultimate flag glow-up ๐Ÿ’–
  • --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. niche but necessary โœจ
  • --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
The argument to --help= should not consist solely of inverted qualifiers. periodt ๐Ÿ’…

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. the classic "who dis?" but make it legal ๐Ÿ‘‘
  • -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. dramatic but useful ๐Ÿ’…
  • -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. iconic behavior, honestly ๐ŸŒˆ
  • -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. left to right, no skipping โœจ
  • -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 .... backstage pass for your debugger ๐ŸŽŸ๏ธ

  • -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 and -fdebug-prefix-map. reproducible build queen ๐Ÿ‘‘
  • -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. plug in, bestie ๐Ÿ”Œ
  • -fplugin-arg-name-key=value โ€” define an argument called key with a value of value for the plugin called name. passing notes in class, but for plugins ๐Ÿ’Œ
  • -fdump-ada-spec[-slim] โ€” for C and C++ source and include files, generate corresponding Ada specs. Ada girlies, rise ๐Ÿ’…
  • -fada-spec-parent=unit โ€” in conjunction with -fdump-ada-spec[-slim] above, generate Ada specs as child units of parent unit. family tree but make it Ada ๐ŸŒณ
  • -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. Go off, then ๐Ÿน
  • @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. recursive, like your fave playlist ๐Ÿ”


๐ŸŽ€ 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 yes, you can still call it gcc and it'll know ๐Ÿ’–

However, the use of gcc does not add the C++ library. g++ is a 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 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. like, pick your fighter bestie ๐Ÿซถ


โœจ 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. rip to your little niceties, honestly

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. she's chill until you ask her to be strict, love that for her

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. she keeps receipts on which extensions are legal, periodt

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 <http://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. fr fr do not build your whole life on this one
  • 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.

-fgnu89-inline

The option -fgnu89-inline tells GCC to use the traditional GNU semantics for inline functions when in C99 mode.

Using this option is roughly equivalent to adding the gnu_inline function attribute to all inline functions.

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

The preprocessor macros __GNUC_GNU_INLINE__ and __GNUC_STDC_INLINE__ may be used to check which semantics are in effect for inline functions.

-fpermitted-flt-eval-methods=style

ISO/IEC TS 18661-3 defines new permissible values for FLT_EVAL_METHOD that indicate that 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.

-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. she simply does not hear you unless you're speaking C, and honestly? valid

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++. C++ said "already legal bestie" and walked off ๐Ÿ’€

  • -fno-asm โ€” okay so do NOT treat asm, inline or typeof as keywords, so your code can totally use those words as identifiers. Instead you can use __asm__, __inline__ and __typeof__. And just so you know, -ansi implies -fno-asm. ๐Ÿ’…

In C++, this switch only affects the typeof keyword, because asm and inline are standard keywords. You might wanna use -fno-gnu-keywords instead โ€” same effect, different vibe. And 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. big mood, but also big tradeoff. 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. ๐Ÿ‘‘

With the -fno-builtin-function option only the built-in function function is disabled. function must not begin with __builtin_. If a function is named that is not built-in in this version of GCC, this option is ignored. There is no corresponding -fbuiltin-function option; if you wish to enable built-in functions selectively when using -fno-builtin or -ffreestanding, you may define macros such as:

#define abs(n)          __builtin_abs ((n))
#define strcpy(d, s)    __builtin_strcpy ((d), (s))
  • -fgimple โ€” Enable parsing of function definitions marked with __GIMPLE. This is an experimental feature that allows unit testing of GIMPLE passes. ๐Ÿงช experimental, bestie!
  • -fhosted โ€” Assert that compilation targets a hosted environment. This implies -fbuiltin. A hosted environment is one in which the entire standard library is available, and in which main has a return type of int. Examples are nearly everything except a kernel. This is equivalent to -fno-freestanding. ๐ŸŒˆ
  • -ffreestanding โ€” Assert that compilation targets a freestanding environment. This implies -fno-builtin. A freestanding environment is one in which the standard library may not exist, and program startup may not necessarily be at main. The most obvious example is an OS kernel. This is equivalent to -fno-hosted. ๐Ÿงš
  • -fopenacc โ€” Enable 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 โ€” Specify default compute dimensions for parallel offload regions that do not explicitly specify. 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 โ€” Enable 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. -fopenmp implies -fopenmp-simd. ๐Ÿซถ
  • -fopenmp-simd โ€” Enable handling of OpenMP's SIMD directives with #pragma omp in C/C++ and !$omp in Fortran. Other OpenMP directives are ignored. โœจ
  • -fgnu-tm โ€” When the option -fgnu-tm is specified, the compiler generates code for the Linux variant of Intel's current Transactional Memory ABI specification document (Revision 1.1, May 6 2009). This is an experimental feature whose interface may change in future versions of GCC, as the official specification changes. Please note that not all architectures are supported for this feature. ๐Ÿงช

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

Note that the transactional memory feature is not supported with non-call exceptions (-fnon-call-exceptions). ๐Ÿ’€

  • -fms-extensions โ€” Accept some non-standard constructs used in Microsoft header files. ๐ŸชŸ

In C++ code, this allows member names in structures to be similar to previous types 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. ๐Ÿ‘‘

  • -fplan9-extensions โ€” Accept 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++. ๐Ÿ’…

  • -fcond-mismatch โ€” Allow conditional expressions with mismatched types in the second and third arguments. The value of such an expression is void. This option is not supported for C++. ๐Ÿ˜ญ
  • -flax-vector-conversions โ€” Allow implicit conversions between vectors with differing numbers of elements and/or incompatible element types. This option should not be used for new code. do not use for new code, bestie! ๐Ÿšซ
  • -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. ๐Ÿ’œ

  • -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. ๐ŸŽ€

  • -fsigned-bitfields, -funsigned-bitfields, -fno-signed-bitfields, -fno-unsigned-bitfields โ€” These options control whether a bit-field is signed or unsigned, when the declaration does not 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. ๐Ÿ’…
  • -fsso-struct=endianness โ€” Set 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 showed up in G++ 7, fixes the mangling of sizeof... expressions and operator names. And for multiple entities with the same name inside 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. But oopsie โ€” it accidentally changes the calling convention for classes with a deleted copy constructor and a trivial move constructor. ๐Ÿ’€

Version 13, which first appeared in G++ 8.2, fixes that accidental change from version 12. We love a redemption arc. ๐Ÿซถ

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__" so it's distinct from that of "alignof", plus 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 whenever it's defining a symbol with an incorrect mangled name. This switch tells it which ABI version to use for that alias.

With -fabi-version=0 (the default), this defaults to 11 (that's GCC 7 compatibility, bestie). If another ABI version is explicitly selected, this defaults to 0. And if you need compatibility with GCC versions 3.2 through 4.9, use -fabi-compat-version=2.

If you don't provide this option but you do pass -Wabi=n, that version gets used for the compatibility aliases. If you provide this option alongside -Wabi (without the version), then the version from this option is used for the warning. Slay, it all just works out. ๐Ÿ’…

  • -fno-access-control โ€” turns off all access checking. This switch is mainly useful for working around bugs in the access control code. (iykyk, sometimes you just gotta โœ‚๏ธ past the bouncer.)
  • -faligned-new โ€” enables support for C++17 new of types that need more alignment than "void* ::operator new(std::size_t)" provides. You can pass a numeric argument like -faligned-new=32 to specify how much alignment (in bytes) that function provides, but honestly few users will ever need to override the default of alignof(std::max_align_t).

This flag is on by default for -std=c++17. ๐ŸŽ€

  • -fchar8_t
  • -fno-char8_t โ€” enables support for "char8_t" as adopted for C++20. That means a whole 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. She's got range. ๐ŸŒˆ

This option lets functions 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 it 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. Like, 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

๐Ÿ˜ญ the errors really said "not today."

  • -fcheck-new โ€” check that the pointer returned by "operator new" is non-null before trying to modify the storage that was allocated. This check is normally unnecessary, because the C++ standard says "operator new" only returns 0 if it's declared throw(), and in that case the compiler always checks the return value even without this option. In all the 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 heads up bestie โ€” the standard spec 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 with -fconcepts-ts. ๐Ÿฆ‹

  • -fconstexpr-depth=n โ€” set the maximum nested evaluation depth for C++11 constexpr functions to n. A limit is needed so we can 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. It's a heuristic that trades off compilation speed (when the cache avoids repeated calculations) against memory consumption (when the cache grows super large from highly recursive evaluations). The default is 8. Very few users are likely to want to touch it, but if your code does heavy constexpr calculations you might want to experiment and find which value vibes best for you. โœจ
  • -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 the 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 the body of some loop, or even outside of a loop, too many expressions need to be evaluated โ€” the resulting constexpr evaluation might take way too long. The default is 33554432 (1<<25).
  • -fcoroutines โ€” enable support for the C++ coroutines extension (experimental). ๐Ÿงš
  • -fno-elide-constructors โ€” the C++ standard allows an implementation to omit creating a temporary that's 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 makes G++ 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. no cap. ๐Ÿ’…

  • -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 it may be useful for reducing code size in production builds, a lot 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. ๐Ÿ’€
  • -fextern-tls-init
  • -fno-extern-tls-init โ€” the C++11 and OpenMP standards allow "thread_local" and "threadprivate" variables to have dynamic (runtime) initialization. To support that, any use of such a variable goes through a wrapper function that performs whatever initialization is necessary. When the use and definition of the variable are in the same translation unit, this overhead can be optimized away โ€” but when the use is in a different translation unit there's significant overhead even if the variable doesn't actually need dynamic initialization. If the programmer can be sure that no use of the variable in a non-defining TU needs to trigger dynamic initialization (either because the variable is statically initialized, or a use of the variable in the defining TU will be executed before any uses in another TU), they can avoid this overhead with the -fno-extern-tls-init option. ๐Ÿซถ

On targets that support symbol aliases, the default is -fextern-tls-init. On targets that do not support symbol aliases, the default is -fno-extern-tls-init.

  • -fno-gnu-keywords โ€” don't recognize "typeof" as a keyword, so that code can use this 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.
  • -fno-implicit-templates โ€” never emit code for non-inline templates that are instantiated implicitly (i.e. by use); only emit code for explicit instantiations.
โš ๏ธ If you use this option, you must take care to structure your code to include all the necessary explicit instantiations, or you'll get undefined symbols at link time. ๐Ÿ˜ญ
  • -fno-implicit-inline-templates โ€” don't emit code for implicit instantiations of inline templates, either. The default is to handle 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 these functions aren't inlined everywhere they're called.
  • -fmodules-ts
  • -fno-modules-ts โ€” enable support for C++20 modules. The -fno-modules-ts is usually not needed, as that's the default. And even though this is a C++20 feature, it is not currently implicitly enabled by selecting that standard version. ๐Ÿ™ˆ
  • -fmodule-header, -fmodule-header=user, -fmodule-header=system โ€” bestie, this compiles a header file so it becomes an importable header unit. That's the whole job. ๐ŸŽ€
  • -fmodule-implicit-inline โ€” so member functions that get defined right inside their class definitions are normally not implicitly inline when you're doing modular code. That's a deliberate choice and it's different from classic C++ behaviour, for good reasons. But it can make porting code a whole thing ๐Ÿ˜ญ. This flag makes those function definitions implicitly inline anyway. Big caveat though: it generates an ABI incompatibility, so you have to use it everywhere or nowhere โ€” no halfsies. (And fyi, definitions like that outside of a named module stay implicitly inline regardless, so don't worry about those.) ๐Ÿ’…
  • -fno-module-lazy โ€” turns off lazy module importing and module mapper creation. Done and dusted.
  • -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] โ€” this is your oracle โœจ, i.e. the thing you query to map module names onto filenames. If you don't specify it, the CXX_MODULE_MAPPER environment variable gets used instead, and if that isn't set either, you get an in-process default. The vibes are: something's always handling it. ๐Ÿฆ‹
  • -fmodule-only โ€” only emit the Compiled Module Interface, and inhibit any object file. Just the CMI, nothing else, periodt.
  • -fms-extensions โ€” silences Wpedantic warnings about constructs used in MFC, like implicit int and grabbing a pointer to a member function via non-standard syntax. MFC girlies, this one's for you ๐Ÿซถ
  • -fnew-inheriting-ctors โ€” enables the P0136 adjustment to how C++11 constructor inheritance behaves. It's part of C++17, but it's also considered a Defect Report against C++11 and C++14. On by default unless you've specified -fabi-version=10 or lower. โญ
  • -fnew-ttp-matching โ€” enables the P0522 resolution to Core issue 150, all about template template parameters and default arguments: it lets a template with default template arguments be used as an argument for a template template parameter that has fewer template parameters. Enabled by default for -std=c++17. ๐ŸŒˆ
  • -fno-nonansi-builtins โ€” kills the built-in declarations of functions that ANSI/ISO C doesn't mandate. That list includes ffs, alloca, _exit, index, bzero, conjf, and other related functions. Bye besties ๐Ÿ‘‹
  • -fnothrow-opt โ€” treats a throw() exception specification as if it were a noexcept specification, which reduces or eliminates the text size overhead compared to a function with no exception spec at all. And plot twist: if the function has local variables whose types have non-trivial destructors, the exception spec actually makes the function smaller, because the EH cleanups for those variables can be optimized away. Semantically, this means an exception thrown out of a function with such a spec results in a call to terminate rather than unexpected. Noted. ๐Ÿ“
  • -fno-operator-names โ€” do not treat the operator name keywords and, bitand, bitor, compl, not, or and xor as synonyms for keywords. They're just words now, fr fr.
  • -fno-optional-diags โ€” disables diagnostics that the standard says a compiler doesn't need to issue. Currently the only such diagnostic G++ issues is the one for a name having multiple meanings within a class. That's it. The whole list. ๐Ÿ˜ญ
  • -fpermissive โ€” downgrades some diagnostics about nonconformant code from errors to warnings. So yeah, using -fpermissive lets some nonconforming code actually compile. You're on your own with it though ๐Ÿ’€
  • -fno-pretty-templates โ€” okay so normally, when an error message refers to a specialization of a function template, the compiler prints the signature of the template followed by the template arguments and any typedefs or typenames in the signature (like 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 that template's default template arguments. If either of those behaviours makes the error message harder to read instead of easier, use -fno-pretty-templates to turn them off. ๐Ÿงš
  • -fno-rtti โ€” disables generating information about every class with virtual functions, the info the C++ run-time type identification features use (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 information, but G++ generates it as needed. Also, 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 and code compiled with -fno-rtti may not work. Like, programs may fail to link if a class compiled with -fno-rtti is used as a base for a class compiled with -frtti. So... don't mix, bestie ๐Ÿ™ˆ

  • -fsized-deallocation โ€” enables 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. This is 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. And the flag -Wsized-deallocation warns about places that might want to add a definition. ๐Ÿ‘‘

  • -fstrict-enums โ€” lets the compiler optimize on 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). Heads up: that assumption may not be valid if the program uses a cast to convert an arbitrary integer value to the enumerated type. So like, careful. โš ๏ธ
  • -fstrong-eval-order โ€” evaluates member access, array subscripting, and shift expressions in left-to-right order, and evaluates assignment in right-to-left order, as adopted for C++17. Enabled by default with -std=c++17. Meanwhile -fstrong-eval-order=some enables just the ordering of member access and shift expressions, and that one is the default without -std=c++17. Slay, order matters ๐ŸŽ€
  • -ftemplate-backtrace-limit=n โ€” sets the max number of template instantiation notes for a single warning or error to n. The default value is 10. ๐Ÿ“
  • -ftemplate-depth=n โ€” sets the maximum instantiation depth for template classes to n. You need a limit on template instantiation depth 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 โ€” don't emit the extra code that uses the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this to shave off a bit of code size in code that doesn't need to be thread-safe. Lowkey a size optimization, highkey a "do you actually need this" question. ๐ŸŒธ
  • -fuse-cxa-atexit โ€” registers 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. So check that first ๐Ÿซถ
  • -fno-use-cxa-get-exception-ptr โ€” don't use the __cxa_get_exception_ptr runtime routine. This causes std::uncaught_exception to be incorrect, but it's necessary if that runtime routine isn't available. Trade-off city ๐Ÿ˜ญ
  • -fvisibility-inlines-hidden โ€” this switch declares that the user doesn't attempt to compare pointers to inline functions or methods where the addresses of the two functions are taken in different shared objects.

What that means in practice: GCC may effectively mark inline methods with __attribute__ ((visibility ("hidden"))), so they don't show up in a DSO's export table and don't need a PLT indirection when used inside the DSO. Enabling this can have a dramatic effect on a DSO's load and link times, because it massively shrinks the dynamic export table when the library makes heavy use of templates. Iconic honestly โœจ

But heads up: the behaviour isn't quite the same as marking the methods hidden directly, because it doesn't affect static variables local to the function, and it doesn't cause the compiler to deduce that the function is defined in only one shared object.

You can mark a method as having visibility explicitly to negate the effect of the switch for that one 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, though. And explicitly instantiated inline methods are unaffected by this option, since their linkage might otherwise cross a shared library boundary.

  • -fvisibility-ms-compat โ€” this flag tries to use visibility settings to make GCC's C++ linkage model compatible with Microsoft Visual Studio's. ๐Ÿ‘‘

It 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's better to use -fvisibility=hidden and export the classes you actually intend to be externally visible. Unfortunately it's possible for code to rely โ€” maybe accidentally โ€” on the Visual Studio behaviour. ๐Ÿ™ˆ

Among the consequences: static data members of the same type with the same name but defined in different shared objects are different, so changing one doesn't change the other; and pointers to function members defined in different shared objects may not compare equal. And when this flag is given, it's a violation of the ODR to define types with the same name differently. Yeah. Read that twice. ๐Ÿ’€

  • -fno-weak โ€” don't use weak symbol support, even if the linker provides it. By default G++ uses weak symbols if they're available. But listen: this option exists only for testing, and end-users should not use it; it results in inferior code and has no benefits. It may be removed in a future release of G++. So like, hands off bestie ๐Ÿšซ

  • -fext-numeric-literals (C++ and Objective-C++ only) โ€” bestie, this one lets you accept imaginary, fixed-point, or machine-defined literal number suffixes as GNU extensions. Turn it off and those suffixes get treated as C++11 user-defined literal numeric suffixes instead. It's 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. And it's 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 โ€” these three are the include-translation gossip girls ๐Ÿ—ฃ๏ธ. They inform you 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 ๐Ÿ˜ญ. However, a comma expression wrapped in ( ) is not deprecated. Example:
void f(int *a, int b, int c) {
    a[b,c];     // deprecated
    a[(b,c)];   // OK
}

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

  • -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.
    • When an initializer_list variable is assigned from a brace-enclosed initializer list, the temporary array created for the right side of the assignment only lives until the end of the full-expression, so at the next statement the initializer_list variable has a dangling pointer.
// 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
  • When a list constructor stores the begin pointer from the initializer_list argument, this doesn't extend the lifetime of the array, so if a class variable is constructed from a temporary initializer_list, the pointer is left dangling by the end of the variable declaration statement.
  • -Winvalid-imported-macros โ€” verify all imported macro definitions are valid at the end of compilation ๐Ÿงš. This is not enabled by default, as it requires additional processing to determine. It may be useful when preparing sets of header-units to ensure consistent macros.
  • -Wno-literal-suffix (C++ and Objective-C++ only) โ€” do not warn when a string or character literal is followed by a ud-suffix which does not begin with an underscore ๐ŸŒธ. As a conforming extension, GCC treats such suffixes as separate preprocessing tokens in order to maintain backwards compatibility with code that uses formatting macros from <inttypes.h>. 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 warnings when a user-defined literal operator is declared with a literal suffix identifier that doesn't begin with an underscore. Literal suffix identifiers that don't begin with an underscore are reserved for future standardization โš ๏ธ.

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 required by the standard ๐Ÿ“. A narrowing conversion from a constant produces an error, and a narrowing conversion 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, warn when a narrowing conversion prohibited by C++11 occurs within { }, e.g.

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) โ€” warn when a noexcept-expression evaluates to false because of a call to a function that does not have a non-throwing exception specification (i.e. throw() or noexcept) but is known by the compiler to never throw an exception ๐Ÿ‘‘.
  • -Wnoexcept-type (C++ and Objective-C++ only) โ€” warn if the C++17 feature making noexcept part of a function type changes the mangled name of a symbol relative to C++14 ๐Ÿ”ฅ. Enabled by -Wabi and -Wc++17-compat.

As an example:

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</p> (C++ and Objective-C++ only)

okay so this one is giving โœ‹ stop right there energy. It yells at you 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 such objects may violate invariants maintained by member functions of the class. For example, the call to memset below is undefined because it modifies a non-trivial class object and is, therefore, diagnosed:

std::string str = "abc";
memset (&str, 0, sizeof str);

The safe way to either initialize or clear the storage of objects of such types is by using the appropriate constructor or assignment operator, if one is available. bestie, please just use the constructor ๐Ÿ™

-Wclass-memaccess is enabled by -Wall. And if you really know what you're doing, explicitly casting the pointer to the class object to void * or to a type that can be safely accessed by the raw memory function suppresses the warning. โœจ


-Wnon-virtual-dtor</p> (C++ and Objective-C++ only)

Warns when a class has virtual functions and an accessible non-virtual destructor โ€” either in itself or in an accessible polymorphic base class. In that case it is possible but unsafe to delete an instance of a derived class through a pointer to the class itself or the base class. it's giving "works on my machine until it doesn't" ๐Ÿ’…

This warning is automatically enabled if -Weffc++ is specified.


-Wregister</p> (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. The use of the register keyword as a storage class specifier has been deprecated in C++11 and removed in C++17. Enabled by default with -std=c++17. she's old, she's retired, let her rest ๐Ÿซถ


-Wreorder</p> (C++ and Objective-C++ only)

Warns when the order of member initializers given in the code does not match the order in which they must be executed. 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, emitting a warning to that effect. This warning is enabled by -Wall. your init list order is a vibe check the compiler does NOT let you skip ๐Ÿ˜ญ


-Wno-pessimizing-move</p> (C++ and Objective-C++ only)

This warning warns when a call to std::move prevents copy elision. A typical scenario when copy elision can occur is when returning in a function with a class return type, when the expression being returned is the name of a non-volatile automatic object, and is not 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, the std::move call prevents copy elision. not you sabotaging your own optimization bestie ๐Ÿ˜ญ

This warning is enabled by -Wall.


-Wno-redundant-move</p> (C++ and Objective-C++ only)

This warning warns about redundant calls to std::move โ€” that is, when a move operation would have been performed 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, such as 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</p> (C++ and Objective-C++ only)

This warning warns when a C++ range-based for-loop is creating an unnecessary copy. This can happen when the range declaration is not 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. tiny copies get a pass, big ones get read ๐Ÿ“–

This warning 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. For example:

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

In the example above, in every iteration of the loop a temporary value of type double is created and destroyed, to which the reference const double & is bound. every. single. iteration. ๐Ÿ’€

This warning is enabled by -Wall.


-Wredundant-tags</p> (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 eliminated without causing an ambiguity. For example:

struct foo;
struct foo *p;   // warn that keyword struct can be eliminated

On the other hand, in this example there is no warning:

struct foo;
void foo ();   // "hides" struct foo
void bar (struct foo&);  // no warning, keyword struct is necessary

context is everything, the keyword stays when it has to ๐ŸŽ€


-Wno-subobject-linkage</p> (C++ and Objective-C++ only)

Do not 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 it 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 a single translation unit, the best way to silence the warning is to give it internal linkage by putting it in an anonymous namespace as well. The compiler doesn't give this warning for types defined in the main .C file, as those are unlikely to have multiple definitions. -Wsubobject-linkage is enabled by default.


-Weffc++</p> (C++ and Objective-C++ only)

Warns about violations of the following style guidelines from Scott Meyers' Effective C++ series of books:

  • Define a copy constructor and an assignment operator for classes with dynamically-allocated memory.
  • Prefer initialization to assignment in constructors.
  • Have operator= return a reference to *this.
  • Don't try to return a reference when you must return an object.
  • Distinguish between prefix and postfix forms of increment and decrement operators.
  • Never overload &&, ||, or ,.

This option also enables -Wnon-virtual-dtor, which is also one of the effective C++ recommendations. However, the check is extended to warn about the lack of virtual destructor in accessible non-polymorphic bases classes too.

When selecting this option, be aware that the standard library headers do not obey all of these guidelines; use grep -v to filter out those warnings. the STL is not passing Scott Meyers' vibe check and that's just how it is ๐Ÿ™ˆ

-Wno-exceptions</p> (C++ and Objective-C++ only)

Disable the warning about the case when an exception handler is shadowed by another handler, which can point out a wrong ordering of exception handlers. catch blocks are read top to bottom, bestie, order matters ๐Ÿซถ


-Wstrict-null-sentinel</p> (C++ and Objective-C++ only)

Warns about the use of an uncasted NULL as sentinel. When compiling only with GCC this is a valid sentinel, as NULL is defined to __null. Although it is a null pointer constant rather than a null pointer, it is guaranteed to be of the same size as a pointer. But this use is not portable across different compilers. works here, breaks everywhere else, classic ๐Ÿ’…


-Wno-non-template-friend</p> (C++ and Objective-C++ only)

Disable warnings when non-template friend functions are declared within a template. In very old versions of GCC that predate implementation of the ISO standard, declarations such as 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 compatibility problems, and is enabled by default. legacy lore, iykyk ๐Ÿ“œ


-Wold-style-cast</p> (C++ and Objective-C++ only)

Warns if an old-style (C-style) cast to a non-void type is used within a C++ program. The new-style casts (dynamic_cast, static_cast, reinterpret_cast, and const_cast) are less vulnerable to unintended effects and much easier to search for. glow up your casts, bestie โœจ


-Woverloaded-virtual</p> (C++ and Objective-C++ only)

Warns when a function declaration hides virtual functions from a base class. For example, in:

struct A {
  virtual void f();
};

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

the A class version of f is hidden in B, and code like:

B* b;
b->f();

fails to compile. not the signature change sneak attack ๐Ÿ˜ญ


-Wno-pmf-conversions</p> (C++ and Objective-C++ only)

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


-Wsign-promo</p> (C++ and Objective-C++ only)

Warns when overload resolution chooses 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. the standard said "we're doing it this way now" and that's that periodt ๐Ÿ’…


-Wtemplates</p> (C++ and Objective-C++ only)

Warns when a primary template declaration is encountered. Some coding rules disallow templates, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also instantiate or specialize templates. so you can still live your STL fantasy, just no declaring your own ๐ŸŽ€

  • -Wno-mismatched-new-delete <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” bestie, this one yells at you when your operator new and operator delete calls don't match up with their allocation/deallocation buddy. That includes calling C++ operator delete on pointers that came from a mismatched form of operator new, or from other functions that allocate objects where operator delete just isn't the right deallocator. Also flags calls to other deallocation functions on pointers returned from operator new when the deallocation function isn't suitable. ๐Ÿ’…

Like, check this โ€” the delete in this function gets diagnosed because it doesn't match the array form of the new the pointer came from. And the free call gets flagged too:

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 catches mismatches involving allocation and deallocation functions that aren't operator new and operator delete.

<span style="color:mint">-Wmismatched-new-delete is enabled by default.</span> โœจ

  • -Wmismatched-tags <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” warns you when structs, classes, class templates and their specializations get declared with a class-key that doesn't match either the definition or the first declaration (if there's no definition). ๐ŸŽ€

For example, the declaration of struct Object in the argument list of draw triggers the warning. To dodge it, either yeet the redundant struct class-key or swap it for class to match its definition:

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

It's not actually wrong to declare a class with the struct class-key like the example above shows. The -Wmismatched-tags option is just here to help you get a consistent style of class declarations. In code meant to be portable to Windows-based compilers, the warning helps prevent unresolved references from the difference in symbol mangling when declared with different class-keys. You can use it on its own or together with -Wredundant-tags. ๐Ÿฆ‹

  • -Wmultiple-inheritance <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” warns when a class is defined with multiple direct base classes. Some coding rules are like "no multiple inheritance" and this can enforce that rule. The warning is inactive inside a system header file, like the STL, so you can still use the STL. You can 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. <span style="color:red">This is dangerous</span> 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, you can disable this warning. ๐Ÿ’€
  • -Wnamespaces โ€” warns when a namespace definition is opened. Some coding rules disallow namespaces, and this can enforce that rule. The warning is inactive inside a system header file, such as the STL, so you can still use the STL. You can also use using directives and qualified names. โœจ
  • -Wno-terminate <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” disables the warning about a throw-expression that will immediately result in a call to terminate. ๐Ÿ˜ญ
  • -Wno-vexing-parse <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” warns about the most vexing parse syntactic ambiguity. This flags 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; like, it can suggest removing the parentheses or using braces instead.

<span style="color:mint">This warning is enabled by default.</span> ๐Ÿ’–

  • -Wno-class-conversion <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” 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 literally never be called. ๐Ÿ™ˆ
  • -Wvolatile <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” 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, and structured bindings of a volatile-qualified type. This usage was deprecated in C++20. ๐Ÿซถ

<span style="color:mint">Enabled by default with -std=c++20.</span>

  • -Wzero-as-null-pointer-constant <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” warns when a literal 0 is used as a null pointer constant. This can be useful to help with converting to nullptr in C++11. โญ
  • -Waligned-new โ€” warns about a new-expression of a type that requires greater alignment than the 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. ๐ŸŒˆ

  • -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];

<span style="color:mint">This warning is enabled by default.</span>

  • -Wplacement-new=1 โ€” this is the default warning level of -Wplacement-new. At this level the warning is not issued for some strictly undefined constructs that GCC allows as extensions for compatibility with legacy code. For example, the following 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, in addition to 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. While the previous example would be diagnosed, the following construct makes use of the flexible member array extension to avoid 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 <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” warns 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 caught by value. With -Wcatch-value=3 it warns about all types that are not caught by reference. -Wcatch-value is enabled by -Wall. ๐ŸŽ€
  • -Wconditionally-supported <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” warns for conditionally-supported (C++11 [intro.defs]) constructs. ๐Ÿ’œ
  • -Wno-delete-incomplete <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” do not warn when deleting a pointer to an incomplete type, which may cause undefined behavior at runtime. <span style="color:mint">This warning is enabled by default.</span> ๐Ÿ’€
  • -Wextra-semi <span style="color:hotpink">(C++, Objective-C++ only)</span> โ€” warns about redundant semicolons after in-class function definitions. ๐Ÿ”ฅ
  • -Wno-inaccessible-base <span style="color:hotpink">(C++, Objective-C++ only)</span> โ€” this option controls warnings when a base class is inaccessible in a class derived from it due to ambiguity. <span style="color:mint">The warning is enabled by default.</span> 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 <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” 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, though, offsetof typically gives meaningful results. This flag is for users who are aware that they're writing nonportable code and who have deliberately chosen to ignore the warning about it.

The restrictions on offsetof may be relaxed in a future version of the C++ standard. ๐Ÿ™ˆ

  • -Wsized-deallocation <span style="color:hotpink">(C++ and Objective-C++ only)</span> โ€” warns about a definition of an unsized deallocation function
void operator delete (void *) noexcept;
void operator delete[] (void *) noexcept;

...but there's no definition of the matching sized deallocation function

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

...or the other way round. Turned on by -Wextra, chillin' right alongside -fsized-deallocation. โœจ

  • -Wsuggest-final-types โ€” bestie, if a type has virtual methods and it would be so much better as a C++11 final type (or maybe tucked into an anonymous namespace), GCC will gently tell you. Why do we care? Because that lets GCC go full beast mode and devirtualize the polymorphic calls ๐Ÿ’… This warning hits different with link-time optimization, where the whole class hierarchy graph is actually visible. ๐Ÿ‘‘
  • -Wsuggest-final-methods โ€” same vibe, but for virtual methods: it warns when declaring the method final (or yeeting its type into an anonymous namespace, or slapping final on the type) would level up your code quality. Also way more effective with link-time optimization since the class hierarchy graph is more complete there. Pro tip: go look at the -Wsuggest-final-types suggestions first, then rebuild with your new annotations. ๐Ÿฆ‹
  • -Wsuggest-override โ€” warns when you're overriding a virtual function but forgot to mark it with the override keyword. ๐Ÿ™ˆ
  • -Wuseless-cast (C++ and Objective-C++ only) โ€” warns when you cast an expression to its own type. Girl, that's you talking to a mirror. ๐Ÿชž
  • -Wno-conversion-null (C++ and Objective-C++ only) โ€” stops warning about conversions between NULL and non-pointer types. Heads up: -Wconversion-null is on by default. ๐ŸŽ€

๐ŸŒˆ Options Controlling Objective-C and Objective-C++ Dialects ๐ŸŒˆ

(Heads up bestie: this manual does not describe the Objective-C and Objective-C++ languages themselves. We're just doing the compiler flags here.) ๐Ÿ’–

This bit is all about the command-line options that only mean something for Objective-C and Objective-C++ programs. That said, you can still use most of the language-independent GNU compiler options with them too. Like, you could compile a file some_class.m like this:

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

See how -fgnu-runtime in there is an option that's only for Objective-C and Objective-C++ programs? The other options in that line work with any language GCC supports. ๐Ÿซถ

And real talk: since Objective-C is an extension of C, your Objective-C compilations can also use C-front-end-specific options (think -Wtraditional). Same energy for Objective-C++ โ€” it can use C++-specific options (hi -Wabi). โœจ

Okay so here's the 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 you write with the syntax @"...". The default class name is NXConstantString if the GNU runtime is in play, and NSConstantString if it's the NeXT runtime (more on that below ๐Ÿ‘‡). On Darwin (macOS, MacOS X) platforms, if -fconstant-cfstrings is also present, it overrides the -fconstant-string-class setting and makes those @"..." literals get laid out as constant CoreFoundation strings. Also FYI: -fconstant-cfstrings is an alias for the target-specific -mconstant-cfstrings equivalent. ๐Ÿ’…
  • -fgnu-runtime โ€” generates object code that's compatible with the standard GNU Objective-C runtime. This is the default for most types of systems. ๐Ÿ“
  • -fnext-runtime โ€” generates output compatible with the NeXT runtime. This is the default for NeXT-based systems, Darwin and Mac OS X included. Oh and the macro __NEXT_RUNTIME__ gets predefined if (and only if) this option is used. โญ
  • -fno-nil-receivers โ€” assumes that every single Objective-C message dispatch ([receiver message:arg]) in this translation unit guarantees the receiver isn't nil. That lets the runtime use more efficient entry points. Heads up though: this one's only available with the NeXT runtime and ABI version 0 or 1. ๐Ÿ”ฅ
  • *-fobjc-abi-version=n* โ€” use version n of the Objective-C ABI for whichever runtime you picked. Currently only supported for the NeXT runtime. In that case:
    • Version 0 is the traditional (32-bit) ABI, no support for properties or the 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 you don't specify anything, the default is Version 0 on 32-bit target machines and Version 2 on 64-bit target machines. ๐Ÿ‘‘

  • -fobjc-call-cxx-cdtors โ€” for each Objective-C class, GCC checks whether any of its instance variables is a C++ object with a non-trivial default constructor. If so, it synthesizes a special - (id) .cxx_construct instance method that runs non-trivial default constructors on any such instance variables, in order, and then returns self. Same deal the other direction: it checks whether any instance variable is a C++ object with a non-trivial destructor, and if so it synthesizes a special - (void) .cxx_destruct method that runs all such default destructors, in reverse order. ๐ŸŒ€

The - (id) .cxx_construct and - (void) .cxx_destruct methods generated this way only operate on instance variables declared in the current Objective-C class โ€” not the ones inherited from superclasses. It's the Objective-C runtime's job to invoke all such methods across an object's inheritance hierarchy. The - (id) .cxx_construct methods get invoked by the runtime right after a new object instance is allocated; the - (void) .cxx_destruct methods get invoked right 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 โ€” allows fast jumps to the message dispatcher. On Darwin this happens via the comm page. ๐Ÿš€
  • -fobjc-exceptions โ€” enables syntactic support for structured exception handling in Objective-C, similar to what C++ gives you. You need this option to use the Objective-C keywords @try, @throw, @catch, @finally and @synchronized. Available with both the GNU runtime and the NeXT runtime โ€” but not available with the NeXT runtime on Mac OS X 10.2 and earlier. ๐Ÿ˜ญ
  • -fobjc-gc โ€” enables garbage collection (GC) in Objective-C and Objective-C++ programs. Only available with the NeXT runtime; the GNU runtime has a different garbage collection implementation that doesn't need special compiler flags. โ™ป๏ธ
  • -fobjc-nilcheck โ€” for the NeXT runtime with version 2 of the ABI, this checks for a nil receiver in method invocations before actually doing the method call. This is the default, and you can turn it off with -fno-objc-nilcheck. Class methods and super calls are never checked for nil this way, no matter what you set this flag to. Currently this flag does literally nothing when the GNU runtime is used, or an older version of the NeXT runtime ABI. ๐Ÿ’€
  • -fobjc-std=objc1 โ€” conform to the language syntax of Objective-C 1.0, the language GCC 4.0 recognized. This only affects the Objective-C additions to the C/C++ language; it does not affect conformance to C/C++ standards, which is handled by the separate C/C++ dialect option flags. When you use this with the Objective-C or Objective-C++ compiler, any Objective-C syntax that GCC 4.0 didn't recognize gets rejected. Super useful if you need to make sure your Objective-C code can compile with older versions of GCC. ๐ŸŒธ
  • -freplace-objc-classes โ€” emits a special marker telling ld(1) not to statically link in the resulting object file, and letting dyld(1) load it in at run time instead. This is used together with the Fix-and-Continue debugging mode, where the object file in question can be recompiled and dynamically reloaded while the program is running โ€” no need to restart the program itself. Currently, Fix-and-Continue functionality is only available 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 class name 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 that behavior and causes calls to objc_getClass("...") to be retained. Useful in Zero-Link debugging mode, since it lets individual class implementations 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 inside 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, which dodges those variable shadowing issues. ๐ŸŽ€
  • -fivar-visibility=[public|protected|private|package] โ€” sets the default instance variable visibility to whatever option you picked, so instance variables declared outside the scope of any access modifier directives default to that visibility. ๐Ÿ’–
  • -gen-decls โ€” dumps interface declarations for all classes seen in the source file to a file named sourcename.decl. ๐Ÿ“
  • -Wassign-intercept (Objective-C and Objective-C++ only) โ€” warns whenever an Objective-C assignment is being intercepted by the garbage collector. ๐Ÿ‘€
  • -Wno-property-assign-default (Objective-C and Objective-C++ only) โ€” doesn't warn if a property for an Objective-C object has no assign semantics specified. ๐Ÿคซ
  • -Wno-protocol (Objective-C and Objective-C++ only) โ€” okay so when a class says it implements a protocol, GCC is like "bestie you're missing methods" and warns for every method in that protocol the class doesn't implement. The default vibe is: warn about every method that isn't explicitly implemented in the class, even if it's inherited from the superclass. But if you pass -Wno-protocol, then methods inherited from the superclass count as implemented and you get zero warnings for them. ๐Ÿซถ
  • -Wobjc-root-class (Objective-C and Objective-C++ only) โ€” this one yells at you if a class interface has no superclass. Like, most classes will inherit from NSObject (or Object) for example. When you're intentionally declaring root classes, you can hush the warning by marking the interfaces with __attribute__((objc_root_class)). ๐Ÿ‘‘
  • -Wselector (Objective-C and Objective-C++ only) โ€” warns if the compiler finds multiple methods of different types hanging out under the same selector during compilation. The check runs on the list of methods in the final stage of compilation. On top of that, it checks each selector that shows up in a @selector(...) expression, and a corresponding method for that selector has been found during compilation. And because these checks only scan the method table at the very end of compilation, you get no warnings if the final stage is never reached โ€” say an error got found during compilation, or you're using -fsyntax-only. ๐Ÿ’€
  • -Wstrict-selector-match (Objective-C and Objective-C++ only) โ€” warns if multiple methods with differing argument and/or return types are found for a given selector when you're trying to send a message using that selector to a receiver of type id or Class. When this flag is off (which is the default), the compiler just skips those warnings if any differences found are confined to types that share the same size and alignment. โœจ
  • -Wundeclared-selector (Objective-C and Objective-C++ only) โ€” warns if a @selector(...) expression referring to an undeclared selector is found. A selector counts as 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 runs its checks the instant a @selector(...) expression is found, while -Wselector only checks in the final stage of compilation. It also enforces that coding-style convention that methods and selectors must be declared before being used. periodt. ๐ŸŽ€
  • -print-objc-runtime-info โ€” generates a C header describing the largest structure that is passed by value, if any. ๐ŸŒธ

๐Ÿฉบ Options to Control Diagnostic Messages Formatting ๐Ÿ’…

So like, traditionally diagnostic messages have been formatted with zero regard for the output device's aspect (its width, and so on...). You can use the options below to control the formatting algorithm for diagnostic messages โ€” things like how many characters per line, and how often source location info should be reported. Heads up though: some language front ends may not honor these options. ๐Ÿ™ˆ

  • -fmessage-length=n โ€” tries to format error messages so they fit on lines of about n characters. If n is zero, then no line-wrapping happens; 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 one asks for diagnostic output to look as plain as possible, which is lowkey useful when running dejagnu or other utilities that need to parse diagnostics output and prefer it stay 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 โ€” only meaningful in line-wrapping mode. Tells the diagnostic messages reporter to emit source location information once; that is, if the message is too long to fit on a single physical line and has to be wrapped, the source location won't be emitted (as a prefix) again and again on subsequent continuation lines. This is the default behavior. โœ…
  • -fdiagnostics-show-location=every-line โ€” only meaningful in line-wrapping mode. Tells the diagnostic messages reporter to emit the same source location info (as a prefix) for the physical lines that result from breaking a message too long to fit on a single line. ๐Ÿ”
  • -fdiagnostics-color[=WHEN], -fno-diagnostics-color โ€” use color in diagnostics. WHEN is never, always, or auto. The default depends on how the compiler has been configured; it can be any of the above WHEN options, 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 the standard error is a terminal, and when not executing in an emacs shell. The forms -fdiagnostics-color and -fno-diagnostics-color are aliases for -fdiagnostics-color=always and -fdiagnostics-color=never, respectively.

The colors 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 are interpreted by the terminal or terminal emulator. (Peep the section in the documentation of your text terminal for permitted values and their meanings as character attributes.) 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.

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. Supported capabilities are as follows. ๐ŸŒˆ

  • "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] โ€” use escape sequences to embed URLs in diagnostics. For example, when -fdiagnostics-show-option emits text showing the command-line option controlling a diagnostic, embed a URL for documentation of that option. ๐Ÿ”—

WHEN is never, always, or auto. auto makes GCC use URL escape sequences only when the standard error is a terminal, and when not executing in an emacs shell or any graphical terminal which is known to be incompatible with this feature, see below.

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.

However, 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. Note: ST is an ANSI escape sequence, string terminator ESC \, BEL is an ASCII character, CTRL-G that usually sounds like a beep. ๐Ÿ›Ž๏ธ

At this time GCC also tries to sniff out a few terminals that are known to not implement the URL feature, and that have bugs (or at least had bugs in some versions that are still out there in the wild) where the URL escapes are likely to misbehave, i.e. just print garbage all over your screen. ๐Ÿ’€ That list is currently xfce4-terminal, certain known-to-be-buggy gnome-terminal versions, the linux console, and mingw. You can skip this whole check with -fdiagnostics-urls=always.

  • -fno-diagnostics-show-option โ€” bestie, by default every diagnostic that pops off also includes text telling you which command-line option directly controls that diagnostic (if the diagnostic machinery even knows of such an option, that is). Slap on -fno-diagnostics-show-option and that behavior gets suppressed. ๐Ÿšซ
  • -fno-diagnostics-show-caret โ€” default behavior? Every diagnostic includes the original source line plus a caret ^ pointing at the column. This option suppresses that info. Ngl the source line gets truncated to n characters if you passed -fmessage-length=n. And when the output is going to the terminal, the width is limited to whatever the COLUMNS environment variable says โ€” or, if that's not set, to the terminal width. ๐Ÿ“
  • -fno-diagnostics-show-labels โ€” when printing source code (via -fdiagnostics-show-caret), diagnostics can label ranges of source code with pertinent info, like the types of expressions. It's giving:
            printf ("foo %s bar", long_i + long_j);
                         ~^       ~~~~~~~~~~~~~~~
                          |              |
                          char *         long int

This option suppresses the printing of those labels (in the example above, the vertical bars and the "char *" and "long int" text go bye-bye).

  • -fno-diagnostics-show-cwe โ€” diagnostic messages can optionally have an associated CWE identifier (the Common Weakness Enumeration situation, https://cwe.mitre.org/index.html). GCC itself only provides that kind of metadata for some of the -fanalyzer diagnostics. GCC plugins may also hand over diagnostics with such metadata. By default, if this info is present, it gets printed with the diagnostic. This option suppresses the printing of that metadata. ๐Ÿ™ˆ
  • -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. โœจ
  • -fdiagnostics-minimum-margin-width=width โ€” this one controls the minimum width of the left margin printed by -fdiagnostics-show-line-numbers. It defaults to 6.
  • -fdiagnostics-parseable-fixits โ€” emit 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:". For example:
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 example above, 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 \", and non-printable characters as octal (e.g. vertical tab as \013).

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. ๐Ÿซถ

  • -fdiagnostics-generate-patch โ€” print fix-it hints to stderr in unified diff format, after any diagnostics are printed. For example:
--- 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). ๐ŸŒˆ

  • -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, such as:

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

The parts that differ are highlighted with color (double and float in this case). ๐ŸŽ€

  • -fno-elide-type โ€” by default when the C++ frontend prints diagnostics showing mismatching template types, common parts of the types are printed as [...] to simplify the error message. 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. This flag also affects the output of the -fdiagnostics-show-template-tree flag.

  • -fdiagnostics-path-format=KIND โ€” specify how to print paths of control-flow events for diagnostics that have such a path associated with them.

KIND is none, separate-events, or inline-events, the default.

none means to not print diagnostic paths at all.

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.

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.

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 extra info when printing control-flow paths associated with a diagnostic. ๐Ÿ”

If this option is provided then the stack depth will be printed for each run of events within -fdiagnostics-path-format=separate-events.

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.
  • -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, is like, super aware of how many display columns each character is hogging. And that is NOT always the same as the bytes, bestie. It can be bigger than the byte count โ€” hi, tab characters ๐Ÿ‘‹ โ€” or smaller, which is what happens with multibyte characters. Example time: the character "GREEK SMALL LETTER PI (U+03C0)" takes up one display column, but its UTF-8 encoding needs two bytes. And the character "SLIGHTLY SMILING FACE (U+1F642)" takes up two display columns while its UTF-8 encoding needs four bytes. The math is mathing, it's just not the same math. ๐Ÿ’…

Set UNIT to byte and the column number becomes the raw byte count in every single case โ€” which is literally how GCC did it before version 11.1.0. Throwback era. ๐ŸŽ€

  • -fdiagnostics-column-origin=ORIGIN โ€” picks where column numbers start, aka which column gets to be called "first". The default is 1, which matches old-school GCC behavior and the GNU style guide. Some utilities lowkey vibe better with an origin of 0 โ€” and honestly, any non-negative value is fair game, you can specify whatever. โœจ
  • -fdiagnostics-format=FORMAT โ€” switches up how diagnostics get printed. FORMAT is either text or json. Default is text. No cap.

The json format is a top-level JSON array, and inside it are JSON objects representing the diagnostics. It gets emitted as one single line, no pretty formatting โ€” the examples below have been formatted for clarity only, don't come for me. ๐Ÿ™ˆ

Diagnostics can have child diagnostics, because of course they can, it's giving family tree. 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:

[
    {
        "kind": "warning",
        "locations": [
            {
                "caret": {
                    "display-column": 3,
                    "byte-column": 3,
                    "column": 3,
                    "file": "misleading-indentation.c",
                    "line": 15
                },
                "finish": {
                    "display-column": 4,
                    "byte-column": 4,
                    "column": 4,
                    "file": "misleading-indentation.c",
                    "line": 15
                }
            }
        ],
        "message": "this \u2018if\u2019 clause does not guard...",
        "option": "-Wmisleading-indentation",
        "option_url": "https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmisleading-indentation",
        "children": [
            {
                "kind": "note",
                "locations": [
                    {
                        "caret": {
                            "display-column": 5,
                            "byte-column": 5,
                            "column": 5,
                            "file": "misleading-indentation.c",
                            "line": 17
                        }
                    }
                ],
                "message": "...this statement, but the latter is ..."
            }
        ]
        "column-origin": 1,
    },
    ...
]

where the "note" is a child of the "warning". Parent-child diagnostic moment, we love to see it. ๐Ÿซถ

A diagnostic has a "kind". If that kind is "warning", then there's an "option" key describing the command-line option that's controlling the warning. Sneaky little key.

A diagnostic can contain zero or more locations. Each location has an optional "label" string and up to three positions inside it: a "caret" position plus 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, and it accounts for tabs and multibyte characters.
  • "byte-column" counts raw bytes.
  • "column" is equal to one of the previous two โ€” whichever one the -fdiagnostics-column-unit option says it should be. Choose your fighter.

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 gets 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. Gone but not forgotten bestie. ๐Ÿ’œ

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 also has two secondary locations, describing the left and right-hand sides of the expression, and those two 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}"
        }
    ],
    "message": "invalid operands to binary + ..."
}

If a diagnostic contains fix-it hints, it has a "fixits" array, made up of half-open intervals, similar to the output of -fdiagnostics-parseable-fixits. Half-open intervals are giving math class but make it JSON. 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
            }
        }
    ],
    "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", and insertions are expressed by having "start" equal "next". Insert = start equals next, delete = string goes bye-bye, periodt. ๐Ÿ’…

If the diagnostic has a path of control-flow events associated with it, it has a "path" array of objects representing those 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 it is, 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
        }
    }
]

๐Ÿ’– Options to Request or Suppress Warnings ๐Ÿ’–

Okay so warnings?? They're diagnostic messages that call out constructions that aren't like, inherently wrong, but they're risky ๐Ÿ’€ or they're giving "bestie there might have been an error here". Not errors, just... vibes that are off.

The next few options are language-independent, meaning they don't turn on any specific warning, they just control the kind of diagnostics GCC spits out at you.

  • -fsyntax-only โ€” Check the code for syntax errors only. That's it. Nothing beyond that. Not the moment for anything else. ๐ŸŽ€
  • -fmax-errors=n โ€” Caps the max number of error messages at n, and once you hit that, GCC just gives up and bails rather than trying to keep processing the source code. If n is 0 (which is the default), there is *no limit on how many error messages get produced. And if -Wfatal-errors is *also specified, then -Wfatal-errors takes precedence over this option. Rude but okay.
  • -w โ€” Inhibit all warning messages. All of them. Gone. Silence. ๐Ÿ™ˆ
  • -Werror โ€” Make every single warning into an error. Iconic. Terrifying. Both.
  • -Werror= โ€” Make the specified warning into an error. You append the specifier for the warning; for example -Werror=switch turns the warnings controlled by -Wswitch into errors. This switch also has a negative form, which you use to negate -Werror for specific warnings; for example -Wno-error=switch makes -Wswitch warnings not be errors, even when -Werror is in effect.

The warning message for each controllable warning includes the option that controls the warning. That option can then be used with -Werror= and -Wno-error= as described above. (You can turn off the printing of the option in the warning message with the -fno-diagnostics-show-option flag.)

Note bestie: specifying -Werror=foo automatically implies -Wfoo. However, -Wno-error=foo does not imply anything. Nothing at all. It's giving unbothered. ๐Ÿ’…

  • -Wfatal-errors โ€” This one makes the compiler abort compilation on the first error that occurs, instead of trying to keep going and printing further error messages. Girl just stops. ๐Ÿ›‘

So you can request a ton of specific warnings with options that start with -W, like -Wimplicit to request warnings on implicit declarations. Every one of these specific warning options also has a negative form starting with -Wno- to turn the warnings off; like -Wno-implicit. This manual only lists one of the two forms โ€” whichever one is not the default. For more language-specific options, also go look at C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. And extra warnings can be produced by enabling the static analyzer.

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, no matter where they sit 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 you request an unrecognized warning option (e.g. -Wunknown-warning), GCC emits a diagnostic saying that the option is not recognized. BUT โ€” plot twist โ€” if you use the -Wno- form, the behavior is slightly different: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are being produced. This lets you use new -Wno- options with old compilers, but if something goes wrong, the compiler warns you that an unrecognized option is present. Protective king behavior honestly. ๐Ÿซถ

Also the effectiveness of some warnings depends on optimizations being enabled too. For example -Wsuggest-final-types is more effective with link-time optimization, and -Wmaybe-uninitialized doesn't warn at all unless optimization is enabled. Just so you know.

  • -Wpedantic
  • -pedantic โ€” Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, and also some other programs that don't follow ISO C and ISO C++. For ISO C, it follows the version of the ISO C standard specified by whatever -std option you 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 get rejected. ๐Ÿšซ

-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__. However, only system header files should use these escape routes; application programs should avoid them. Bestie. Don't. ๐Ÿ™ˆ

Some users try to use -Wpedantic to check programs for strict ISO C conformance. They soon find that it doesn't 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.

A feature to report any failure to conform to ISO C might be useful in some instances, but it 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. Sorry babes ๐Ÿ’œ

Where the standard specified with -std represents a GNU extended dialect of C, such as gnu90 or gnu99, there is 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.) Like. Correct. ๐Ÿ‘‘

  • -pedantic-errors โ€” Give 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. This is not equivalent to -Werror=pedantic, since there are errors enabled by this option and not enabled by the latter and vice versa. Two different girlies, two different jobs. ๐Ÿ’…
  • -Wall โ€” 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:

-Waddress
-Warray-bounds=1 (only with -O2)
-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
-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++)
-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
-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 don't 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. So -Wall isn't actually "all". It's giving โœจ all โœจ in quotes. ๐Ÿ˜ญ

  • -Wextra โ€” 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 behavior honestly. ๐ŸŒˆ

Here's what it turns on:

-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)

Okay bestie, this one is the ABI gossip column ๐Ÿ’… โ€” it warns you about code that's affected by ABI changes. That includes code that may not play nice with the vendor-neutral C++ ABI, plus the psABI for whatever target you're on.

Since G++ now defaults to updating the ABI with each major release, normally -Wabi only warns 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. But -Wabi warns about more things if an older ABI version is selected (with -fabi-version=n).

You can also use -Wabi 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.

Real talk though: even though an effort has been made to warn about all such cases, there are probably some cases that are not warned about, even though G++ is generating incompatible code ๐Ÿ˜ญ. And there may also be cases where warnings are emitted even though the code that is generated is compatible. Messy, ik.

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.

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

Warns you 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

Warns you 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. Periodt.

โœจ -Wno-cpp

(C, Objective-C, C++, Objective-C++ and Fortran only) Suppress warning messages emitted by "#warning" directives. That's it, that's the whole vibe ๐Ÿซถ.


๐Ÿ”ฅ -Wdouble-promotion (C, C++, Objective-C and Objective-C++ only)

Gives you a warning when a value of type "float" is implicitly promoted to "double" ๐Ÿ˜ญ. Here's the tea: 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" ๐Ÿ’€.


โญ -Wduplicate-decl-specifier (C and Objective-C only)

Warns you if a declaration has duplicate "const", "volatile", "restrict" or "_Atomic" specifier. This warning is enabled by -Wall.


๐Ÿ’– -Wformat / -Wformat=n

Checks 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 ๐Ÿซถ.


๐ŸŒˆ -Wformat-overflow / -Wformat-overflow=level

Warns you 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 โ€” bestie, this is level 1 of -Wformat-overflow (it comes free with -Wformat), and it's playing it safe. It only yells about calls that most likely blow past the buffer. At this level, numeric args to format directives whose values are unknown get assumed to be one, and strings of unknown length get assumed to be empty. But if a numeric arg is known to be bounded to a subrange of its type, or a string arg's output is bounded either by the directive's precision or by a finite set of string literals, then GCC assumes the value in that range that gives the most bytes on output. For example, the sprintf call below gets diagnosed because even with both a and b set to zero, the terminating NUL character ('\0') that the function appends to the destination buffer will be written past its end. Bumping the buffer size by a single byte is enough to dodge the warning, though ngl it may not be enough to dodge the actual overflow.
void f (int a, int b)
{
  char buf [13];
  sprintf (buf, "a = %i, b = %i\n", a, b);
}
  • -Wformat-overflow=2 โ€” level 2 is extra and also warns about calls that might overflow the destination buffer, given an argument of sufficient length or magnitude. At level 2, unknown numeric args are assumed to have the minimum representable value for signed types with a precision greater than 1, and the maximum representable value otherwise. Unknown string args whose length can't be assumed bounded (neither by the directive's precision, nor by a finite set of string literals they might evaluate to, nor by the character array they might point to) get assumed to be 1 character long.

At level 2, the call in the example above is diagnosed again, 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. To make the call safe no matter what the two variables hold, the destination buffer size must be increased to at least 34 bytes. GCC even drops the minimum buffer size in an informational note right after the warning. ๐Ÿซถ

An alternative to making the buffer bigger is to constrain the range of formatted values. The maximum length of string args can be bounded by specifying the precision in the format directive. And when numeric args of format directives can be assumed bounded by less than the precision of their type, picking an appropriate length modifier for the format specifier will shrink the required buffer size. So like, 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 brings the max required buffer size down 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, don't warn about zero-length formats. The C standard says zero-length formats are allowed, so live your truth. โœจ
  • -Wformat-nonliteral โ€” if -Wformat is specified, also warn when the format string isn't a string literal (so it can't 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. Right now this warns about calls to printf and scanf functions where the format string isn't a string literal and there are no format arguments, like printf (foo);. That may be a security hole if the format string came from untrusted input and contains %n. Big yikes energy. (This is currently a subset of what -Wformat-nonliteral warns about, but in the future more warnings may be added to -Wformat-security that aren't included in -Wformat-nonliteral.)
  • -Wformat-signedness โ€” if -Wformat is specified, also warn when the format string requires an unsigned argument but the argument is signed, or vice versa.
  • -Wformat-truncation
  • -Wformat-truncation=level โ€” warn about calls to formatted input/output functions like snprintf and vsnprintf that might result in output truncation. When the exact number of bytes written by a format directive can't be determined at compile-time, it gets estimated based on heuristics that depend on the level argument and on optimization. Enabling optimization will in most cases improve the warning's accuracy, but it may also cause false positives. Except as noted otherwise, this option uses the same logic as -Wformat-overflow.
  • -Wformat-truncation
  • -Wformat-truncation=1 โ€” level 1 of -Wformat-truncation (enabled by -Wformat) is the cautious era: it only warns about calls to bounded functions whose return value is unused and that will most likely result in output truncation.
  • -Wformat-truncation=2 โ€” level 2 also warns about calls to bounded functions whose return value is used and that might result in truncation given an argument of sufficient length or magnitude.
  • -Wformat-y2k โ€” if -Wformat is specified, also warn about strftime formats that may yield only a two-digit year. (yes this is real and it's giving 1999 ๐Ÿ’œ)
  • -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. ๐Ÿ’€

-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 by dereferencing a null pointer. This option is only active when -fdelete-null-pointer-checks is active, which is enabled by optimizations in most targets. How precise these warnings are depends on the optimization options used.
  • -Winit-self (C, C++, Objective-C and Objective-C++ only) โ€” warn about uninitialized variables that are initialized with themselves. Note that this option can only be used with the -Wuninitialized option. ๐Ÿ™ˆ

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 doesn't 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.
  • -Wimplicit (C and Objective-C only) โ€” same as -Wimplicit-int and -Wimplicit-function-declaration. This warning is enabled by -Wall.
  • -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. For example:
switch (cond)
  {
  case 1:
    a = 1;
    break;
  case 2:
    a = 2;
  case 3:
    a = 3;
    break;
  }

This warning does not fire when the last statement of a case can't fall through โ€” like when there's a return statement or a call to a 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 actually desirable, GCC provides an attribute, __attribute__ ((fallthrough)), that's meant 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's 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:

โ€ฆand the rest of the regexes for -Wimplicit-fallthrough=3 (matched case sensitively) are these iconic little pattern babies:

  • "-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(oughu)[ \t.!](-[^\n\r])?"`
  • `"[ \t.!]*([Ee]lse,? |[Ii]ntentional(ly)? )?fall(s |
-)?thr(oughu)[ \t.!](-[^\n\r])?"`
  • -Wimplicit-fallthrough=4 โ€” case sensitively matches one of these:
    • "-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. That's it, that's the whole vibe. ๐Ÿ™ˆ

Okay so the comment itself has to be followed โ€” after optional whitespace and other comments โ€” by "case" or "default" keywords, or by a user label that comes before some "case" or "default" label. Like:

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

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 like "const". For ISO C, that kind of type qualifier literally has no effect, because the value returned by a function is not an lvalue. For C++, the warning only fires for scalar types or "void". And ISO C prohibits qualified "void" return types on function definitions, so those return types always get a warning even without this option. no cap.

This warning is also enabled by -Wextra.

  • -Wno-ignored-attributes (C and C++ only) โ€” this one controls warnings when an attribute gets ignored. It's different from the -Wattributes option because it warns whenever the compiler decides to drop an attribute, not that the attribute is unknown or used in a 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. Enabled by default in C++, and 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 gets issued for "if", "else", "while", and "for" clauses with a guarded statement that doesn't use braces, followed by an unguarded statement with the same indentation. it's giving trap ๐Ÿ˜ญ

In this next 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".  */

When it's mixed tabs and spaces, the warning uses the -ftabstop= option to figure out if the statements line up (defaulting to 8).

The warning is not issued for code involving multiline preprocessor logic like this:

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

And it's not issued after a "#line" directive either, since that typically means autogenerated code, and you can't make any assumptions about the layout of the file that 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, where that absence may adversely affect the correctness or efficiency of the 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 gets diagnosed because it's 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 isn't fully bracketed. In the next example, the initializer for "a" isn't 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 and Objective-C++ only) โ€” warns if a user-supplied include directory does not exist. simple as that bestie.
  • -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 got added between compiling with -fprofile-generate and with -fprofile-use, without regenerating the profiles. In those cases, the profile feedback data files don't contain any profile feedback information for the newly added function or file respectively. Also, when profile count data (.gcda) files are removed, GCC can't use any profile feedback information. In all these cases, warnings get 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.
  • -Wno-mismatched-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 enabled by default.

  • -Wmultistatement-macros โ€” warns about unsafe multiple statement macros that look like they're guarded by a clause such as "if", "else", "for", "switch", or "while", when actually only the first statement is guarded after the macro is expanded. the betrayal ๐Ÿ˜ญ

Like:

          #define DOIT x++; y++
          if (c)
            DOIT;

This will increment "y" unconditionally, not just when "c" holds. You can usually fix it 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, like when there's an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about. we've all been there.

It also warns if a comparison like "x<=y<=z" shows up; that's equivalent to "(x<=y ? 1 : 0) <= z", which is a totally different interpretation from ordinary mathematical notation.

It also warns for dangerous uses of the GNU extension to "?:" with an 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++ it 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 literally define the order that expressions in a C/C++ program get evaluated in terms of sequence points ๐Ÿ’… โ€” which are basically a partial ordering between the execution of parts of your program: the bits that run before the sequence point, and the bits that run after it. Where do these little guys show up?

  • after the evaluation of a full expression (one that isn't part of a bigger 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 what the sequence point rules say, the order of evaluation of subexpressions of an expression is not specified. And bestie, all these rules describe only a partial order, not a total order โ€” because, 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 ๐Ÿ˜ญ. That said, the standards committee has ruled that function calls do not overlap.


It is not specified when between sequence points modifications to the values of objects take effect. Programs whose behavior depends on this have undefined behavior ๐Ÿ’€. The C and C++ standards say it like this:

"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 these rules, the results on any particular implementation are entirely unpredictable ๐Ÿ™ˆ.

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. ngl, pretty iconic of it ๐ŸŒธ.

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++ ๐Ÿซถ.

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 <http://gcc.gnu.org/readings.html> ๐Ÿ”ฅ.

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


  • -Wno-return-local-addr โ€” bestie, this one says do NOT warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns. (Which is likeโ€ฆ handing someone your house key as the house is being demolished, but okay ๐Ÿ˜ญ)
  • -Wreturn-type โ€” warns whenever a function is defined with a return type that defaults to int. It also warns 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 counts as returning without a value).

For C only, it warns 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, that 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. periodt.

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 โ€” warns if you left shift 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 ๐Ÿ’….
    • -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 โ€” warns 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 โ€” warns whenever a switch statement does not have a default case ๐Ÿ˜ฑ.
  • -Wswitch-enum โ€” warns 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.
  • -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) โ€” warns when __sync_fetch_and_nand and __sync_nand_and_fetch built-in functions are used. These functions changed semantics in GCC 4.4 ๐Ÿ’€.
  • -Wunused-but-set-parameter โ€” warns 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 โ€” warns 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 โ€” warns 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 โ€” warns 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) โ€” warns when a typedef locally defined in a function is not used. This warning is enabled by -Wall.
  • -Wunused-parameter โ€” warns 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 ๐Ÿซถ.
  • -Wunused-variable โ€” warns 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 โ€” warns 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 ๐ŸŽ€.
  • -Wunused-value โ€” bestie, this one clocks you when a statement computes a result that literally nobody asked for. It's explicitly not used, and GCC is like "girl why". ๐Ÿ’…

Wanna shut it up? Just cast that unused expression to void. Easy.

This covers an expression-statement, or the left-hand side of a comma expression, that has no side effects. Classic example: x[i,j] gets a warning (the i is just vibing, doing nothing), but x[(void)i,j] is fine because you told it to chill. โœจ

This warning is enabled by -Wall.
  • -Wunused โ€” it's giving "all of the above, bundled". Every -Wunused option listed above, combined into one glorious package. ๐ŸŽ€

But heads up, bestie: if you want a warning about an unused function parameter, you have to either say -Wextra -Wunused (and yes, -Wall implies -Wunused), or spell out -Wunused-parameter all by yourself. No free rides. ๐Ÿ’€

  • -Wuninitialized โ€” this one yells if an object with automatic or allocated storage duration gets used before it's been initialized. Rude behavior, honestly. In C++, it also warns if a non-static reference or a non-static const member shows up in a class that has no constructors.

Bonus tea: passing a pointer (or, in C++, a reference) to an uninitialized object into a const-qualified argument of a built-in function that's known to read the object? Also diagnosed here. (-Wmaybe-uninitialized is what gets issued for ordinary functions instead.)

Want a warning about code that reads a variable's uninitialized value inside its own initializer? That's a whole separate vibe โ€” use -Winit-self. ๐Ÿฆ‹

These warnings fire for individual uninitialized elements of structure, union or array variables, and for variables that are uninitialized as a whole. They do not fire for variables or elements declared volatile. And because they depend on optimization, the exact variables/elements you get warned about depend on the precise optimization options and the version of GCC you're running. No cap.

Also note: there may be no warning about a variable that's only used to compute a value that itself is never used โ€” because data flow analysis can just delete those computations before the warnings even get printed. Gone. Poof. ๐Ÿ˜ญ

  • -Wno-invalid-memory-model โ€” okay so 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. ๐ŸŒˆ

Example time: since __atomic_store and __atomic_store_n are only defined for the relaxed, release, and sequentially consistent memory orders, this little snippet gets diagnosed:

void store (int *i)
{
  __atomic_store_n (i, 0, memory_order_consume);
}

-Winvalid-memory-model is enabled by default. (So yes, -Wno- is how you turn it off, iykyk.) ๐Ÿ‘‘

  • -Wmaybe-uninitialized โ€” for an object with automatic or allocated storage duration: if there's a path from function entry to a use of the object where it's initialized, but there are also some other paths where it's not initialized, the compiler throws a warning if it can't prove those uninitialized paths never actually run at runtime. ๐Ÿ”ฅ

Extra: passing a pointer (or, in C++, a reference) to an uninitialized object into a const-qualified function argument also gets diagnosed here. (-Wuninitialized is what's issued for built-in functions known to read the object.) And if you annotate the function with attribute access (none), that tells GCC the argument isn't used to access the object โ€” and that dodges the warning. โœจ

These warnings are only possible in optimizing compilation, because otherwise GCC isn't keeping track of the state of variables at all. It's not being lazy, it literally can't see. ๐Ÿ™ˆ

They're made optional because GCC might not be able to tell when the code is actually correct despite looking like an error. Here's an example of exactly how that happens:

{
  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 give it a default case with assert(0) or similar code. ๐Ÿซถ

This option also warns when a non-volatile automatic variable might get changed by a call to longjmp. Here's the thing: the compiler only sees the calls to setjmp. It has no idea where longjmp will be called โ€” and honestly, a signal handler could call it at any point in the code. So you might get a warning even when there's genuinely no problem, because longjmp can't actually be called at the place that would cause a problem. ๐Ÿ’€

And some spurious warnings can be avoided entirely if you declare all the functions you use that never return as noreturn. Chef's kiss. ๐Ÿ’…

This warning is enabled by -Wall or -Wextra.
  • -Wunknown-pragmas โ€” warns whenever a #pragma directive shows up that GCC just... doesn't understand. If you use this command-line option, warnings get issued even for unknown pragmas hiding in system header files. That is not the case if the warnings are only enabled by the -Wall command-line option. Sneaky difference, fr fr. ๐ŸŽ€
  • -Wno-pragmas โ€” do not warn about misuses of pragmas. We're talking incorrect parameters, invalid syntax, or conflicts between pragmas. Also see -Wunknown-pragmas above. ๐ŸŒธ
  • -Wno-prio-ctor-dtor โ€” do not warn if a priority from 0 to 100 is used for a constructor or destructor. So like, the constructor and destructor attributes let you assign a priority to the constructor/destructor to control its order of execution before main is called or after it returns. But the priority values must be greater than 100, because the compiler reserves priority values between 0--100 for the implementation itself. Respect the reservation. ๐Ÿ‘‘
  • -Wstrict-aliasing โ€” this option is only active when -fstrict-aliasing is active. It warns about code that might break the strict aliasing rules the compiler is using for optimization. It doesn't catch every case (be real, nothing does), but it does attempt to catch the more common pitfalls. It's included in -Wall. And it's equivalent to -Wstrict-aliasing=3. โœจ
  • -Wstrict-aliasing=n โ€” same deal, only active when -fstrict-aliasing is active, warns about code that might break those strict aliasing rules. Higher levels = higher accuracy (fewer false positives). Higher levels also = more effort, kinda like how -O works. And reminder: -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. It warns for all pointer conversions between possibly incompatible types โ€” even if they're 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. It 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. Iconic behavior, 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. ๐Ÿ“ˆ

An optimization that assumes signed overflow doesn't occur is perfectly safe if the values of the variables involved are such that overflow never in fact happens. So this warning can easily give a false positive: a warning about code that isn't actually a problem. To help you focus on the important stuff, several warning levels are defined. 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. ๐ŸŒˆ

  • -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. And btw, -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 โ€” bestie, this one's for when you call strcmp or strncmp and the compiler already knows the answer, because one argument's length is bigger than the size of the array the other one lives in (or bigger than the bound, in the strncmp case). That's almost always a mistake, and GCC will side-eye you for it. Like, look at this strcmp call โ€” it gets flagged because its result is necessarily non-zero, no matter what's actually inside the array a:
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 switched on for you by -Wextra. ๐Ÿ’–

  • -Wno-stringop-overflow
  • -Wstringop-overflow
  • -Wstringop-overflow=type โ€” this trio is the buffer-overflow alarm ๐Ÿšจ. It warns about calls to string-manipulation functions like memcpy and strcpy that GCC can prove will overflow 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. Heads up though: that argument only means anything for functions that work on character arrays โ€” raw memory functions like memcpy always use Object Size type-0, no matter what. The option also yells at calls that specify a size bigger than the largest possible object, or at most SIZE_MAX / 2 bytes. It works best with optimization turned on, but it can still catch a small subset of simple buffer overflows even with no optimization, in calls to GCC built-ins like __builtin_memcpy that match the standard functions. Either way, it only warns about a subset of the overflows that the corresponding overflow-checking built-ins can detect. For example, it warns on the strcpy below because it copies at least 5 characters (the string "blue" plus the terminating NUL) into a 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

The -Wstringop-overflow=1 option uses type-zero Object Size Checking to determine the sizes of destination objects. At this setting it 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 could be any one of several objects, it just assumes it's the biggest one of them. On Linux systems, with optimization enabled at this setting, it warns on the same code as when the _FORTIFY_SOURCE macro is defined to a non-zero value. ๐ŸŒธ

-Wstringop-overflow=2

The -Wstringop-overflow=2 option uses type-one Object Size Checking to determine the sizes of destination objects. At this setting it warns about overflows when writing to members of the largest complete objects whose exact size is known. But it will not warn about excessive writes to those same members of unknown objects referenced by pointers, since those pointers might point at arrays with an unknown number of elements. This is the default setting of the option. โœจ

-Wstringop-overflow=3

The -Wstringop-overflow=3 option uses type-two Object Size Checking to determine the sizes of destination objects. At this setting it warns about overflowing the smallest object or data member. This is the most restrictive setting of the option โ€” and ngl, it may end up warning about perfectly safe code. ๐Ÿ˜ญ

-Wstringop-overflow=4

The -Wstringop-overflow=4 option uses type-three Object Size Checking to determine the sizes of destination objects. At this setting it 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 warn. Same energy as -Wstringop-overflow=3: this setting may also produce warnings for totally benign code. ๐Ÿ’€


  • -Wno-stringop-overread โ€” warns about calls to string-manipulation functions like memchr, or strcpy, that GCC determines will read past the end of the source sequence. ๐Ÿ‘€
Option -Wstringop-overread is enabled by default.
  • -Wno-stringop-truncation โ€” tells GCC not to warn about calls to bounded string-manipulation functions like strncat, strncpy, and stpncpy that might either truncate the copied string or leave the destination untouched.

In this next example, the strncat call gives a bound that's shorter than the source string, so the copy gets truncated and the call gets diagnosed. Want to dodge the warning? Use bufsize - strlen (buf) - 1) as the bound. ๐ŸŽ€

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

Another example: this strncpy call copies into d only the characters before the terminating NUL, and never appends the NUL at the end. Assuming the result of strncpy is necessarily a NUL-terminated string is a super common mistake, so the call gets diagnosed. If you're not expecting a NUL-terminated result, call memcpy instead and the warning goes away. ๐Ÿ’…

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

And one more: this strncpy call passes the size of the destination buffer as the bound. If the source string's length is equal to or greater than that size, the copy won't be NUL-terminated, so the call is diagnosed too. To avoid the warning, pass 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);
  ...
}

Now, if you've got a character array that's meant to hold a sequence of bytes with no terminating NUL, you can annotate it with the nonstring attribute to shut this warning up. Careful though โ€” those arrays are not suitable arguments for functions that expect NUL-terminated strings. To help catch accidental misuse of arrays like that, GCC issues warnings unless it can prove the use is safe. ๐Ÿซถ


  • -Wsuggest-attribute=[pure|const|noreturn|format|cold|malloc] โ€” warns you when slapping an attribute on a function would probably be a glow-up. The attributes currently supported are listed right below. โญ

-Wsuggest-attribute=pure / -Wsuggest-attribute=const / -Wsuggest-attribute=noreturn / -Wmissing-noreturn / -Wsuggest-attribute=malloc

Warns about functions that might be candidates for the pure, const, noreturn or malloc attributes. The compiler only warns for functions that are visible in other compilation units, or โ€” for pure and const โ€” when it can't prove the function returns normally. A function counts as returning normally if it doesn't contain an infinite loop and doesn't return abnormally by throwing, calling abort, or trapping. This analysis needs the option -fipa-pure-const, which is enabled by default at -O and higher. Higher optimization levels make the analysis 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, bestie. GCC guesses that function pointers with format attributes which get used in assignment, initialization, parameter passing or return statements should have a matching 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 carry a format attribute to avoid the warning.

GCC also warns about function definitions that might be candidates for format attributes. Again โ€” only possible candidates. GCC guesses that format attributes might be appropriate for any function that calls something like vprintf or vscanf, but that's not always the case, and some functions that genuinely deserve format attributes might not get detected at all. ๐Ÿ™ˆ

-Wsuggest-attribute=cold

Warns about functions that might be candidates for the cold attribute. This is based on static detection, and it generally only warns about functions that always lead to a call to another cold function โ€” think wrappers of C++ throw, or fatal-error-reporting functions that lead to abort. ๐ŸงŠ


  • -Walloc-zero โ€” warns about calls to allocation functions decorated with the alloc_size attribute that ask for zero bytes, including the built-in forms of aligned_alloc, alloca, calloc, malloc, and realloc. Why? Because the behaviour of these functions when called with a zero size differs between implementations โ€” and in the case of realloc it's been deprecated โ€” so relying on it can cause subtle portability bugs and should be avoided. ๐Ÿšซ
  • -Walloc-size-larger-than=byte-size โ€” warns about calls to functions decorated with the alloc_size attribute that try to allocate objects bigger 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. Want the warnings off? Either specify a byte-size of SIZE_MAX or more, or just use -Wno-alloc-size-larger-than. โœจ
  • -Wno-alloc-size-larger-than โ€” turns OFF the -Walloc-size-larger-than= warnings. Bestie, this is literally the same energy as -Walloc-size-larger-than=SIZE_MAX or bigger. ๐Ÿ’…
  • -Walloca โ€” screams at you every single time you use alloca in the source. Every. Single. Time. ๐Ÿ”ฅ
  • -Walloca-larger-than=byte-size โ€” warns on calls to alloca with an integer argument whose value is either *zero, or that isn't bounded by a controlling predicate keeping it at most *byte-size. It also warns when the bound value is just... unknown ๐Ÿ™ˆ. Arguments of non-integer types count as unbounded even if they look constrained to the expected range. Sneaky like that.

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);
}

In the above example, passing -Walloca-larger-than=1000 would not issue a warning because the call to alloca is known to be at most 1000 bytes. However, if -Walloca-larger-than=500 were passed, the compiler would emit a warning. Yeah. ๐Ÿ’€

Unbounded uses, on the other hand, are uses of alloca with no controlling predicate constraining its integer argument. For example:

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. no cap.

Note, that 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, causing a larger than expected argument to be implicitly cast into the alloca call. the audacity tbh ๐Ÿ˜ญ

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 โ€” turns OFF the -Walloca-larger-than= warnings. Same as saying -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. lowkey nosy but okay โœจ
void f (char c, int i)
{
  c = c + i; // warns with -Wconversion
  c = c + 1; // only warns with -Warith-conversion
}
  • -Warray-bounds
  • -Warray-bounds=n โ€” this option is only active when -ftree-vrp is active (default for -O2 and above). It warns about subscripts to arrays that are **always out of bounds. This warning is enabled by -Wall. ๐Ÿ‘‘
    • -Warray-bounds=1 โ€” this is the warning level of -Warray-bounds and is enabled by -Wall; higher levels are not, and must be explicitly requested. you have to ask nicely bestie.
    • -Warray-bounds=2 โ€” this warning level also warns about out of bounds access for arrays at the end of a struct and for arrays accessed through pointers. Heads up though: this warning level may give a larger number of false positives and is deactivated by default. ๐Ÿ’€
  • -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. iykyk.

  • *-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. mismatched besties, not it ๐Ÿ’…
    • -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. red flag fr.
    • -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. the full roster, iconic โœจ

  • -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.
  • -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 warn 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. shhh, it's fine ๐Ÿคซ
  • -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) โ€” do not warn about incompatible integer to pointer and pointer to integer conversions. This warning is about implicit conversions; for explicit conversions the warnings -Wno-int-to-pointer-cast and -Wno-pointer-to-int-cast may be used. receipts ๐Ÿ“
  • -Wzero-length-bounds โ€” warn about accesses to elements of zero-length array members that might overlap other members of the same object. Declaring interior zero-length arrays is discouraged because accesses to them are undefined. See

For example, the first two stores in function bad are diagnosed because the array elements overlap the subsequent members b and c. The third store is diagnosed by -Warray-bounds because it is 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
}

Oh and btw, -Wzero-length-bounds gets switched on for you by -Warray-bounds โ€” no extra work, bestie ๐Ÿ’…


  • -Wno-div-by-zero โ€” okay so this one tells GCC to not warn when you divide an integer by zero at compile time. But floating-point division by zero? That one doesn't get warned about at all, because ngl it can be a totally legit way to get yourself an infinity or a NaN ๐ŸŒˆ
  • -Wsystem-headers โ€” this makes GCC print warning messages for stuff it finds in system header files. Normally those warnings are โœจsuppressedโœจ because the assumption is they usually don't mean real problems and they just make the compiler output harder to read (fair tbh). Using this command-line option tells GCC to emit warnings from system headers as if they happened in your code. BUT โ€” heads up โ€” using -Wall together with this option still does not warn about unknown pragmas in system headers. For that you also need -Wunknown-pragmas ๐Ÿ’€
  • -Wtautological-compare โ€” warns you when a self-comparison always evaluates to true or false. Like, it catches these little mistakes, for example:
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, bestie, will always be false ๐Ÿ™ˆ

This warning is enabled by -Wall.

  • -Wtrampolines โ€” warns about trampolines generated for pointers to nested functions. And what's a trampoline, you ask? It's a small piece of data or code 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, so it needs no special treatment. But for most targets it's made up of code, which means the stack has to be made executable for the program to work properly. So yeah, that's the vibe.
  • -Wfloat-equal โ€” warns if floating-point values are used in equality comparisons. The idea here is that sometimes it's convenient (for the programmer, not for the computer ๐Ÿ˜ญ) to think of floating-point values as approximations to infinitely precise real numbers. If that's what you're doing, then you need to figure out (by analyzing the code, or some other way) the maximum, or likely maximum, error the computation introduces, and allow for it when you do comparisons (and when you produce output too, but that's a whole different problem). Specifically: instead of testing for equality, you should check whether the two values have ranges that overlap โ€” and that's done with the relational operators. So equality comparisons are probably mistaken, fr fr.
  • -Wtraditional (C and Objective-C only) โ€” warns about certain constructs that behave differently in traditional C versus ISO C. It also warns about ISO C constructs that have no traditional C equivalent, and/or problematic constructs you should just avoid ๐Ÿ‘‘
    • Macro parameters that show up inside string literals in the macro body. In traditional C, macro replacement happens inside string literals, but in ISO C it does not.
    • In traditional C, some preprocessor directives did not exist. Traditional preprocessors only considered a line a directive if the # appeared in column 1 on the line. So -Wtraditional warns about directives that traditional C understands but ignores because the # isn't 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. Some traditional C compilers don't accept this construct.
    • 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 without 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, just so you know ๐Ÿ’€
  • -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. Which 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 โ€” warn for any shadowing. Same as -Wshadow.
  • -Wshadow=local โ€” warn when a local variable shadows another local variable or parameter.
  • -Wshadow=compatible-local โ€” warn 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 (on top of -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 this option can be disabled either by specifying byte-size of SIZE_MAX or more, or by -Wno-larger-than.

It also warns for calls to bounded functions such as memchr or strnlen that specify a bound greater than the largest possible object, which is PTRDIFF_MAX bytes by default. These warnings can only be disabled by -Wno-larger-than.

  • -Wno-larger-than โ€” disable -Wlarger-than= warnings. This option is equivalent to -Wlarger-than=SIZE_MAX or larger ๐ŸŽ€
  • -Wframe-larger-than=byte-size โ€” bestie, this one yells at you if a function's stack frame is bigger than byte-size. BUT. And this is the important part ๐Ÿ‘€ โ€” the math it does to figure out the frame size is approximate and not conservative. So your actual stack needs might be a lil bit bigger than byte-size and it still won't warn you. Also, anything you grab with alloca, variable-length arrays, or related constructs? The compiler does not count that at all when deciding whether to warn. -Wframe-larger-than=PTRDIFF_MAX is on by default. Wanna turn the warnings off? Either pass a byte-size of SIZE_MAX or more, or just use -Wno-frame-larger-than.
  • -Wno-frame-larger-than โ€” kills the -Wframe-larger-than= warnings. It's literally the same thing as -Wframe-larger-than=SIZE_MAX or bigger. Same energy, less typing ๐Ÿ’…
  • -Wno-free-nonheap-object โ€” snitches on you when you try to deallocate something that either wasn't allocated on the heap at all, or you're freeing it through a pointer that didn't come back from the matching allocation function. Example time ๐Ÿ“ โ€” stpcpy hands you back a pointer to the terminating nul character, NOT to the beginning of the object, so this free call right here gets flagged:
void f (char *p)
{
  p = stpcpy (p, "abc");
  // ...
  free (p);   // warning
}

-Wfree-nonheap-object is enabled by default.

  • -Wstack-usage=byte-size โ€” warns you if a function's stack usage might go over byte-size. And unlike that last one, this computation is conservative โ€” it's not out here guessing cute. Anything from alloca, variable-length arrays, or related constructs is included when the compiler decides whether to warn you.

The message matches the output of -fstack-usage.

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

-Wstack-usage=PTRDIFF_MAX is enabled by default. To shut it up, either give a byte-size of SIZE_MAX or more, or use -Wno-stack-usage.

  • -Wno-stack-usage โ€” disables the -Wstack-usage= warnings. Equivalent to -Wstack-usage=SIZE_MAX or larger. Slay.
  • -Wunsafe-loop-optimizations โ€” warns you when a loop can't be optimized because the compiler can't assume anything about the bounds of the loop indices. And flip side ๐Ÿ‘‘ โ€” with -funsafe-loop-optimizations, it warns if the compiler does make those assumptions.
  • -Wno-pedantic-ms-format (MinGW targets only) โ€” when you pair this with -Wformat and -pedantic without GNU extensions, it shuts off the warnings about non-ISO printf / scanf format width specifiers I32, I64, and I on Windows targets. Those ones 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 gives those types a size of 1, purely for convenience when you're doing math with void * pointers and pointers to functions. In C++, it also warns when an arithmetic operation involves NULL. -Wpedantic turns this one on too.
  • -Wno-pointer-compare โ€” stops the warning when a pointer gets compared to a zero character constant. When that happens it usually means somebody meant to dereference the pointer. Like:
const char *p = foo ();
if (p == '\0')
  return 42;

Heads up though โ€” that code up there is invalid in C++11. ๐Ÿ’€

This warning is enabled by default.

  • -Wtsan โ€” warns about unsupported features in ThreadSanitizer.

ThreadSanitizer does not support std::atomic_thread_fence and can report false positives.

This warning is enabled by default.

  • -Wtype-limits โ€” warns if a comparison is always true or always false because the data type's range is just that limited โ€” but it does not warn for constant expressions. So like, if you compare an unsigned variable against zero using < or >=? Warning. -Wextra enables this one too.
  • -Wabsolute-value (C and Objective-C only) โ€” warns on calls to standard functions that compute the absolute value of an argument when there's a better-suited standard function sitting right there. Example: calling abs(3.14) triggers the warning, because the right function for the absolute value of a double argument is fabs. It also fires when the argument in a call to such a function has an unsigned type. You can suppress it with an explicit type cast, and -Wextra enables it too.
  • -Wcomment
  • -Wcomments โ€” warns whenever a comment-start sequence /* shows up inside a /* comment, or whenever a backslash-newline shows up in a // comment. Enabled by -Wall.
  • -Wtrigraphs โ€” warns if any trigraphs show up that could change the meaning of your program. 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 with no warnings but all 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, no cap.
  • -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 is not portable. -Wpedantic and -Wextra enable this one too.
  • -Wunused-macros โ€” warns about macros defined in the main file that never get used. A macro counts as used if it's expanded or tested for existence at least once. The preprocessor also warns if the macro hadn't been used by the time it got redefined or undefined.

Built-in macros, macros defined on the command line, and macros defined in include files don't get warned about.

Note: if a macro actually is used but only inside skipped conditional blocks, the preprocessor will report it as unused. To dodge the warning in that case, you could tighten up the macro's scope by โ€” for example โ€” moving it into the first skipped block. Or you could just give it a dummy use, like:
#if defined the_macro_causing_the_warning
#endif
  • -Wno-endif-labels โ€” don't warn whenever an #else or an #endif is followed by text. This happens sometimes in older programs with code shaped like:
#if FOO
...
#else FOO
...
#endif FOO

That second and third FOO should be in comments, bestie. 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 gets 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. Warnings are disabled inside the expression that follows __extension__.
  • -Wc99-c11-compat (C and Objective-C only) โ€” warns about features that aren't in ISO C99 but are 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. Warnings are disabled in the expression that follows __extension__.
  • -Wc11-c2x-compat (C and Objective-C only) โ€” warns about features that aren't in ISO C11 but are in ISO C2X. For instance: omitting the string in _Static_assert, using [[]] syntax for attributes, using decimal floating-point types, and so on. Independent of the standards mode. 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++. Example: a request for implicit conversion from void * to a pointer to 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. Example: identifiers in ISO C++ 1998 that 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.
  • -Wcast-qual โ€” warns whenever a pointer is cast in a way that strips a type qualifier off the target type. Like, warn if a const char * gets cast to a plain old char *.

It also warns when a cast introduces a type qualifier in an unsafe way. For example, casting char ** to const char ** is unsafe โ€” check it:

/* 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';
  • -Wcast-align โ€” warns whenever a pointer is cast in a way that increases the required alignment of the target. Example: warn if a char * gets cast to an int * on machines where integers can only be accessed at two- or four-byte boundaries. ๐Ÿฆ‹
  • -Wcast-align=strict โ€” bestie, this one screams at you whenever a pointer gets cast in a way that increases the alignment the target needs. Like, if a char * gets cast to an int *? Warning. Doesn't matter what machine you're on โ€” every target, no exceptions. ๐Ÿ’…
  • -Wcast-function-type โ€” warns when you cast a function pointer to an incompatible function pointer. Okay so the deets: if the cast involves function types with a variable argument list, only the types of the initial arguments that are actually provided get considered. Any parameter of pointer-type matches any other pointer-type. Any benign differences in integral types are just ignored, like int vs. long on ILP32 targets. Same energy for type qualifiers โ€” ignored. The function type void (*) (void) is special and matches literally everything, which you can use to suppress this warning. And if the cast involves pointer to member types, this warns whenever the type cast is changing the pointer to member type. This warning is enabled by -Wextra. โœจ
  • -Wwrite-strings โ€” when compiling C, this gives string constants the type const char[length] so that 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. That's literally why -Wall doesn't request these warnings. ๐Ÿซถ When compiling C++, it warns about the deprecated conversion from string literals to char *. This warning is enabled by default for C++ programs.
  • -Wclobbered โ€” warns for variables that might be changed by longjmp or vfork. Also enabled by -Wextra. ๐Ÿ’€
  • -Wconversion โ€” warns for implicit conversions that may alter a value. This includes:
    • conversions between real and integer, like abs (x) when x is double;
    • conversions between signed and unsigned, like unsigned ui = -1;
    • and 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 disabled by using -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.

Warnings about conversion from arithmetic on a small type back to that type are only given with -Warith-conversion. โญ

  • -Wdangling-else โ€” warns about constructions where there could be confusion over which if statement an else branch belongs to. Here's an example of that exact situation:
{
  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). That's often not what the programmer expected โ€” as illustrated above by the indentation the programmer chose. 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 resulting code looks like this:

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

This warning is enabled by -Wparentheses. ๐Ÿ‘‘

  • -Wdate-time โ€” warns when macros __TIME__, __DATE__ or __TIMESTAMP__ are encountered, because they might prevent bit-wise-identical reproducible compilations. ๐Ÿ™ˆ
  • -Wempty-body โ€” warns if an empty body occurs in an if, else or do while statement. Also enabled by -Wextra. โœจ
  • -Wno-endif-labels โ€” do not warn about stray tokens after #else and #endif. ๐ŸŽ€
  • -Wenum-compare โ€” warns 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 โ€” warns when a value of enumerated type is implicitly converted to a different enumerated type. This warning is enabled by -Wextra in C. ๐ŸŒธ
  • -Wjump-misses-init (C, Objective-C only) โ€” warns 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. This warning is only supported for C and Objective-C; in C++ this sort of branch is an error in any case. ๐Ÿฆ‹

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

  • -Wsign-compare โ€” warns when a comparison between signed and unsigned values could produce an incorrect result when the signed value is converted to unsigned. In C++, this warning is also enabled by -Wall. In C, it's also enabled by -Wextra. ๐Ÿ”ฅ
  • -Wsign-conversion โ€” warns 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 โ€” warns for implicit conversions that reduce the precision of a real value. This 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. ๐ŸŒˆ
  • -Wsizeof-array-div โ€” warns 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 won't yield the number of elements in the array โ€” which is probably what the user intended. This warning warns e.g. about:
int fn ()
{
  int arr[10];
  return sizeof (arr) / sizeof (short);
}

This warning is enabled by -Wall. ๐Ÿ‘‘

  • -Wsizeof-pointer-div โ€” warns for suspicious divisions of two sizeof expressions that divide the pointer size by the element size โ€” which is the usual way to compute the array size but won't work out correctly with pointers. This warning warns e.g. about sizeof (ptr) / sizeof (ptr[0]) if ptr is not an array, but a pointer. This warning is enabled by -Wall. ๐Ÿ’–
  • -Wsizeof-pointer-memaccess โ€” warns for suspicious length parameters to certain string and memory built-in functions if the argument uses sizeof. This warning triggers, for example, for memset (ptr, 0, sizeof (ptr)); if ptr is not an array, but a pointer, and suggests a possible fix โ€” or about memcpy (&foo, ptr, sizeof (&foo));. -Wsizeof-pointer-memaccess also warns about calls to bounded string copy functions like strncat or strncpy that specify as the bound a sizeof expression of the source array. For example, in the following function the call to strncat specifies the size of the source string as the bound. That is almost certainly a mistake, and so the call is diagnosed. ๐Ÿ˜ญ
void make_file (const char *name)
{
  char path[PATH_MAX];
  strncpy (path, name, sizeof path - 1);
  strncat (path, ".text", sizeof ".text");
  ...
}

The -Wsizeof-pointer-memaccess option is enabled by -Wall. โœจ

  • -Wno-sizeof-array-argument โ€” do not warn when the sizeof operator is applied to a parameter that is declared as an array in a function definition. This warning is enabled by default for C and C++ programs. ๐ŸŽ€
  • -Wmemset-elt-size โ€” warns for suspicious calls to the memset built-in function, if the first argument references an array and the third argument is a number equal to the number of elements, but not equal to the size of the array in memory. That means the user has omitted a multiplication by the element size. This warning is enabled by -Wall. ๐Ÿ’œ
  • -Wmemset-transposed-args โ€” warns for suspicious calls to the memset built-in function where the second argument is not zero and the third argument is zero. For example, the call memset (buf, sizeof buf, 0) is diagnosed because memset (buf, 0, sizeof buf) was meant instead. The diagnostic is only emitted if the third argument is a literal zero. Otherwise, if it's an expression that is folded to zero, or a cast of zero to some type, it's far less likely that the arguments have been mistakenly transposed and no warning is emitted. This warning is enabled by -Wall. ๐Ÿ”ฅ
  • -Waddress โ€” warns about suspicious uses of memory addresses. These include using the address of a function in a conditional expression, such as void func(void); if (func), and comparisons against the memory address of a string literal, such as if (x == "abc"). Such uses typically indicate a programmer error: the address of a function always evaluates to true, so their use in a conditional usually indicates that the programmer forgot the parentheses in a function call; and comparisons against string literals result in unspecified behavior and are not portable in C, so they usually indicate that the programmer intended to use strcmp. This warning is enabled by -Wall. ๐Ÿ‘‘
  • -Wno-address-of-packed-member โ€” do not warn when the address of a packed member of a struct or union is taken, which usually results in an unaligned pointer value. This is enabled by default. ๐ŸŒธ
  • -Wlogical-op โ€” warns about suspicious uses of logical operators in expressions. This includes using logical operators in contexts where a bit-wise operator is likely to be expected. It also warns when the operands of a logical operator are the same: ๐Ÿ’…
                   extern int a;
                   if (a < 0 && a < 0) { ... }
  • -Wlogical-not-parentheses โ€” bestie, this one's out here catching the โœจsuspiciousโœจ stuff. It yells at you when you slap a logical not on the left-hand side operand of a comparison. It stays quiet if the right operand is considered a boolean expression, so don't worry about that case. Its whole purpose in life? Sniffing out code like this:
int a;
...
if (!a > 1) { ... }

You can hush the warning by wrapping the LHS into parentheses, like so:

if ((!a) > 1) { ... }

This warning is enabled by -Wall. ๐Ÿ’…

  • -Waggregate-return โ€” warns if any functions that return structures or unions are defined or called. (In languages where you can return an array, this also elicits a warning.) Not the vibe it wants, apparently. ๐Ÿ˜ญ
  • -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 the iterations. lowkey alarming fr fr.
  • -Wno-attributes โ€” do not warn if an unexpected __attribute__ is used โ€” think unrecognized attributes, function attributes applied to variables, etc. Important though: this does not stop errors for incorrect use of supported attributes. no cap.
  • -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 function declared with a type that does not include a prototype is called with arguments whose promoted types do not match those expected by the function. When -Wextra is specified, it also warns when a built-in function that takes arguments is declared without a prototype. The -Wbuiltin-declaration-mismatch warning is enabled by default. To avoid the warning, include the appropriate header to bring the prototypes of built-in functions into scope. ๐Ÿซถ

For example, the call to memset below is diagnosed by the warning because the function expects a value of type size_t as its argument but the type of 32 is int. With -Wextra, the declaration of the function is diagnosed as well.

extern void* memset ();
void f (void *d)
{
  memset (d, '\0', 32);
}
  • -Wno-builtin-macro-redefined โ€” do not warn if certain built-in macros are redefined. This suppresses warnings for redefinition of __TIMESTAMP__, __TIME__, __DATE__, __FILE__, and __BASE_FILE__. periodt. ๐Ÿ’–
  • -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 permitted without a warning if preceded by a declaration that specifies the argument types.) okay slay, it's flexible.
  • -Wold-style-declaration (C and Objective-C only) โ€” warns for obsolescent usages, according to the C Standard, in a declaration. For example, warn if storage-class specifiers like static are not the first things in a declaration. This warning is also enabled by -Wextra.
  • -Wold-style-definition (C and Objective-C only) โ€” warns if an old-style function definition is used. A warning is given even if there is a previous prototype. Here's the cute lil nuance: a definition using () is not considered an old-style definition in C2X mode, because it is equivalent to (void) in that case โ€” but it is considered an old-style definition for older standards. ๐Ÿ™ˆ
  • -Wmissing-parameter-type (C and Objective-C only) โ€” a function parameter is declared without a type specifier in K&R-style functions:
void foo(bar) { }

This warning is also enabled by -Wextra. ๐Ÿ’œ

  • -Wmissing-prototypes (C and Objective-C only) โ€” warns if a global function is defined without a previous prototype declaration. And it warns even if the definition itself provides a prototype. Use this option to detect global functions that do not have a matching prototype declaration in a header file. Heads up bestie: this option is not valid for C++, because all function declarations provide prototypes and a non-matching declaration declares an overload rather than conflict with an earlier declaration. For C++, use -Wmissing-declarations to detect missing declarations instead. ๐Ÿ‘‘
  • -Wmissing-declarations โ€” warns if a global function is defined without a previous declaration. It does so even if the definition itself provides a prototype. Use this option to detect global functions that are not declared in header files. In C, no warnings are issued for functions with previous non-prototype declarations โ€” use -Wmissing-prototypes to detect missing prototypes. In C++, no warnings are issued for function templates, or for inline functions, or for functions in anonymous namespaces. iykyk. โœจ
  • -Wmissing-field-initializers โ€” warns if a structure's initializer has some fields missing. For example, the following code causes such a warning, because x.h is implicitly zero:
struct s { int f, g, h; };
struct s x = { 3, 4 };

This option does not warn about designated initializers, so the following modification does not trigger a warning:

struct s { int f, g, h; };
struct s x = { .f = 3, .g = 4 };

In C this option does not 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, for example:

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-multichar โ€” do not warn if a multicharacter constant ('FOOF') is used. Usually they indicate a typo in the user's code, as they have implementation-defined values, and should not be used in portable code. ๐Ÿ’€
  • -Wnormalized=[none|id|nfc|nfkc] โ€” okay so in ISO C and ISO C++, two identifiers are different if they are 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 are 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 are using some other normalization scheme (like "D"), because otherwise you can easily create bugs that are literally impossible to see. scary fr.

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 may be useful as a local coding convention if the programming environment cannot be fixed to display these characters distinctly. ๐Ÿฆ‹

  • -Wno-attribute-warning โ€” do not warn about usage of functions declared with 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 -Werror flag. ๐ŸŒธ
  • -Wno-deprecated โ€” do not warn about usage of deprecated features. it's giving "we know, we know". ๐Ÿ™ˆ
  • -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 โ€” warns about One Definition Rule violations during link-time optimization. Enabled by default. ๐Ÿ”ฅ
  • -Wopenmp-simd โ€” warns if the vectorizer cost model overrides the OpenMP simd directive set by user. The -fsimd-cost-model=unlimited option can be used to relax the cost model.
  • -Woverride-init (C and Objective-C only) โ€” warns 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 โ€” warns 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;
};

lowkey wasteful, highkey worth a warning. ๐Ÿ’…

  • -Wnopacked-bitfield-compat โ€” bestie, the 4.1, 4.2 and 4.3 series of GCC literally ignore the "packed" attribute on bit-fields of type "char". Rude, right? It got fixed in GCC 4.4, but the glow-up came with consequences: the change can lead to differences in the structure layout. GCC will tell 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) โ€” warns you 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 โ€” warns 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 is possible to rearrange the fields of the structure to reduce the padding and so make the structure smaller. Lowkey a free size-up, no cap. โœจ
  • -Wredundant-decls โ€” warns if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing. Like saying the same thing twice. We get it girl, we heard you the first time. ๐Ÿ’€
  • -Wrestrict โ€” warns 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) โ€” warns if an "extern" declaration is encountered within a function. Nested. In a function. Bestie what are you doing. ๐Ÿ™ˆ
  • -Winline โ€” warns 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. It's giving โœจchaosโœจ.

  • -Wint-in-bool-context โ€” warns for suspicious use of integer values where boolean values are expected, such as conditional expressions (?:) using non-boolean integer constants in boolean context, like "if (a <= b ? 2 : 3)". Or left shifting of signed integers in boolean context, like "for (a = 0; 1 << a; a++);". Likewise 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. In C++, casting to a pointer type of smaller size is an error. 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. Found but unusable? Tragic. ๐Ÿ˜ญ
  • -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. Long long. Long long. Say it with me. ๐Ÿฆ‹
  • -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 vector operation is not implemented via SIMD capabilities of the architecture. Mainly useful for the performance tuning. Vector operation can be implemented "piecewise", which means that the scalar operation is performed on every vector element; "in parallel", which means that the vector operation is implemented using scalars of wider type, which normally is more performance efficient; and "as a single scalar", which means that vector fits into a scalar type. Three flavours, pick your fighter. โญ
  • -Wvla โ€” warns if a variable-length array is used in the code. -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. Slippery little things. ๐Ÿงš

-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 โ€” disable -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. 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. It's not you, it's the optimizer's schedule. ๐Ÿ˜ญ
  • -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. Not me leaving the door unlocked. ๐Ÿšช๐Ÿ’€
  • -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. 509 to 4095 is a glow up fr fr. ๐Ÿ”ฅ

  • -Wunsuffixed-float-constants (C and Objective-C only) โ€” issue 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) โ€” suppress 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 an static analysis of program flow which looks for "interesting" interprocedural paths through the code, and issues warnings for problems found on them. ๐Ÿ”๐Ÿ‘‘

okay so real talk bestie โ€” this analysis is so much more expensive than the other GCC warnings, like it's the designer bag of diagnostics, it costs, but it serves.

Turning this one on is basically enabling this whole little squad:

-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-possible-null-argument
-Wanalyzer-possible-null-dereference -Wanalyzer-null-argument
-Wanalyzer-null-dereference -Wanalyzer-shift-count-negative
-Wanalyzer-shift-count-overflow -Wanalyzer-stale-setjmp-buffer
-Wanalyzer-tainted-array-index
-Wanalyzer-unsafe-call-within-signal-handler
-Wanalyzer-use-after-free
-Wanalyzer-use-of-pointer-in-stale-stack-frame
-Wanalyzer-write-to-const -Wanalyzer-write-to-string-literal
heads up ๐Ÿ’› this option is only available if GCC was configured with analyzer support enabled. no analyzer support, no party, sorry.

๐ŸŒธ -Wanalyzer-too-complex ๐ŸŒธ

If -fanalyzer is on, the analyzer runs a bunch of heuristics to try and explore the control flow and data flow in your program, but complicated code can absolutely body those heuristics. It's giving "the vibes were immaculate but the graph was too big."

By default, the analysis just silently stops if the code is too complicated for the analyzer to fully explore and it hits an internal limit. Silently! Rude, honestly. The -Wanalyzer-too-complex option warns you when that happens, so you actually know your analysis ghosted you.


โœจ -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. Closing a file twice? That's not closure, bestie, that's a double-close.

๐ŸŽ€ -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". Double free is the original villain arc.

๐Ÿฆ‹ -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). Do NOT log the password, I am begging ๐Ÿ˜ญ

๐ŸŒธ -Wno-analyzer-file-leak ๐ŸŒธ

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-file-leak to disable it.

This diagnostic warns for paths through the code in which a "<stdio.h>" "FILE *" stream object is leaked. It's giving "you opened it, you never closed it, and now it's just... out there."

๐Ÿ’… -Wno-analyzer-free-of-non-heap ๐Ÿ’…

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-free-of-non-heap to disable it.

This diagnostic warns for paths through the code in which "free" is called on a non-heap pointer (e.g. an on-stack buffer, or a global). Ma'am that memory was never malloc'd, put it down.

๐Ÿซถ -Wno-analyzer-malloc-leak ๐Ÿซถ

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-malloc-leak to disable it.

This diagnostic warns for paths through the code in which a pointer allocated via an allocator is leaked: either "malloc", or a function marked with attribute "malloc". The allocation said "I'll be back" and then just... never came back. ๐Ÿ’€

๐Ÿ‘‘ -Wno-analyzer-mismatching-deallocation ๐Ÿ‘‘

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-mismatching-deallocation to disable it.

This diagnostic warns for paths through the code in which the wrong deallocation function is called on a pointer value, based on which function was used to allocate the pointer value. The diagnostic will warn about mismatches between "free", scalar "delete" and vector "delete[]", and those marked as allocator/deallocator pairs using attribute "malloc". You have to free it the way you birthed it, that's the rule.

โญ -Wno-analyzer-possible-null-argument โญ

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-possible-null-argument to disable it.

This diagnostic warns for paths through the code in which a possibly-NULL value is passed to a function argument marked with "__attribute__((nonnull))" as requiring a non-NULL value. You told the function it'd never get NULL and then you... maybe handed it NULL. ๐Ÿ™ˆ

๐ŸŒˆ -Wno-analyzer-possible-null-dereference ๐ŸŒˆ

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-possible-null-dereference to disable it.

This diagnostic warns for paths through the code in which a possibly-NULL value is dereferenced. Could be NULL, could be fine, but the analyzer is side-eyeing it.

๐Ÿ”ฅ -Wno-analyzer-null-argument ๐Ÿ”ฅ

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-null-argument to disable it.

This diagnostic warns for paths through the code in which a value known to be NULL is passed to a function argument marked with "__attribute__((nonnull))" as requiring a non-NULL value. Not "possibly" this time โ€” we know. It's confirmed. It's over.

๐Ÿ’œ -Wno-analyzer-null-dereference ๐Ÿ’œ

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-null-dereference to disable it.

This diagnostic warns for paths through the code in which a value known to be NULL is dereferenced. That's the crash, that's the segfault, that's the whole thing. ๐Ÿ’€

๐ŸŽ€ -Wno-analyzer-shift-count-negative ๐ŸŽ€

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-shift-count-negative to disable it.

This diagnostic warns for paths through the code in which a shift is attempted with a negative count. It is analogous to the -Wshift-count-negative diagnostic implemented in the C/C++ front ends, but is 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. (iykyk, it's just not the analyzer's main character moment.)

๐Ÿฆ‹ -Wno-analyzer-shift-count-overflow ๐Ÿฆ‹

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-shift-count-overflow to disable it.

This diagnostic warns for paths through the code in which a shift is attempted with a count greater than or equal to the precision of the operand's type. It is analogous to the -Wshift-count-overflow diagnostic implemented in the C/C++ front ends, but is 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.

๐ŸŒธ -Wno-analyzer-stale-setjmp-buffer ๐ŸŒธ

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-stale-setjmp-buffer to disable it.

This diagnostic warns for paths through the code in which "longjmp" is called to rewind to a "jmp_buf" relating to a "setjmp" call in a function that has returned.

When "setjmp" is called on a "jmp_buf" to record a rewind location, it records the stack frame. The stack frame becomes invalid when the function containing the "setjmp" call returns. Attempting to rewind to it via "longjmp" would reference a stack frame that no longer exists, and likely lead to a crash (or worse). Or worse!! ๐Ÿ˜ญ

๐Ÿ’… -Wno-analyzer-tainted-array-index ๐Ÿ’…

This warning requires both -fanalyzer and -fanalyzer-checker=taint to enable it; use -Wno-analyzer-tainted-array-index to disable it.

This diagnostic warns for paths through the code in which a value that could be under an attacker's control is used as the index of an array access without being sanitized. Untrusted input driving your index? Absolutely not, sanitize it first.

๐Ÿ‘‘ -Wno-analyzer-unsafe-call-within-signal-handler ๐Ÿ‘‘

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-unsafe-call-within-signal-handler to disable it.

This diagnostic warns for paths through the code in which a function known to be async-signal-unsafe (such as "fprintf") is called from a signal handler. Signal handlers are not the place, bestie, they have strict rules.

๐Ÿซถ -Wno-analyzer-use-after-free ๐Ÿซถ

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-use-after-free to disable it.

This diagnostic warns for paths through the code in which a pointer is used after a deallocator is called on it: either "free", or a deallocator referenced by attribute "malloc". Using memory after you freed it is the ghost of a pointer and it will haunt you.

โญ -Wno-analyzer-use-of-pointer-in-stale-stack-frame โญ

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-use-of-pointer-in-stale-stack-frame to disable it.

This diagnostic warns for paths through the code in which a pointer is dereferenced that points to a variable in a stale stack frame. That variable left the building and the pointer is still texting it. ๐Ÿ’€

๐ŸŽ€ -Wno-analyzer-write-to-const ๐ŸŽ€

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-write-to-const to disable it.

This diagnostic warns for paths through the code in which 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. You said const. That means const. Periodt. ๐Ÿ’…

๐ŸŒˆ -Wno-analyzer-write-to-string-literal ๐ŸŒˆ

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-write-to-string-literal to disable it.

This diagnostic warns for paths through the code in which 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. Writing into a string literal is undefined behaviour and the vibes are rancid.


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. These are your little dials, your sliders, your knobs for how hard the analyzer goes. ๐Ÿ”ฅ

The following options control the analyzer. โœจ


๐Ÿ’– -fanalyzer-call-summaries ๐Ÿ’–

Simplify interprocedural analysis by computing the effect of certain calls, rather than exploring all paths through the function from callsite to each possible return. It's giving "let's summarize the meeting instead of reading every single message in the thread."

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 it's picky about who gets summarized. As it should be. ๐Ÿ‘‘

๐Ÿงš -fanalyzer-checker=name ๐Ÿงš

Restrict the analyzer to run just the named checker, and enable it. One checker, one job, no distractions.

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. So if taint isn't doing its thing, this is why โ€” you gotta invite it.

๐Ÿ’œ -fno-analyzer-feasibility ๐Ÿ’œ

This option is intended for analyzer developers.

By default the analyzer verifies that there is a feasible control flow path for each diagnostic it emits: that the conditions that hold are not mutually exclusive. Diagnostics for which no feasible path can be found are rejected. This filtering can be suppressed with -fno-analyzer-feasibility, for debugging issues in this code. Debugging mode, not bestie mode.

๐Ÿ“ -fanalyzer-fine-grained ๐Ÿ“

This option is intended for analyzer developers.

(...and we're picking that thought right back up in the next part, hold on, don't go anywhere ๐ŸŽ€)

okay so internally the analyzer builds this whole entire thing called an "exploded graph" โ€” and bestie it's literally just control flow graphs combined with data flow information. that's it. that's the graph. ๐Ÿ’…

by default, an edge in this graph can contain the effects of a run of multiple statements within a basic block. but with -fanalyzer-fine-grained, every single statement gets its own edge. one statement, one edge, no sharing, periodt. โœจ

  • -fanalyzer-show-duplicate-count โ€” this one is for analyzer developers, iykyk. if multiple diagnostics got detected as duplicates of each other, it emits a note when reporting the best diagnostic, and that note tells you the number of additional diagnostics that got suppressed by the deduplication logic. ๐Ÿซถ
  • -fno-analyzer-state-merge โ€” also for analyzer developers, bestie, don't worry about it unless that's you. 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 โ€” again, analyzer developers only. by default the analyzer tries to simplify analysis by purging aspects of state at a program point that appear to no longer be 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 of state can be suppressed, for debugging state-handling issues. ๐Ÿ’€
  • -fanalyzer-transitivity โ€” enables transitivity of constraints within the analyzer. that's the whole thing. slay. โœจ
  • -fanalyzer-verbose-edges โ€” analyzer developer option, bestie. it enables more verbose, lower-level detail in the descriptions of control flow within diagnostic paths. ๐ŸŒธ
  • -fanalyzer-verbose-state-changes โ€” also for the analyzer developers. it enables more verbose, lower-level detail in the descriptions of events relating to state machines within diagnostic paths. ๐Ÿ’œ
  • -fanalyzer-verbosity=level โ€” this one controls the complexity of the control flow paths that get emitted for analyzer diagnostics. the level can be one of these, and yes we're going through all of them:
    1. 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. ๐Ÿ‘€
    2. as per the previous level, but also show events for the entry to each function.
    3. 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. ๐Ÿ‘‘
    4. as per the previous level, but show all control flow events, not just significant ones.
    5. 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. this option is overridden by -fdump-analyzer-stderr. ๐Ÿ“
  • -fdump-analyzer-stderr โ€” dumps internal details about what the analyzer is doing to stderr. this option overrides -fdump-analyzer. take that, previous option. ๐Ÿ’…
  • -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. so aesthetic. โœจ
  • -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. this is typically a large number of dump files, so like... be aware. ๐Ÿ˜ญ
  • -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 and file.*.tg.dot. ๐Ÿ’œ
  • -fdump-analyzer-json โ€” dumps a compressed JSON representation of analyzer internals to file.analyzer.json.gz. the precise format is subject to change, ngl. ๐Ÿ™ˆ
  • -fdump-analyzer-state-purge โ€” as per -fdump-analyzer-supergraph, dumps a representation of the "supergraph" suitable for viewing with GraphViz, but annotates 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. two dumps, one option, iconic. ๐Ÿ‘‘

โœจ Options for Debugging Your Program โœจ

to tell GCC to emit extra information for use by a debugger, in almost all cases you need only to add -g to your other options. that's it. that's the whole vibe. ๐ŸŽ€

GCC allows you to use -g with -O. but bestie, 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. this makes it reasonable to use the optimizer for programs that might have bugs.

if you are 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 do not run at all, so that -Og may result in a better debugging experience. โœจ

  • -g โ€” produces 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 (see below). ๐Ÿ‘€

  • -ggdb โ€” produces 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 โ€” produces 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. history is messy like that. ๐Ÿ’€

  • -gstabs โ€” produces debugging information in stabs format (if that is supported), without GDB extensions. this is the format used by DBX on most BSD systems. on MIPS, Alpha and System V Release 4 systems this option produces stabs debugging output that is not understood by DBX. on System V Release 4 systems this option requires the GNU assembler. ๐Ÿ˜ญ
  • -gstabs+ โ€” produces debugging information in stabs format (if that is supported), using GNU extensions understood only by the GNU debugger (GDB). the use of these extensions is likely to make other debuggers crash or refuse to read the program. ๐Ÿ™ˆ
  • -gxcoff โ€” produces debugging information in XCOFF format (if that is supported). this is the format used by the DBX debugger on IBM RS/6000 systems. ๐Ÿฆ‹
  • -gxcoff+ โ€” produces debugging information in XCOFF format (if that is supported), using GNU extensions understood only by the GNU debugger (GDB). 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 โ€” produces debugging information in Alpha/VMS debug format (if that is supported). this is the format used by DEBUG on Alpha/VMS systems. ๐Ÿ’œ
  • -glevel, -ggdblevel, -gstabslevel, -gxcofflevel, -gvmslevel โ€” requests debugging information and also uses level to specify how much information. the default level is 2. and now the levels, bestie, all of them:
    • Level 0 produces no debug information at all. thus, -g0 negates -g. โœจ
    • Level 1 produces minimal information, enough for making backtraces in parts of the program that 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. periodt.

-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. don't try to be clever, just pass the extra flag. ๐Ÿ’…

  • -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. all of them. every single one. ๐ŸŽ€
  • -femit-class-debug-always โ€” bestie, normally GCC emits the debugging info for a C++ class in one single object file and calls it a day. This flag says "no, put it in every object file that uses the class." Only reach for this if your debugger literally cannot handle the way GCC normally does class debug info, because the price of admission is that your debugging information can balloon by as much as a factor of two. ๐Ÿ’€
  • -fno-merge-debug-strings โ€” tells the linker to not merge together strings in the debugging information that are identical across different object files. Important caveat: merging isn't supported by all assemblers or linkers in the first place. Merging shrinks the debug info in the output file but costs you link processing time. And btw, merging is enabled by default, so this flag is the "actually, don't" version.
  • -fdebug-prefix-map=old=new โ€” when you're compiling files that live in directory old, record the debugging information as if they lived in directory new instead. Iconic use case: swap a build-time path for an install-time path in the debug info. You can also flip an absolute path into a relative one by using . for new. This gives you more reproducible builds that are location independent, but you might need an extra command to tell GDB where the source files actually are. See also -ffile-prefix-map. ๐Ÿซถ
  • -fvar-tracking โ€” runs the variable tracking pass, which figures out where variables are stored at each position in the code. Then better debugging information gets generated (assuming the debug info format supports that info, ofc). It's on by default when you compile with optimization (-Os, -O, -O2, ...), debugging information (-g), and the debug info format supports it. โœจ
  • -fvar-tracking-assignments โ€” annotates assignments to user variables early in compilation, then tries to carry those annotations all the way to the end, all in the name of better debug info while optimizing. Pairing it with -gdwarf-4 is recommended. Fun fact: it can be enabled even when var-tracking is disabled โ€” in that case the annotations get created and maintained, then discarded at the end. By default it's enabled together with -fvar-tracking, except when selective scheduling is enabled.
  • -gsplit-dwarf โ€” if DWARF debugging information is enabled, split as much of it as possible into a separate output file with the .dwo extension. This lets the build system avoid linking files that have debug info in them. To actually be useful though, you need a debugger that can read .dwo files. No cap. ๐Ÿฆ‹
  • -gdwarf32, -gdwarf64 โ€” with DWARF debugging info enabled, -gdwarf32 picks the 32-bit DWARF format and -gdwarf64 picks the 64-bit one. The default is target specific, but on most targets it's -gdwarf32. The 32-bit format is smaller, but it can't support more than 2GiB of debug information in any of the DWARF debug information sections. The 64-bit format allows bigger debug info, but heads up: it might not be well supported by all consumers yet. ๐Ÿ’…
  • -gdescribe-dies โ€” adds description attributes to some DWARF DIEs that have no name attribute, like artificial variables, external references and call site parameter DIEs.
  • -gpubnames โ€” generates the DWARF .debug_pubnames and .debug_pubtypes sections.
  • -ggnu-pubnames โ€” generates .debug_pubnames and .debug_pubtypes sections in a format that's suitable for conversion into a GDB index. This one is only useful with a linker that can produce GDB index version 7.
  • -fdebug-types-section โ€” when you're on DWARF Version 4 or higher, type DIEs can go into their own .debug_types section instead of being part of the .debug_info section. Putting them in a separate comdat section is more efficient because the linker can then remove duplicates. But plot twist: not all DWARF consumers support .debug_types sections yet, and on some objects .debug_types produces larger instead of smaller debugging information. ๐Ÿ˜ญ
  • -grecord-gcc-switches, -gno-record-gcc-switches โ€” this switch appends the command-line options used to invoke the compiler that may affect code generation onto 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's enabled by default. See also -frecord-gcc-switches for another way of storing compiler options into the object file.
  • -gstrict-dwarf โ€” disallows using extensions from a later DWARF standard version 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 saying "no thank you, keep it strict." ๐ŸŒธ
  • -gno-strict-dwarf โ€” allows using extensions of later DWARF standard versions than the one selected with -gdwarf-version. The chill option. ๐Ÿงš
  • -gas-loc-support โ€” informs the compiler that the assembler supports .loc directives. It may then use them so the assembler generates 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. It'll be enabled by default if, at GCC configure time, the assembler was found to support those directives.
  • -gno-as-loc-support โ€” forces GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are going to be generated at all.
  • -gas-locview-support โ€” informs the compiler that the assembler supports "view" assignment and reset assertion checking in .loc directives. 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 โ€” emits location column information into DWARF debugging information, rather than just file and line. Enabled by default.
  • -gstatement-frontiers, -gno-statement-frontiers โ€” makes GCC create markers in the internal representation at the beginning of statements, then keep them roughly in place throughout compilation, using them to guide the output of is_stmt markers in the line number table. Enabled by default when compiling with optimization (-Os, -O, -O2, ...) and outputting DWARF 2 debug information at the normal level.
  • -gvariable-location-views, -gvariable-location-views=incompat5, -gno-variable-location-views โ€” augments variable location lists with progressive view numbers implied from the line number table. This lets debug information consumers inspect state at certain points of the program, even when 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 causes 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 debug info consumers that don't know about these augmentations can still consume them โ€” they just won't get any benefit from them either. ๐Ÿ’€

This is enabled by default when outputting DWARF 2 debug information at the normal level, as long as there's assembler support, -fvar-tracking-assignments is enabled and -gstrict-dwarf is not. When assembler support isn't available, it 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. ๐Ÿ˜ญ

There's a proposed representation for view numbers that is not backward compatible with the location list format introduced in DWARF 5, enabled with -gvariable-location-views=incompat5. This option may be removed in the future, and it's only provided as a reference implementation of the proposed representation. Debug information consumers aren't expected to support this extended format, and they'd be rendered unable to decode location lists that use it.

  • -ginternal-reset-location-views, -gno-internal-reset-location-views โ€” attempts to determine location views that can be omitted from location view lists. This requires 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 using an assembler that doesn't support location view lists. The GNU assembler will flag any such error as a "view number mismatch". Only enabled on ports that define a reliable estimation function.
  • -ginline-points, -gno-inline-points โ€” generates extended debug information for inlined functions. Location view tracking markers get inserted at inlined entry points so that address and view numbers can be computed and output in the debug info. It can be enabled independently of location views โ€” in that case the view numbers just 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] โ€” produces compressed debug sections in DWARF format, if that's supported. If type isn't given, the default type depends on the capabilities of the assembler and linker you're using. type can be one of none (don't compress debug sections), 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 gets rejected. Otherwise, if the assembler doesn't support them, -gz is silently ignored when producing object files. ๐Ÿ™ˆ
  • -femit-struct-debug-baseonly โ€” emits debug information for struct-like types only when the base name of the compilation source file matches the base name of the file where the struct is defined. This substantially reduces the size of debugging information, but at a significant potential loss in type information to the debugger. See -femit-struct-debug-reduced for a less aggressive option, and -femit-struct-debug-detailed for more detailed control. This option works only with DWARF debug output. ๐Ÿ‘‘

  • -femit-struct-debug-reduced โ€” bestie, this one is โœจpickyโœจ about which struct-like types get debug info. GCC only emits it when the base name of the compilation source file matches the base name of the file where the type is defined โ€” unless the struct is a template or it lives in a system header. It shrinks your debug info a lot, but lowkey you might lose some type info in the debugger. Want something more aggressive? That's -femit-struct-debug-baseonly. Want the full control freak version? -femit-struct-debug-detailed. Heads up though: this only works with DWARF debug output. ๐Ÿฆ‹
  • -femit-struct-debug-detailed[=spec-list] โ€” the main-character version of the two options above, fr fr. You tell GCC exactly which struct-like types it should generate debug info for, and the whole point is to cut down on duplicate struct debug info across different object files in the same program. It's the detailed edition of -femit-struct-debug-reduced and -femit-struct-debug-baseonly, and ngl it handles most people's needs all by itself.

A specification looks like this, exactly:

[dir:|ind:][ord:|gen:](any|sys|base|none)

The optional first word narrows the spec to structs used directly (dir:) or indirectly (ind:). A struct type is used directly when it's the type of a variable or a member. Indirect uses come through pointers to structs โ€” like, when using an incomplete struct is valid, that use is indirect. The example, verbatim: struct one direct; struct two * indirect;.

The optional second word narrows it to ordinary structs (ord:) or generic structs (gen:). Generic structs areโ€ฆ a whole thing to explain ๐Ÿ’€. For C++, these are non-explicit specializations of template classes, or non-template classes within the above. Other languages have generics too, but -femit-struct-debug-detailed does not yet implement them.

The third word says which source files those structs must come from for GCC to emit debug info. none and any mean what you'd expect. base means the base of the name of the file where the type declaration appears has to match the base of the name of the main compilation file โ€” in practice, compiling foo.c means debug info gets generated for types declared in that file and foo.h, but not other header files. sys means those types satisfying base or declared in system or compiler headers.

You may need to experiment to figure out the best settings for your application. ๐Ÿ™ˆ

The default is -femit-struct-debug-detailed=all.

And yeah โ€” this only works 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. Simple as that. ๐Ÿ’…
  • -fno-eliminate-unused-debug-types โ€” normally, when producing DWARF output, GCC skips debug symbol output for types that are nowhere used in the source file being compiled. Sometimes you want the opposite though: GCC emitting debug info for every type declared in a compilation unit, whether or not it's actually used there. Classic scenario โ€” you're in the debugger and you want to cast a value to a type that isn't used in your program but is declared. More often than not though? This just wastes a significant amount of space. ๐Ÿ˜ญ

โœจ Options That Control Optimization โœจ

Okay so these options control the various sorts of optimizations. Buckle up. ๐ŸŽ€

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. It's giving "predictable and chill." ๐ŸŒธ

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. Trade-offs, bestie. That's the whole vibe.

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. Teamwork makes the dream work, no cap. ๐Ÿ‘‘

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 is not 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. Iconic little trick, iykyk. ๐Ÿ”ฅ

  • -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
-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 do not involve a space-speed tradeoff. Compared to -O, this option increases both compilation time and the performance of the generated code. It's giving glow-up. โœจ

-O2 turns on all optimization flags specified by -O. 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-pre
-ftree-switch-conversion  -ftree-tail-merge -ftree-vrp

Please note the warning under -fgcse about invoking -O2 on programs that use computed gotos. Not me being dramatic โ€” it's literally in the docs, bestie. ๐Ÿซถ

NOTE: In Ubuntu 8.10 and later versions, -D_FORTIFY_SOURCE=2, in Ubuntu 24.04 and later versions, -D_FORTIFY_SOURCE=3, is set by default, and is activated when -O is set to 2 or higher. This enables additional compile-time and run-time checks for several libc functions. To disable, specify either -U_FORTIFY_SOURCE or -D_FORTIFY_SOURCE=0.
  • -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-loop-vectorize -ftree-partial-pre -ftree-slp-vectorize
-funswitch-loops -fvect-cost-model -fvect-cost-model=dynamic
-fversion-loops-for-strides
  • -O0 โ€” Reduce compilation time and make debugging produce the expected results. This is the default. The cozy baseline. ๐Ÿงธ
  • -Os โ€” Optimize for size. -Os enables all -O2 optimizations except those that often increase code size:
-falign-functions  -falign-jumps -falign-labels  -falign-loops
-fprefetch-loop-arrays  -freorder-blocks-algorithm=stc

It also enables -finline-functions, causes the compiler to tune for code size rather than execution speed, and performs further optimizations designed to reduce code size. Tiny and cute. ๐ŸŽ€

  • -Ofast โ€” Disregard strict standards compliance. ๐Ÿ’€ -Ofast enables all -O3 optimizations. It also enables optimizations that are not valid for all standard-compliant programs. 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.
Bestie, please read that again: not valid for all standard-compliant programs. She's fast, she's reckless, she does NOT care about your standards. โš ๏ธ
  • -Og โ€” Optimize the debugging experience. -Og should be the optimization level of choice for the standard edit-compile-debug cycle, offering a reasonable level of optimization while maintaining fast compilation and a good debugging experience. It is a better choice than -O0 for producing debuggable code because some compiler passes that collect debug information are disabled at -O0. It's giving โœจthe best of both worldsโœจ.

Like -O0, -Og completely disables a number of optimization passes so that individual options controlling them have no effect. Otherwise -Og enables all -O1 optimization flags except for those that may interfere with debugging:

-fbranch-count-reg  -fdelayed-branch -fdse  -fif-conversion
-fif-conversion2 -finline-functions-called-once
-fmove-loop-invariants  -fssa-phiopt -ftree-bit-ccp  -ftree-dse
-ftree-pta  -ftree-sra

If you use multiple -O options, with or without level numbers, the last such option is the one that is effective. Last one wins, periodt. ๐Ÿ’…


Options of the form -fflag specify machine-independent flags. Most flags 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 you typically use. You can figure out the other form by either removing no- or adding it. Easy math, bestie. ๐Ÿงฎ

The following options control specific optimizations. They are either activated by -O options or are related to ones that are. You can use the following flags in the rare cases when "fine-tuning" of optimizations to be performed is desired. That's your cue to get very specific about what you want. ๐Ÿ”

  • -fno-defer-pop โ€” okay so some machines have to pop the args after a function call, right? This makes them pop those args the literal second each function returns. But at -O1 and up, -fdefer-pop is the default, which lets args just chill and pile up on the stack across several calls and then get popped all at once. Efficiency slay. ๐Ÿ’…
  • -fforward-propagate โ€” runs a forward propagation pass on RTL. What it does is try to smoosh two instructions together and see if the result can be simplified. And if loop unrolling is active? Then you get two passes, bestie, and the second one is scheduled after loop unrolling. This one is on by default at -O, -O2, -O3, -Os. โœจ
  • -ffp-contract=style โ€” floating-point contraction, let's talk about it:
    • -ffp-contract=off disables floating-point expression contraction. periodt.
    • -ffp-contract=fast enables floating-point expression contraction, like forming fused multiply-add operations if the target natively supports them. iconic behavior.
    • -ffp-contract=on enables floating-point expression contraction if the language standard allows it. Ngl though โ€” this is currently not implemented and gets treated exactly equal to -ffp-contract=off. ๐Ÿ˜ญ

The default is -ffp-contract=fast.

  • -fomit-frame-pointer โ€” omits the frame pointer in functions that genuinely don't need one. This skips the instructions to save, set up and restore that frame pointer, and on lots of targets it frees up an extra register too. ๐ŸŽ€

On some targets this flag does literally nothing, because the standard calling sequence always uses a frame pointer so it can't be omitted. Not me finding out the hard way. ๐Ÿ’€

And heads up: -fno-omit-frame-pointer does not guarantee the frame pointer is used in all functions. Several targets always omit it in leaf functions regardless.

Enabled by default at -O and higher.

  • -foptimize-sibling-calls โ€” optimizes sibling and tail recursive calls. Enabled at levels -O2, -O3, -Os. ๐Ÿฆ‹
  • -foptimize-strlen โ€” optimizes various standard C string functions (like strlen, strchr or strcpy) and their _FORTIFY_SOURCE counterparts into faster alternatives. Enabled at levels -O2, -O3. ๐Ÿ”ฅ
  • -fno-inline โ€” do not expand any functions inline apart from the ones marked with the always_inline attribute. This is the default when you're not optimizing. Single functions can be exempted from inlining by marking them with the noinline attribute. ๐Ÿ™ˆ
  • -finline-small-functions โ€” integrates functions into their callers when the body is smaller than the expected function call code (so the overall size of the program gets smaller, cute). The compiler heuristically decides which functions are simple enough to be worth integrating this way. And this inlining applies to all functions, even the ones not declared inline. Enabled at levels -O2, -O3, -Os. โœจ
  • -findirect-inlining โ€” inlines the indirect calls too, the ones that get discovered to be known at compile time thanks to previous inlining. Lowkey 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 โ€” considers all functions for inlining, even if they're not declared inline. The compiler heuristically decides which functions are worth integrating this way. And if all calls to a given function get integrated, and that function is declared static, then it's 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 โ€” considers all static functions called once for inlining into their caller, even if they're not marked inline. If a call to a given function gets 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 โ€” inlines functions marked by always_inline and functions whose body seems smaller than the function call overhead, and it does it early, before doing -fprofile-generate instrumentation and the real inlining pass. Doing it this way makes profiling significantly cheaper and usually makes inlining faster on programs with large chains of nested wrapper functions. Enabled by default. ๐ŸŒธ
  • -fipa-sra โ€” performs 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, and this flag gives you coarse control over that limit. n is the size of functions that can be inlined in number of pseudo instructions. โœจ

Real talk though: inlining is actually controlled by a number of parameters, which you can specify individually using --param name=value. The -finline-limit=n option sets some of these parameters like so:

  • 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 to -finline-limit that results in default behavior. ๐Ÿ’€
Note: pseudo instruction represents, in this particular context, an abstract measurement of 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 an another. So like, don't read into it too hard.
  • -fno-keep-inline-dllexport โ€” this is a more fine-grained version of -fkeep-inline-functions, which applies only to functions 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. Not me keeping things around just in case. ๐Ÿ“
  • -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. And if you want to force the compiler to check whether a variable is referenced, regardless of whether optimization is on or not, use the -fno-keep-static-consts option.
  • -fmerge-constants โ€” attempts 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 -O, -O2, -O3, -Os. โญ
  • -fmerge-all-constants โ€” attempts to merge identical constants and identical variables. This option implies -fmerge-constants. On top of that, it also considers e.g. even constant initialized arrays or initialized constant variables with integral or floating-point types.
Okay bestie this is the important bit: 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. ๐Ÿšจ
  • -fmodulo-sched โ€” performs swing modulo scheduling immediately before the first scheduling pass. This pass looks at innermost loops and reorders their instructions by overlapping different iterations. ๐ŸŒธ
  • -fmodulo-sched-allow-regmoves โ€” performs more aggressive SMS-based modulo scheduling with register moves allowed. By setting this flag, certain anti-dependences 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 โ€” disables the optimization pass that scans for opportunities to use "decrement and branch" instructions on a count register, instead of instruction sequences that decrement a register, compare it against zero, and then branch based upon the result. This option is only meaningful on architectures that support such instructions, which include x86, PowerPC, IA-64 and S/390. And note that -fno-branch-count-reg doesn't remove the decrement and branch instructions from the generated instruction stream introduced by other optimization passes. ๐Ÿ™ˆ

The default is -fbranch-count-reg at -O1 and higher, except for -Og.

  • -fno-function-cse โ€” do not put function addresses in registers; make each instruction that calls a constant function contain the function's address explicitly. This option results in less efficient code, but some strange hacks that alter the assembler output may be confused by the optimizations performed when this option is not used. The default is -ffunction-cse. ๐Ÿ’œ
  • -fno-zero-initialized-in-bss โ€” if the target supports a BSS section, GCC by default puts variables that are initialized to zero into BSS. This can save space in the resulting code. ๐ŸŽ€

This option turns off that behavior, 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.

The default is -fzero-initialized-in-bss.

  • -fthread-jumps โ€” performs optimizations that check to see if a jump branches to a location where another comparison subsumed by the first is found. If so, the first branch is 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. Enabled at levels -O2, -O3, -Os. โœจ
  • -fsplit-wide-types โ€” when using a type that occupies multiple registers, such as long long on a 32-bit system, split the registers apart and allocate them independently. This normally generates better code for those types, but may make debugging more difficult. Trade-offs, bestie. ๐Ÿ˜ญ Enabled at levels -O, -O2, -O3, -Os.
  • -fsplit-wide-types-early โ€” fully split wide types early, instead of very late. This option has no effect unless -fsplit-wide-types is turned on. This is the default on some targets. ๐Ÿซถ
  • -fcse-follow-jumps โ€” bestie, this one's about common subexpression elimination (CSE for short ๐Ÿ’…). With it on, CSE will scan straight through jump instructions whenever the jump's target isn't reached by any other path. Like, picture CSE hitting an if statement that has an else clause โ€” it follows that jump when the condition tested comes out false. Iconic.

Enabled at levels -O2, -O3, -Os.

  • -fcse-skip-blocks โ€” lowkey the sibling of -fcse-follow-jumps, except this one makes CSE follow jumps that conditionally skip over blocks. So when CSE runs into a simple if statement with no else clause, -fcse-skip-blocks makes it follow the jump around the body of that if. slay.

Enabled at levels -O2, -O3, -Os.

  • -frerun-cse-after-loop โ€” literally just re-runs common subexpression elimination after the loop optimizations have done their thing. second pass energy โœจ.

Enabled at levels -O2, -O3, -Os.

  • -fgcse โ€” runs a global common subexpression elimination pass. And not just that โ€” this pass also does global constant and copy propagation. multi-tasking queen ๐Ÿ‘‘.
Note: when you're compiling a program that uses computed gotos (a GCC extension, iykyk), 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 this one's enabled, global common subexpression elimination tries to move loads that are only killed by stores into themselves. The way that works out: a loop containing a load/store sequence can get changed into a load outside the loop, plus a copy/store within the loop. chef's kiss ๐ŸŽ€.

Enabled by default when -fgcse is enabled.

  • -fgcse-sm โ€” flip this on and a store motion pass runs after global common subexpression elimination. This pass attempts to move stores out of loops. Team it up with -fgcse-lm and loops containing a load/store sequence can be changed into a load before the loop and a store after the loop. obsessed fr.

Not enabled at any optimization level.

  • -fgcse-las โ€” with -fgcse-las enabled, the global common subexpression elimination pass eliminates redundant loads that come after stores to the same memory location (both partial and full redundancies, bestie, we're thorough ๐Ÿ’…).

Not enabled at any optimization level.

  • -fgcse-after-reload โ€” when this is enabled, a redundant load elimination pass is performed after reload. The whole point of this pass is to clean up redundant spilling. tidy vibes ๐Ÿงš.

Enabled by -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. It assumes that loop code doesn't invoke undefined behavior โ€” like, no causing signed integer overflows or out-of-bound array accesses, okay?? ๐Ÿ˜ญ The bounds for the number of iterations get used to guide loop unrolling, peeling, and loop exit test optimizations.

This option is enabled by default.

  • -funconstrained-commons โ€” this tells the compiler that variables declared in common blocks (e.g. Fortran) may later be overridden with longer trailing arrays. That prevents certain optimizations which depend on knowing the array bounds. nosy optimizations, blocked ๐Ÿ’€.
  • -fcrossjumping โ€” performs the 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, so, no promises, bestie ๐Ÿ™ˆ.

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 don't have instructions to support it. Enabled by default at -O and higher on architectures that support this.
  • -fdce โ€” performs dead code elimination (DCE) on RTL. Enabled by default at -O and higher. bye bye dead code ๐Ÿฆ‹.
  • -fdse โ€” performs dead store elimination (DSE) on RTL. Enabled by default at -O and higher.
  • -fif-conversion โ€” attempts to transform conditional jumps into branch-less equivalents. That includes conditional moves, min, max, set flags, abs instructions, and some tricks doable by standard arithmetics. The use of conditional execution on chips where it's available is controlled by -fif-conversion2. So cute, so efficient ๐Ÿ’–.

Enabled at levels -O, -O2, -O3, -Os, but not with -Og.

  • -fif-conversion2 โ€” uses conditional execution (where available) to transform conditional jumps into branch-less equivalents.

Enabled at levels -O, -O2, -O3, -Os, but not with -Og.

  • -fdeclone-ctor-dtor โ€” okay so 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 get changed into thunks that call a common implementation. deduplication but make it C++ โœจ.

Enabled by -Os.

  • -fdelete-null-pointer-checks โ€” assumes that programs can't safely dereference null pointers, and that no code or data element lives at address zero. This option enables simple constant folding optimizations at all optimization levels. On top of that, other optimization passes in GCC use this flag to control global dataflow analyses that eliminate useless checks for null pointers. Those assume that a memory access to address zero always results in a trap โ€” so if a pointer is checked after it's already been dereferenced, it can't be null.
Note though: 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 โ€” attempts to convert calls to virtual functions into direct calls. This happens both within a procedure and interprocedurally, as part of indirect inlining (-findirect-inlining) and interprocedural constant propagation (-fipa-cp). Enabled at levels -O2, -O3, -Os.
  • -fdevirtualize-speculatively โ€” attempts to convert calls to virtual functions into speculative direct calls. Based on analysis of the type inheritance graph, it figures out for a given call the set of likely targets. If that set is small โ€” preferably of size 1 โ€” it changes the call into a conditional deciding between direct and indirect calls. These speculative calls enable more optimizations, like inlining. And when they seem useless after further optimization, they get converted back into their original form. it's giving glow-up-then-glow-down ๐Ÿฆ‹.
  • -fdevirtualize-at-ltrans โ€” streams 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. (trade-offs, bestie, we all have them ๐Ÿ’…)
  • -fexpensive-optimizations โ€” performs a number of minor optimizations that are relatively expensive. small but bougie ๐ŸŽ€.

Enabled at levels -O2, -O3, -Os.

  • -free โ€” attempts 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. ngl, very satisfying.

Enabled for Alpha, AArch64 and x86 at levels -O2, -O3, -Os.

  • -fno-lifetime-dse โ€” in C++, the value of an object is only affected by changes within its lifetime: when the constructor begins, the object has an indeterminate value, and any changes during the lifetime of the object are dead when the object is destroyed. Normally dead store elimination takes advantage of this. But if your code relies on the value of the object storage persisting beyond the lifetime of the object, you can use this flag to disable this optimization. To preserve stores before the constructor starts (e.g. because your operator new clears the object storage) but still treat the object as dead after the destructor, you can use -flifetime-dse=1. The default behavior can be explicitly selected with -flifetime-dse=2. And -flifetime-dse=0 is equivalent to -fno-lifetime-dse. options for daysss ๐Ÿ’œ
  • -flive-range-shrinkage โ€” attempts to decrease register pressure through register live range shrinkage. This is helpful for fast processors with small or moderate size register sets. squeeze that register pressure out ๐Ÿ“.
  • -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, but for those targets that do support it, it's the default because it generates better code. main character algorithm fr ๐Ÿ‘‘.
  • -fira-region=region โ€” use the specified regions for the integrated register allocator. The region argument should be one of the following:
    • 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 is enabled by default when compiling with optimization for speed (-O, -O2, ...).
    • one โ€” use all functions as a single region. This typically results in the smallest code size, and is 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. (worth it though, probably โœจ)

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 option usually results in generation of faster and smaller code on machines with large register files (>= 32 registers), but it can slow the compiler down.

This option is enabled at level -O3 for some targets.

  • -fno-ira-share-save-slots โ€” bestie this turns OFF sharing of the stack slots that hold call-used hard registers that gotta survive a call. So every hard register gets its own lil stack slot ๐ŸŽ€ which meansโ€ฆ yeah, function stack frames get bigger. it's giving "more room, more problems" fr fr.
  • -fno-ira-share-spill-slots โ€” same energy, different victim: this disables sharing of stack slots allocated for pseudo-registers ๐Ÿ’€. Every pseudo-register that didn't snag a hard register gets its own separate stack slot, and guess what โ€” function stack frames are larger. periodt.
  • -flra-remat โ€” turns on CFG-sensitive rematerialization in LRA โœจ. Instead of loading values of spilled pseudos, LRA tries to rematerialize (aka recalculate) values whenever it's profitable. main character behavior ngl.

Enabled at levels -O2, -O3, -Os.

  • -fdelayed-branch โ€” if the target machine supports it, this attempts to reorder instructions so we can actually use those instruction slots chilling after delayed branch instructions ๐Ÿฆ‹.

Enabled at levels -O, -O2, -O3, -Os, but not at -Og.

  • -fschedule-insns โ€” if the target machine supports it, this tries to reorder instructions to kill execution stalls caused by required data not being ready yet ๐Ÿ˜ญ. It's a lifesaver on machines with slow floating point or memory load instructions, because it lets other instructions get issued while we wait for the load or floating-point result to be needed. iconic.

Enabled at levels -O2, -O3.

  • -fschedule-insns2 โ€” basically -fschedule-insns but it requests an additional pass of instruction scheduling after register allocation is done ๐Ÿ’…. Super 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 โ€” disables instruction scheduling across basic blocks. That scheduling is normally enabled when we schedule before register allocation, i.e. with -fschedule-insns or at -O2 or higher ๐ŸŒธ.
  • -fno-sched-spec โ€” disables speculative motion of non-load instructions. Again, normally enabled when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher ๐Ÿ™ˆ.
  • -fsched-pressure โ€” enables 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 it can improve the generated code and shrink its size by stopping register pressure from climbing above the number of available hard registers โ€” and thus preventing the spills that follow in register allocation. no cap, that's a glow-up.
  • -fsched-spec-load โ€” allows speculative motion of some load instructions โœจ. Only makes sense when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher.
  • -fsched-spec-load-dangerous โ€” allows speculative motion of more load instructions ๐Ÿ˜ณ. Note the name, bestie โ€” dangerous. 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 โ€” defines 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 no insns get moved prematurely. -fsched-stalled-insns=0 means there's no limit on how many queued insns can be moved prematurely. And -fsched-stalled-insns with no value is equivalent to -fsched-stalled-insns=1 ๐Ÿ’–.
  • -fsched-stalled-insns-dep, -fsched-stalled-insns-dep=n โ€” defines how many insn groups (cycles) get examined for a dependency on a stalled insn that's a candidate for premature removal from the queue of stalled insns ๐Ÿ‘‘. This only does anything 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 with no 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, which results in faster schedules.
โš ๏ธ Heads up bestie: this option is experimental, 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 โ€” enables the group heuristic in the scheduler ๐Ÿ’…. It favors the instruction that belongs to a schedule group. Enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -fsched-critical-path-heuristic โ€” enables the critical-path heuristic in the scheduler ๐ŸŽ€. It 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 โ€” enables the speculative instruction heuristic in the scheduler ๐Ÿฆ‹. It 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 โ€” enables the rank heuristic in the scheduler โญ. It 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 โ€” enables the last-instruction heuristic in the scheduler ๐ŸŒธ. It favors the instruction that's 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 โ€” enables the dependent-count heuristic in the scheduler ๐Ÿ’œ. It 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 โ€” okay so modulo scheduling happens before traditional scheduling. If a loop is modulo scheduled, later scheduling passes might 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, round two ๐Ÿ’…. Selective scheduling runs instead of the second scheduler pass.
  • -fsel-sched-pipelining โ€” enables software pipelining of innermost loops during selective scheduling ๐ŸŽ€. This option has no effect unless one of -fselective-scheduling or -fselective-scheduling2 is turned on. iykyk.
  • -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 โ€” so some object formats, like ELF, allow interposing of symbols by the dynamic linker ๐Ÿ‘€. That means for symbols exported from the DSO, the compiler can't do interprocedural propagation, inlining and other optimizations, because it has to assume the function or variable in question might change. This feature is useful โ€” for example, to rewrite memory allocation functions by 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). Similarly, if interposition happens for variables, the constructor of the variable will be the same. The 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, rather than at the top of the function ๐Ÿซถ. This flag is enabled by default at -O and higher.
  • -fshrink-wrap-separate โ€” shrink-wrap separate parts of the prologue and epilogue separately, so those parts are only executed when needed ๐ŸŒˆ. This option is on by default, but has no effect unless -fshrink-wrap is also turned on and the target supports this.
  • -fcaller-saves โ€” enables allocation of values to registers that get clobbered by function calls, by emitting extra instructions to save and restore the registers around such calls โœจ. That allocation only happens 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 you don't need to save and restore them around calls. This is 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 can't be known exactly (this happens on targets that don't expose prologues and epilogues in RTL).

  • -fconserve-stack โ€” attempts 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 โ€” performs reassociation on trees โœจ. This flag is enabled by default at -O and higher.
  • -fcode-hoisting โ€” performs code hoisting ๐Ÿ”ฅ. Code hoisting tries to move the evaluation of expressions executed on all paths to the function exit as early as possible. This is especially useful as a code size optimization, but it often helps for code speed as well. This flag is enabled by default at -O2 and higher.
  • -ftree-pre โ€” bestie, this one does partial redundancy elimination (PRE) on trees. it's on by default at -O2 and -O3, slay โœจ
  • -ftree-partial-pre โ€” makes PRE more aggressive ๐Ÿ’… on by default at -O3, she's a little extra and we love that for her
  • -ftree-forwprop โ€” performs forward propagation on trees ๐ŸŒˆ on by default at -O and higher
  • -ftree-fre โ€” full redundancy elimination (FRE) on trees ๐Ÿ”ฅ the tea is that FRE and PRE are not the same: FRE only looks at expressions computed on all paths leading to the redundant computation. this analysis is faster than PRE, tho it exposes fewer redundancies (tragic but ok). on by default at -O and higher
  • -ftree-phiprop โ€” hoisting of loads from conditional pointers, on trees ๐Ÿฆ‹ on by default at -O and higher
  • -fhoist-adjacent-loads โ€” speculatively hoists 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 ๐Ÿ‘‘ on by default at -O2 and higher
  • -ftree-copy-prop โ€” copy propagation on trees, which eliminates unnecessary copy operations ๐ŸŽ€ on by default at -O and higher
  • -fipa-pure-const โ€” discovers which functions are pure or constant ๐Ÿ” on by default at -O and higher
  • -fipa-reference โ€” discovers which static variables do not escape the compilation unit ๐Ÿšช on by default at -O and higher
  • -fipa-reference-addressable โ€” discovers read-only, write-only and non-addressable static variables โœจ on by default at -O and higher
  • -fipa-stack-alignment โ€” reduces stack alignment on call sites if possible ๐Ÿซถ on by default, no cap
  • -fipa-pta โ€” performs 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 is not enabled by default at any optimization level, periodt.
  • -fipa-profile โ€” interprocedural profile propagation. functions called only from cold functions get marked as cold ๐Ÿฅถ also, functions executed once (like "cold", "noreturn", static constructors or destructors) get identified. cold functions and loop less parts of functions executed once are then optimized for size. on by default at -O and higher
  • -fipa-modref โ€” interprocedural mod/ref analysis ๐Ÿงš this one analyzes the side effects of functions (like which memory locations are modified or referenced) and enables better optimization across the function call boundary. on by default at -O and higher
  • -fipa-cp โ€” interprocedural constant propagation ๐ŸŒธ this optimization analyzes the program to figure out when values passed to functions are constants, then optimizes accordingly. it can substantially increase performance if the application has constants passed to functions ๐Ÿ”ฅ on by default at -O2, -Os and -O3. also enabled by -fprofile-use and -fauto-profile
  • -fipa-cp-clone โ€” performs 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). on by default at -O3. also enabled by -fprofile-use and -fauto-profile
  • -fipa-bit-cp โ€” when enabled, performs interprocedural bitwise constant propagation ๐ŸŽ€ on by default at -O2 and by -fprofile-use and -fauto-profile. it requires that -fipa-cp is enabled
  • -fipa-vrp โ€” when enabled, performs interprocedural propagation of value ranges ๐Ÿ“Š on by default at -O2. it requires that -fipa-cp is enabled
  • -fipa-icf โ€” performs Identical Code Folding for functions and read-only variables ๐Ÿช„ this optimization reduces code size and may disturb unwind stacks by replacing a function by an equivalent one with a different name. it works more effectively with link-time optimization enabled.

ngl, even though the behavior is similar to the Gold Linker's ICF optimization, GCC ICF works on different levels, so the optimizations are not the same โ€” there are equivalences that are found only by GCC and equivalences found only by Gold ๐Ÿ‘ฏ

on by default at -O2 and -Os

  • -flive-patching=level โ€” controls GCC's optimizations to produce output suitable for live-patching ๐Ÿ”ง

okay so here's the lore: 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. 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) ๐Ÿ˜ญ
  • -fisolate-erroneous-paths-dereference โ€” detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer ๐Ÿ‘€ isolates those paths from the main control flow and turns the statement with erroneous or undefined behavior into a trap. on by default at -O2 and higher, and it depends on -fdelete-null-pointer-checks also being enabled
  • -fisolate-erroneous-paths-attribute โ€” detects paths that trigger erroneous or undefined behavior due to a null value being used in a way forbidden by a returns_nonnull or nonnull attribute ๐Ÿšซ 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 may be enabled by -O2 in the future (mysterious of her, honestly)
  • -ftree-sink โ€” performs forward store motion on trees ๐ŸŒŠ on by default at -O and higher
  • -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 on by default at -O1 and higher, except for -Og. it requires that -ftree-ccp is enabled
  • -ftree-ccp โ€” performs sparse conditional constant propagation (CCP) on trees โญ this pass only operates on local scalar variables and is on by default at -O and higher
  • -fssa-backprop โ€” propagates information about uses of a value up the definition chain in order to simplify the definitions ๐Ÿ”„ for example, this pass strips sign operations if the sign of a value never matters. on by default at -O and higher
  • -fssa-phiopt โ€” performs pattern matching on SSA PHI nodes to optimize conditional code ๐ŸŽฏ this pass is on 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 ๐ŸŒธ on by default at -O2 and higher
  • -ftree-tail-merge โ€” looks for identical code sequences ๐Ÿ‘ฏ when found, it replaces one with a jump to the other. this optimization is known as tail merging or cross jumping. on 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 โฑ๏ธ
  • -ftree-dce โ€” performs dead code elimination (DCE) on trees ๐Ÿ’€ on by default at -O and higher
  • -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 ๐Ÿ“ on by default at -O2 and higher if -Os is not also specified
  • -ffinite-loops โ€” assumes that a loop with an exit will eventually take the exit and not loop indefinitely ๐Ÿ” this allows the compiler to remove loops that otherwise have no side-effects, not considering eventual endless looping as such. on by default at -O2 for C++ with -std=c++11 or higher
  • -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 โœจ this also performs jump threading (to reduce jumps to jumps). on by default at -O and higher ๐ŸŽ€
  • -ftree-dse โ€” bestie, this one does dead store elimination (DSE) on trees. And what even is a dead store, you ask? It's when you write to some memory location and then, like, immediately overwrite it with another store before anything ever reads it. The first store was giving absolutely nothing. So it gets yeeted. ๐Ÿ’€ Enabled by default at -O and higher, no cap.
  • -ftree-ch โ€” this performs loop header copying on trees. It's lowkey iconic because it makes code motion optimizations way more effective, and it also saves you one whole jump. Enabled by default at -O and higher. But it is not enabled for -Os, because it usually makes your code bigger and -Os said "we're not doing that here." ๐Ÿ™ˆ
  • -ftree-loop-optimize โ€” does loop optimizations on trees. Enabled by default at -O and higher. Simple. Slay. โœจ
  • -ftree-loop-linear
  • -floop-strip-mine
  • -floop-block โ€” these three do loop nest optimizations. Same thing as -floop-nest-optimize, fr fr. But heads up: to actually use this code transformation, GCC has to be configured with --with-isl to enable the Graphite loop transformation infrastructure. No --with-isl, no vibe. ๐Ÿซถ
  • -fgraphite-identity โ€” enables the identity transformation for graphite. For every SCoP we generate the polyhedral representation and then transform it right back to gimple. Using -fgraphite-identity you can check out the costs or the benefits of the whole GIMPLE -> GRAPHITE -> GIMPLE glow-up journey. Some minimal optimizations also get performed by the code generator isl, like index splitting and dead code elimination in loops. It's giving "look how far we came just to end up here" ๐Ÿ’…
  • -floop-nest-optimize โ€” enables the isl based loop nest optimizer. It's a generic loop nest optimizer built on the Pluto optimization algorithms, and it calculates a loop structure optimized for data-locality and parallelism. This option is experimental. You've been warned, bestie. ๐ŸŽ€
  • -floop-parallelize-all โ€” uses the Graphite data dependence analysis to sniff out loops that can be parallelized. It parallelizes all the loops that can be analyzed to not contain loop carried dependences โ€” and it does not check whether parallelizing them is actually profitable. It's just out here parallelizing with reckless abandon. Main character energy, honestly. ๐Ÿ”ฅ
  • -ftree-coalesce-vars โ€” while transforming your program out of the SSA representation, this attempts to reduce copying by coalescing versions of different user-defined variables, instead of just the compiler's little temporaries. โš ๏ธ Heads up though: this may severely limit your ability to debug an optimized program compiled with -fno-var-tracking-assignments. In its negated form, this flag prevents SSA coalescing of user variables. Enabled by default if optimization is enabled, and it does very little otherwise. Like, barely any vibes when optimization's off.
  • -ftree-loop-if-convert โ€” attempts to transform conditional jumps in the innermost loops into branch-less equivalents. The whole intent is to remove control-flow from the innermost loops so the vectorization pass can handle them better. Enabled by default if vectorization is enabled. ๐Ÿฆ‹
  • -ftree-loop-distribution โ€” performs loop distribution. This 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's also enabled by -fprofile-use and -fauto-profile. โœจ

  • -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's also enabled by -fprofile-use and -fauto-profile. ๐ŸŒˆ

  • -floop-interchange โ€” performs loop interchange outside of graphite. This can improve cache performance on loop nests and allow further loop optimizations, like vectorization, to take place. For example, this 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's also enabled by -fprofile-use and -fauto-profile. ๐Ÿ”ฅ

  • -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 together. Enabled by default at -O3. It's also enabled by -fprofile-use and -fauto-profile. ๐Ÿ’…
  • -ftree-loop-im โ€” performs loop invariant motion on trees. This pass only moves invariants that are hard to handle at the RTL level โ€” think function calls, operations that expand into nontrivial sequences of insns. With -funswitch-loops it also moves operands of conditions that are invariant out of the loop, so we can get away with just trivial invariantness analysis in loop unswitching. The pass also includes store motion. Moving things around, as one does. ๐Ÿงš
  • -ftree-loop-ivcanon โ€” creates a canonical counter for the number of iterations in loops where figuring out that number requires complicated analysis. Later optimizations can then determine the number easily. Super useful especially in connection with unrolling. โœจ
  • -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, then uses of the final value get replaced by that computation โ€” provided it's sufficiently cheap. This reduces data dependencies and may allow further simplifications. Enabled by default at -O and higher. ๐ŸŒธ
  • -fivopts โ€” performs induction variable optimizations (strength reduction, induction variable merging and induction variable elimination) on trees. Say that five times fast, bestie. ๐Ÿ˜ญ
  • *-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, and only for loops that are CPU-intensive rather than constrained by, like, memory bandwidth. This option implies -pthread, so it's only supported on targets that have support for -pthread. ๐Ÿซถ
  • -ftree-pta โ€” performs function-local points-to analysis on trees. Enabled by default at -O1 and higher, except for -Og. ๐Ÿ‘‘
  • -ftree-sra โ€” performs scalar replacement of aggregates. This pass replaces structure references with scalars to prevent committing structures to memory too early. Enabled by default at -O1 and higher, except for -Og. ๐Ÿ’œ
  • -fstore-merging โ€” performs merging of narrow stores to consecutive memory addresses. This pass merges contiguous stores of immediate values narrower than a word into fewer wider stores to reduce the number of instructions. Enabled by default at -O2 and higher as well as -Os. Fewer instructions, same energy. ๐Ÿ’…
  • -ftree-ter โ€” performs temporary expression replacement during the SSA->normal phase. Single use/single def temporaries are replaced at their use location with their defining expression. This results in non-GIMPLE code, but it gives the expanders much more complex trees to work on, which results in better RTL generation. Enabled by default at -O and higher. It's giving "messy on purpose, gorgeous in practice." ๐ŸŽ€
  • -ftree-slsr โ€” performs straight-line strength reduction on trees. It recognizes related expressions involving multiplications and replaces them with less expensive calculations when possible. Enabled by default at -O and higher. ๐ŸŒŸ
  • -ftree-vectorize โ€” performs vectorization on trees. This flag enables -ftree-loop-vectorize and -ftree-slp-vectorize if they're not explicitly specified. โœจ
  • -ftree-loop-vectorize โ€” performs loop vectorization on trees. Enabled by default at -O3 and by -ftree-vectorize, -fprofile-use, and -fauto-profile. ๐Ÿ”ฅ
  • -ftree-slp-vectorize โ€” performs basic block vectorization on trees. Enabled by default at -O3 and by -ftree-vectorize, -fprofile-use, and -fauto-profile. ๐Ÿฆ‹
  • *-fvect-cost-model=model* โ€” alters the cost model used for vectorization. The model argument should be one of unlimited, dynamic, cheap or very-cheap.
    • With the unlimited model, the vectorized code-path is assumed to be profitable. ๐Ÿ’ธ
    • With the dynamic model, a runtime check guards the vectorized code-path so it only gets enabled for iteration counts that will likely execute faster than running the original scalar loop.
    • The cheap model disables vectorization of loops where doing so would be cost prohibitive โ€” for example due to required runtime checks for data dependence or alignment โ€” but otherwise it's equal to the dynamic model.
    • The very-cheap model only allows vectorization if the vector code would entirely replace the scalar code that is being vectorized. For example, if each iteration of a vectorized loop would only be able to handle exactly four iterations of the scalar loop, the very-cheap model 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. No cap. ๐Ÿ’…

  • *-fsimd-cost-model=model* โ€” alters the cost model used for vectorization of loops marked with the OpenMP simd directive. The model argument should be one of unlimited, dynamic, cheap. All values of model have the same meaning as described in -fvect-cost-model, and by default a cost model defined with -fvect-cost-model is used. ๐ŸŒˆ
  • -ftree-vrp โ€” this one runs Value Range Propagation on trees, bestie ๐Ÿ’–. It's lowkey cousins with the constant propagation pass, except instead of propagating values it propagates ranges of values, which is honestly so much more slay. The payoff? The optimizers get to yeet unnecessary range checks like array bound checks and null pointer checks ๐Ÿ—‘๏ธโœจ. It's on by default at -O2 and higher. One tiny caveat: null pointer check elimination only happens if -fdelete-null-pointer-checks is enabled, iykyk.
  • -fsplit-paths โ€” splits paths that lead to loop backedges ๐Ÿฆ‹. This can level up dead code elimination and common subexpression elimination. Enabled by default at -O3 and above, no cap.
  • -fsplit-ivs-in-unroller โ€” ok so this lets values of induction variables in later iterations of the unrolled loop be expressed using the value in the first iteration ๐ŸŒธ. The whole point is it breaks long dependency chains, which makes the scheduling passes way more efficient. Chef's kiss.

A combo of -fweb and CSE is often enough to get the same effect, but ngl that's not reliable when the loop body is more complicated than a single basic block ๐Ÿ˜ญ. It also doesn't work at all on some architectures because of restrictions in the CSE pass. Tragic.

This optimization is enabled by default.

  • -fvariable-expansion-in-unroller โ€” with this on, the compiler makes multiple copies of some local variables while unrolling a loop, which can give you superior code ๐Ÿ‘‘. This optimization is enabled by default for PowerPC targets, but disabled by default everywhere else.
  • -fpartial-inlining โ€” inlines parts of functions, not the whole thing โœจ. Heads up though: this option only does anything when inlining itself is turned on by the -finline-functions or -finline-small-functions options. Enabled at levels -O2, -O3, -Os.
  • -fpredictive-commoning โ€” performs the predictive commoning optimization, which is just a fancy way of saying it reuses computations (especially memory loads and stores) that were performed in previous iterations of loops ๐Ÿ”๐Ÿ’…. This option is enabled at level -O3. It's also enabled by -fprofile-use and -fauto-profile.
  • -fprefetch-loop-arrays โ€” if the target machine supports it, generate instructions to prefetch memory so loops that access large arrays go faster ๐Ÿš€. Real talk though: this option may generate better or worse code โ€” results are highly dependent on the structure of the loops in your source. Disabled at level -Os.
  • -fno-printf-return-value โ€” do not substitute constants for the known return value of formatted output functions such as sprintf, snprintf, vsprintf, and vsnprintf (but not printf of fprintf) ๐Ÿ™ˆ. This transformation lets GCC optimize or even fully eliminate branches based on the known return value of those functions when they're 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 snprint) 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 all in how they're implemented inside the compiler; some targets use one, some use the other, and a few chaotic ones 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, periodt โœ‹.

GCC uses heuristics to guess branch probabilities when 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 that __builtin_expect info into account. The interactions between the heuristics and __builtin_expect can get genuinely complex, and in some cases it's actually useful to disable the heuristics so the effects of __builtin_expect are easier to understand ๐Ÿ‘€.

It's also possible to 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 โ€” reorder basic blocks in the compiled function so there are fewer taken branches and better code locality ๐ŸŒˆ. Enabled at levels -O, -O2, -O3, -Os.
  • -freorder-blocks-algorithm=algorithm โ€” pick which algorithm does the basic block reordering ๐Ÿ’…. The algorithm argument can be simple, which does not 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 -O, -Os, and stc at levels -O2, -O3.
  • -freorder-blocks-and-partition โ€” on top of reordering basic blocks in the compiled function to reduce the number of taken branches, this one partitions hot and cold basic blocks into separate sections of the assembly and .o files, to improve paging and cache locality performance ๐Ÿ”ฅ.

This optimization is automatically turned off in the presence of exception handling or unwind tables (on targets using setjump/longjump or target specific scheme), for linkonce sections, for functions with a user-defined section attribute, and on any architecture that does not support named sections. When -fsplit-stack is used, this option is not enabled by default (to avoid linker errors), but it may be enabled explicitly (if using a working linker) ๐Ÿงš.

Enabled for x86 at levels -O2, -O3, -Os.

  • -freorder-functions โ€” reorder functions in the object file to improve code locality โœจ. It's implemented by using special subsections .text.hot for the most frequently executed functions and .text.unlikely for unlikely executed functions. Reordering is done by the linker, so the object file format must support named sections and the linker must place them in a reasonable way.

Heads up bestie: this option isn't effective unless you either provide profile feedback (see -fprofile-arcs for details) or manually annotate functions with hot or cold attributes ๐Ÿ’–.

Enabled at levels -O2, -O3, -Os.

  • -fstrict-aliasing โ€” allow the compiler to assume the strictest aliasing rules applicable to the language being compiled ๐Ÿ‘‘. For C (and C++), this activates optimizations based on the type of expressions. In particular, an object of one type is assumed never to reside at the same address as an object of a different type, unless the types are almost the same. For example, an unsigned int can alias an int, but not a void* or a double. A character type may alias any other type.

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. 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.

  • -falign-functions
  • -falign-functions=n
  • -falign-functions=n:m
  • -falign-functions=n:m:n2
  • -falign-functions=n:m:n2:m2 โ€” align the start of functions to the next power-of-two greater than or equal to n, skipping up to m-1 bytes ๐ŸŒธ. This ensures that 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 vibes need numbers: -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, and -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 is rounded up. -fno-align-functions and -falign-functions=1 are equivalent and mean that functions 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.

  • -flimit-function-alignment โ€” with this 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.
  • -falign-labels
  • -falign-labels=n
  • -falign-labels=n:m
  • -falign-labels=n:m:n2
  • -falign-labels=n:m:n2:m2 โ€” align all branch targets to a power-of-two boundary.
  • -falign-labels, -falign-labels=n, -falign-labels=n:m, -falign-labels=n:m:n2, -falign-labels=n:m:n2:m2 โ€” Align all branch targets to a power-of-two boundary, bestie, and the parameters work exactly like the -falign-functions ones (go look up above, iykyk). Fun fact: -fno-align-labels and -falign-labels=1 are literally the same thing โ€” both mean labels get zero alignment, periodt.

But wait, there's a vibe check: if -falign-loops or -falign-jumps apply and their values are bigger than this one, then their values win. Theirs. Not yours. ๐Ÿ’…

And if n isn't specified or is 0? Then we use a machine-dependent default which is very likely to be 1, aka no alignment at all. The biggest n you're allowed to pass is 65536.

Turned on at levels -O2, -O3. โœจ

  • -falign-loops, -falign-loops=n, -falign-loops=n:m, -falign-loops=n:m:n2, -falign-loops=n:m:n2:m2 โ€” Align loops to a power-of-two boundary. ๐ŸŒ€ If those loops get executed a whole bunch of times, that pays you back for any execution of the dummy padding instructions, so it's giving investment.

If -falign-labels is greater than this value, then its value is used instead. (Yeah, labels can steal the spotlight here. ๐Ÿ™ˆ)

The parameters are analogous to the -falign-functions option. -fno-align-loops and -falign-loops=1 are equivalent, and they both mean 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 โ€” Align branch targets to a power-of-two boundary โ€” specifically for branch targets where the only way to reach them is by jumping. ๐Ÿฆ˜ And the slay here is that in this case, no dummy operations need be executed at all. Zero waste, we love to see it.

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 during dead code elimination. That allocation stays. It lives there now. ๐Ÿ 
  • -fallow-store-data-races โ€” Okay so this one lets the compiler do optimizations that may introduce new data races on stores, without proving the variable can't be concurrently accessed by other threads. It does not affect optimization of local data. And it's safe to use if you know global data won't be accessed by multiple threads. ๐Ÿงต

Examples of optimizations this turns on 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. Heads up: 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. It's a legacy icon that just vibes in the corner. ๐Ÿ‘‘

Enabled by default.

  • -fno-toplevel-reorder โ€” Do not reorder top-level functions, variables, and asm statements. Output them in the same order that 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 is 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 its own individual pseudo register. This lets the register allocation pass operate on pseudos directly, but it also strengthens several other optimization passes, like CSE, the loop optimizer, and the trivial dead code remover. ๐Ÿ’ช
But it can make debugging impossible, since variables no longer stay in a "home register". ๐Ÿ˜ญ So like, pick your fighter.

Enabled by default with -funroll-loops.

  • -fwhole-program โ€” Assume 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 way more aggressively by interprocedural optimizers. ๐Ÿ”ฅ
This option should not be used in combination with -flto. Instead, relying on a linker plugin should provide safer and more precise information. Bestie, please. ๐Ÿซถ
  • -flto[=n] โ€” THE big one. 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 are 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 "we were always one file, actually". โœจ

To use the link-time optimizer, -flto and optimization options should be specified at compile time and during the final link. It is recommended that you compile all the files participating in the same link with the same options and also specify those options at link time. For example:

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. The final invocation reads the GIMPLE bytecode from foo.o and bar.o, merges the two files into a single internal image, and compiles the result as usual. Since both foo.o and bar.o are merged into a single image, this causes all the interprocedural analyses and optimizations in GCC to work across the two files as if they were a single one. Which means, for example, that the inliner is able to 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

The above 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. So flexible, we stan. ๐Ÿฆ‹

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. So do both. Both is the move. ๐Ÿ’…

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. No negotiating, bestie. ๐Ÿšซ

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. ๐ŸŽ€

...and like, diagnostic options such as -Wstringop-overflow get passed through to the link stage too, and their setting matches whatever the compile-step was set to, at function granularity. ๐Ÿ’… Heads up though: this only matters for diagnostics that get emitted during optimization. And also, code transforms like inlining can literally lead to warnings being turned on or off for regions of code that aren't consistent with the setting at compile time. ๐Ÿ™ˆ so wild.

When you need to pass options to the assembler via -Wa or -Xassembler, bestie, please make sure to either compile those 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, slay. โœจ

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. ๐Ÿซถ But 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. ๐Ÿ˜ญ don't do it.

If LTO encounters objects with C linkage declared with incompatible types in separate translation units to be linked together (which is undefined behavior according to ISO C99 6.2.7), a non-fatal diagnostic may be issued. The behavior is still undefined at run time though โ€” the diagnostic is just a heads up. Similar diagnostics may be raised for other languages.

Another feature of LTO is that it's 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's possible to extract and use them in an LTO link if you're 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's 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 the 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. ๐Ÿ’€ fr fr, keep your versions matched.

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 โ€” picks the partitioning algorithm the link-time optimizer uses. The value is either 1to1 to specify a partitioning mirroring the original source files, or balanced to specify partitioning into equally sized chunks (whenever possible), or max to create a new partition for every symbol where possible. Specifying none as an algorithm disables partitioning and streaming completely. The default value is balanced. While 1to1 can be used as a workaround for various code ordering issues, the max partitioning is intended for internal testing only. The value one specifies that exactly one partition should be used, while the value none bypasses partitioning and executes the link-time optimization step directly from the WPA phase. ๐ŸŽ€
  • -flto-compression-level=n โ€” sets the level of compression used for intermediate language written to LTO object files, and is 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 the option is not given, a default balanced compression setting is used. โœจ
  • -fuse-linker-plugin โ€” enables the use of a linker plugin during link-time optimization. This option relies on plugin support in the linker, which is available in gold or in GNU ld 2.21 or newer. ๐Ÿ‘‘

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. This 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 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 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.

  • -fcompare-elim โ€” after register allocation and post-register allocation instruction splitting, identify arithmetic instructions that compute processor flags similar to a comparison operation based on that arithmetic. If possible, eliminate 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 -O, -O2, -O3, -Os. โญ

  • -fcprop-registers โ€” after register allocation and post-register allocation instruction splitting, perform a copy-propagation pass to try to reduce scheduling dependencies and occasionally eliminate the copy. ๐Ÿ’…

Enabled at levels -O, -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. ๐Ÿ˜ญ

This option is enabled by -fauto-profile.

  • -fprofile-partial-training โ€” with -fprofile-use all portions of programs not executed during train run are optimized agressively for size rather than speed. In some cases it is not practical to train all possible hot paths in the program. (For example, program may contain functions specific for a given hardware and trianing may not cover all hardware configurations 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 train run is not representative but also leads to significantly bigger code. ๐Ÿฆ‹
  • -fprofile-use
  • -fprofile-use=path โ€” enable profile feedback-directed optimizations, and the following optimizations, many of which are generally profitable only with profile feedback available: ๐Ÿ‘‘

and the option parade keeps going, bestie โ€” hold onto your iced coffee ๐Ÿซถ

-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

Okay so before you can use this option, you have to generate profiling information first. Like, actually run your program and collect the receipts. No receipts, no vibes-based optimization, bestie ๐Ÿ’…

By default, GCC throws an error message if the feedback profiles don't match the source code. Like, it notices and it says something. You can downgrade that whole situation into a warning by using -Wno-error=coverage-mismatch. โš ๏ธ But heads up: this may result in poorly optimized code. Also by default, GCC drops a warning message if the feedback profiles don't exist at all (peep -Wmissing-profile). So it's gonna tell you either way, fr fr.

If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir. ๐Ÿ—‚๏ธ


-fauto-profile & -fauto-profile=path

Turn on sampling-based feedback-directed optimizations, plus this whole stack of optimizations below โ€” many of which are genuinely only worth it when you've got profile feedback to work with:

-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 you just... don't give it one, it defaults to fbdata.afdo in the current directory. Defaults really said "I got you" ๐Ÿซถ

To actually produce an AutoFDO profile data file you have to run your program with the perf utility on a supported GNU/Linux target system. Want the tea? See <https://perf.wiki.kernel.org/>. โœจ

For example:

perf record -e br_inst_retired:near_taken -b -o perf.data \
    -- your_program

Then you use the create_gcov tool to convert that raw profile data into a format GCC can actually read. You also have to hand this tool the unstripped binary for your program โ€” yes, the one with all its debug info still attached, no skimping. See <https://github.com/google/autofdo>.

For example:

create_gcov --binary=your_program.unstripped --profile=perf.data \
    --gcov=profile.afdo

floating-point era โœจ (the speed vs. correctness trade-off)

The following options control compiler behavior regarding floating-point arithmetic. These options trade off between speed and correctness. All must be specifically enabled โ€” they do NOT just turn themselves on, okay? You have to ask. ๐Ÿ™ˆ

  • -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. Same deal 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, do the homework first ๐Ÿ’€

  • *-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. ๐Ÿ˜ญ

  • -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 like... know what you're signing up for, bestie.

  • -fno-math-errno โ€” Do not set "errno" after calling math functions that are executed with a single instruction, e.g., "sqrt". A program that relies on IEEE exceptions for math error handling may want to use this flag for speed while maintaining IEEE arithmetic compatibility.

This option is 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 do not require the guarantees of these specifications.

The default is -fmath-errno.

On Darwin systems, the math library never sets "errno". There is therefore no reason for the compiler to consider the possibility that it might, and -fno-math-errno is the default. ๐Ÿ“

  • -funsafe-math-optimizations โ€” Allow optimizations for floating-point arithmetic that (a) assume that 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.

This option is 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 do not require the guarantees of these specifications. Enables -fno-signed-zeros, -fno-trapping-math, -fassociative-math and -freciprocal-math.

The default is -fno-unsafe-math-optimizations.

  • -fassociative-math โ€” Allow 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 that arguments and results are not NaNs or +-Infs.

This option is 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 do not require the guarantees of these 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, never never. ๐Ÿ˜ค

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". ๐Ÿ”ฎ

okay keep scrolling, there's SO much more and we are not even close to done ๐Ÿฆ‹

  • -fsignaling-nans โ€” okay so this one tells the compiler to just assume that IEEE signaling NaNs might throw user-visible traps while floating-point ops are happening. Turning it on kills off any optimizations that could change how many exceptions you'd see with signaling NaNs. It also implies -ftrapping-math. โœจ

It makes the preprocessor macro __SUPPORT_SNAN__ get defined.

Default is -fno-signaling-nans.

Bestie, this one is experimental โ€” right now it does not guarantee that it disables every single GCC optimization that messes with signaling NaN behavior. No cap. ๐Ÿ’€
  • -fno-fp-int-builtin-inexact โ€” this says don't let the built-in functions ceil, floor, round and trunc (plus their float and long double variants) generate code that raises the inexact floating-point exception for noninteger arguments. ISO C99 and C11 actually allow those functions to raise inexact, but ISO/IEC TS 18661-1:2014 โ€” the C bindings to IEEE 754-2008, as integrated into ISO C2X โ€” does not allow it. ๐ŸŽ€

Default is -ffp-int-builtin-inexact, which lets the exception be raised, unless C2X or a later C standard is selected. This option does nothing unless -ftrapping-math is in effect.

Even if you use -fno-fp-int-builtin-inexact, if those functions generate a call to a library function then the inexact exception may still be raised if the library implementation doesn't follow TS 18661.

  • -fsingle-precision-constant โ€” treats floating-point constants as single precision instead of quietly converting them into double-precision constants. ๐Ÿ’…
  • -fcx-limited-range โ€” when it's on, this option is basically declaring that you don't need a range reduction step when doing complex division. Also, 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. Default is -fno-cx-limited-range, but it gets 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. ๐Ÿฆ‹

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. ๐Ÿ™ˆ


  • -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 how many 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 info in that 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. ๐Ÿ”ฅ

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.c, 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 gets 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 the 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 tells 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 โ€” attempts 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, though, it can make debugging impossible, since variables no longer stay in a "home register". ๐Ÿ˜ญ

Enabled by default with -funroll-loops.

  • -fschedule-fusion โ€” performs a target dependent pass over the instruction stream to schedule instructions of the same type together, because the target machine can execute them more efficiently if they're adjacent to each other in the instruction flow. โšก

Enabled at levels -O2, -O3, -Os.

  • -ftracer โ€” performs tail duplication to enlarge superblock size. This transformation simplifies the control flow of the function, letting other optimizations do a better job.

Enabled by -fprofile-use and -fauto-profile.

  • -funroll-loops โ€” unrolls loops whose number of iterations can be determined at compile time or upon entry to the loop. -funroll-loops implies -frerun-cse-after-loop, -fweb and -frename-registers. It also turns on complete loop peeling (i.e. complete removal of loops with a small constant number of iterations). Heads up: this option makes code larger, and it may or may not make it run faster. ๐ŸŒ€

Enabled by -fprofile-use and -fauto-profile.

  • -funroll-all-loops โ€” unrolls all loops, even if their number of iterations is uncertain when the loop is entered. This usually makes programs run more slowly. -funroll-all-loops implies the same options as -funroll-loops. ๐Ÿ’€
  • -fpeel-loops โ€” peels loops for which there's enough information that they don't roll much (from profile feedback or static analysis). It also turns on complete loop peeling (i.e. 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.
  • -fsplit-loops โ€” splits a loop into two if it contains a condition that's always true for one side of the iteration space and false for the other. โœ‚๏ธ

Enabled by -fprofile-use and -fauto-profile.

  • -funswitch-loops โ€” moves branches with loop invariant conditions out of the loop, with duplicates of the loop on both branches (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, creates another version of the loop that assumes the stride is always one. Like, for example:
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 particularly useful for assumed-shape arrays in Fortran where (for example) it allows better vectorization 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 โ€” place 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 name of the data item determines the section's name in the output file. ๐ŸŽ€

Use these options on systems where the linker can perform optimizations to improve locality of reference in the instruction space. Most systems using the ELF object format have linkers with such optimizations. On AIX, the linker rearranges sections (CSECTs) based on the call graph. The performance impact varies.

Together with a linker garbage collection (linker --gc-sections option) these options may lead to smaller statically-linked executables (after stripping).

On ELF/DWARF systems these options do not degenerate 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 these options, 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 using relative locations inside a translation unit since the locations are unknown until link time. An example of such an optimization is relaxing calls to short call instructions. โš ๏ธ
  • -fstdarg-opt โ€” optimizes the prologue of variadic argument functions with respect to usage of those arguments. โœจ
NOTE: In Ubuntu 14.10 and later versions, -fstack-protector-strong is enabled by default for C, C++, ObjC, ObjC++, if none of -fno-stack-protector, -nostdlib, nor -ffreestanding are found. ๐Ÿ’œ
  • -fsection-anchors โ€” tries to reduce 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 the following 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 the following pseudocode (which isn't valid C):

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 out the call-used registers when a function returns, and it's giving โœจsecurity eraโœจ. Two glow-ups in one: it either mitigates Return-Oriented Programming (ROP) attacks or stops info from leaking out through registers. The possible values of choice are exactly the same ones as for the "zero_call_used_regs" attribute. The default is skip. And bestie, if you wanna control this for just one specific function instead of the whole vibe, use the function attribute "zero_call_used_regs". ๐Ÿซถ
  • --param name=value โ€” okay so here's the tea โ˜•: in some places GCC uses a bunch of random constants to control how much optimization happens. Example: GCC won't inline functions that contain more than a certain number of instructions. And you can tweak some of those constants straight from the command line with this option. The names of the specific parameters and what their values even mean are tied to the compiler's internals, and they are subject to change without notice in future releases โ€” so lowkey don't build your whole personality on them. ๐Ÿ˜ญ

Wanna know the minimal, maximal and default value of a parameter? Hit it with --help=param -Q. Iconic.

In each case the value is an integer, and the following choices of name are recognized for all targets:

  • predictable-branch-outcome โ€” if 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 yeet conditional branches around a block and replace them with conditionally executed instructions. This parameter is the max number of instructions in a block that even gets considered for if-conversion. The compiler also uses other heuristics to decide whether if-conversion is likely to be profitable, no cap.
  • max-rtl-if-conversion-predictable-cost โ€” RTL if-conversion will try to remove conditional branches around a block and swap in 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. Units for this parameter are the same as for the GCC internal seq_cost metric. The compiler will try to provide a reasonable default using the BRANCH_COST target macro. โœจ
  • max-crossjump-edges โ€” the maximum number of incoming edges to consider for cross-jumping. The algorithm used by -fcrossjumping is O(N^2) in the number of edges incoming to each block. Bigger values = more aggressive optimization = compilation time goes up with probably only a tiny improvement in executable size. it's giving diminishing returns ๐Ÿ’…
  • min-crossjump-insns โ€” the minimum number of instructions that have to match at the end of two blocks before cross-jumping them is even attempted. This value gets ignored when all the 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 maximum number of instructions to duplicate into 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 maximum number of instructions to consider while 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 just stop searching. Bigger values = more aggressive optimization = compilation time up, probably tiny improvement in execution time. ๐ŸŒ
  • max-delay-slot-live-search โ€” when trying to fill delay slots, the max number of instructions to consider while searching for a block with valid live register info. Bumping this arbitrarily chosen value = more aggressive optimization = more compilation time. This parameter should be removed once the delay slot code gets rewritten to maintain the control-flow graph. (rip to it fr)
  • max-gcse-memory โ€” the approximate max amount of memory in "kB" that can be allocated to do the global common subexpression elimination optimization. If it needs more memory than specified, the optimization justโ€ฆ doesn't happen. ๐Ÿ’€
  • 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 sitting in the instruction stream.
  • max-pending-list-length โ€” the max 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 that needlessly eat memory and resources. ๐Ÿ™ˆ
  • max-modulo-backtrack-attempts โ€” the max number of backtrack attempts the scheduler should make when modulo scheduling a loop. Larger values can make compilation time go up exponentially. bestie that's not a vibe, that's a threat ๐Ÿšจ
  • max-inline-insns-single โ€” several parameters control the tree inliner used in GCC. This number sets the max 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++).
  • max-inline-insns-auto โ€” when you use -finline-functions (which is included in -O3), a whole lot of functions that would otherwise never be considered for inlining by the compiler get investigated. To those functions, a different (more restrictive) limit compared to functions declared inline can be applied (--param max-inline-insns-auto).
  • max-inline-insns-small โ€” this is the bound applied to calls which are considered relevant with -finline-small-functions.
  • max-inline-insns-size โ€” this is the bound applied to calls which are optimized for size. A little growth may be desirable to anticipate optimization oppurtunities exposed by inlining.
  • uninlined-function-insns โ€” number of instructions accounted by the inliner for function overhead, like the function prologue and epilogue.
  • uninlined-function-time โ€” extra time accounted by the inliner for function overhead, like the time needed to execute the function prologue and epilogue.
  • inline-heuristics-hint-percent โ€” the scale (in percents) applied to inline-insns-single, inline-insns-single-O2, inline-insns-auto when the inline heuristics hint that inlining is very profitable (i.e. it'll enable later optimizations). ๐Ÿ‘‘
  • uninlined-thunk-insns, uninlined-thunk-time โ€” same as --param uninlined-function-insns and --param uninlined-function-time, but applied to function thunks.
  • inline-min-speedup โ€” when the 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. slay ๐Ÿ’…
  • large-function-insns โ€” the limit specifying really large functions. For functions larger than this limit after inlining, inlining gets 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. ๐Ÿ˜ญ
  • large-function-growth โ€” specifies maximal growth of a large function caused by inlining, in percents. For example, parameter value 100 limits large function growth to 2.0 times the original size.
  • large-unit-insns โ€” the limit specifying a 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 the 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. ๐Ÿงš
  • lazy-modules โ€” maximum number of concurrently open C++ module files when lazy loading.
  • 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. ๐Ÿฅถ
  • 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-large-unit-insns โ€” the size of translation unit that the IPA-CP pass considers large.
  • large-stack-frame โ€” the limit specifying large stack frames. While inlining, the algorithm is trying not to grow past this limit too much.
  • 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. ๐Ÿซ 
  • 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.

okay bestie we're STILL in the --param zone and honestly? we live here now ๐Ÿ’… quick lil callback to the entry that started this whole thing:

--param max-inline-insns-recursive applies to functions declared inline. For functions that are not declared inline, recursive inlining happens only when -finline-functions (which is included in -O3) is enabled; --param max-inline-insns-recursive-auto applies instead. two params, two vibes, one recursion party ๐ŸŽ‰


  • --param max-inline-recursive-depth, --param max-inline-recursive-depth-auto โ€” sets the maximum recursion depth used for recursive inlining. Same split as above: --param max-inline-recursive-depth applies to functions declared inline, and for functions that are not declared inline, recursive inlining only happens when -finline-functions (included in -O3) is enabled, in which case --param max-inline-recursive-depth-auto applies instead. ๐ŸŒ€
  • --param min-inline-recursive-probability โ€” lowkey a whole philosophy moment: recursive inlining is only profitable for functions with deep recursion on average, and it can hurt functions with little recursion depth by increasing the prologue size or the complexity of the function body for other optimizers. ๐Ÿ˜ญ When profile feedback is available (peep -fprofile-generate), the actual recursion depth can be guessed from the probability that the function recurses via a given call expression. This parameter limits inlining only to call expressions whose probability exceeds the given threshold (in percents). math girlies rise ๐Ÿ“Š
  • --param early-inlining-insns โ€” specifies the growth the early inliner can make. In effect it increases the amount of inlining for code that has a large abstraction penalty. the early bird gets the inline โœจ
  • --param max-early-inliner-iterations โ€” the iteration limit 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 says "not my problem, ask late inlining" ๐Ÿ™ˆ
  • --param comdat-sharing-probability โ€” the probability (in percent) that a C++ inline function with comdat visibility gets shared across multiple compilation units. ๐Ÿค
  • --param modref-max-bases, --param modref-max-refs, --param modref-max-accesses โ€” the maximal number of base pointers, references and accesses stored for a single function by mod/ref analysis. three params, one storage closet ๐Ÿ—„๏ธ
  • --param modref-max-tests โ€” the maximum number of tests the 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. it's giving "please be bigger than your friends" energy ๐Ÿ‘‘
  • --param modref-max-depth โ€” the maximum depth of the DFS walk used by modref escape analysis. Setting it to 0 disables the analysis completely. zero means GONE, no cap ๐Ÿ’€
  • --param modref-max-escape-points โ€” the maximum number of escape points tracked by modref per SSA-name. ๐Ÿƒโ€โ™€๏ธ๐Ÿ’จ
  • --param profile-func-internal-id โ€” a parameter to control whether to use the function internal id in profile database lookup. If the value is 0, the compiler uses an id based on the function assembler name and filename, which makes old profile data more tolerant to source changes such as function reordering etc. grandma profile data stays valid, we love to see it ๐Ÿซถ
  • --param 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. gotta clear the bar to get the glow-up ๐ŸŒˆ
  • --param gcse-cost-distance-ratio โ€” the scaling factor in the calculation of the 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 a cost less than gcse-unrestricted-cost. Specifying 0 disables hoisting of simple expressions. ๐Ÿ”ฅ
  • --param gcse-unrestricted-cost โ€” the cost, roughly measured as the cost of a single typical machine instruction, at which GCSE optimizations do not constrain the distance an expression can travel. This is currently supported only in the code hoisting pass. The lesser the cost, the more aggressive code hoisting is. Specifying 0 allows all expressions to travel unrestricted distances. free-range expressions, roaming the countryside ๐Ÿฆ‹
  • --param max-hoist-depth โ€” the depth of search in the dominator tree for expressions to hoist. This is used to avoid quadratic behavior in the hoisting algorithm. A value of 0 does not limit the search, but may slow down compilation of huge functions. no limit = no chill on your compile times bestie โณ
  • --param max-tail-merge-comparisons โ€” the maximum amount of similar bbs to compare a bb with. This is used to avoid quadratic behavior in tree tail merging. ๐Ÿงฌ
  • --param max-tail-merge-iterations โ€” the maximum amount of iterations of the pass over the function. This is used to limit compilation time in tree tail merging. โฑ๏ธ
  • --param store-merging-allow-unaligned โ€” allow the store merging pass to introduce unaligned stores if it is legal to do so. chaotic but legal, we stan ๐Ÿ’…
  • --param max-stores-to-merge โ€” the maximum number of stores to attempt to merge into wider stores in the store merging pass. ๐Ÿ“ฆ๐Ÿ“ฆโžก๏ธ๐Ÿ“ฆ
  • --param max-store-chains-to-track โ€” the maximum number of store chains to track at the same time in the attempt to merge them into wider stores in the store merging pass. ๐Ÿ”—
  • --param max-stores-to-track โ€” the maximum number of stores to track at the same time in the attempt to merge them into wider stores in the store merging pass. yes it's basically the sibling of the last one, no I will not be merging them, the manpage said what it said ๐Ÿ™…โ€โ™€๏ธ
  • --param max-unrolled-insns โ€” the maximum number of instructions a loop may have to be unrolled. If a loop is unrolled, this parameter also determines how many times the loop code is unrolled. ๐ŸŽข
  • --param max-average-unrolled-insns โ€” the maximum number of instructions biased by probabilities of their execution that a loop may have to be unrolled. If a loop is unrolled, this parameter also determines how many times the loop code is unrolled. probability-weighted, because of course it is โœจ
  • --param max-unroll-times โ€” the maximum number of unrollings of a single loop. ๐Ÿ”
  • --param max-peeled-insns โ€” the maximum number of instructions a loop may have to be peeled. If a loop is peeled, this parameter also determines how many times the loop code is peeled. ๐ŸŒ get it? peeled? I'll see myself out
  • --param max-peel-times โ€” the maximum number of peelings of a single loop. ๐ŸŒ๐ŸŒ
  • --param max-peel-branches โ€” the maximum number of branches on the hot path through the peeled sequence. ๐ŸŒถ๏ธ
  • --param max-completely-peeled-insns โ€” the maximum number of insns of a completely peeled loop. ๐ŸŒโœจ
  • --param max-completely-peel-times โ€” the maximum number of iterations of a loop to be suitable for complete peeling. ๐Ÿ”„
  • --param max-completely-peel-loop-nest-depth โ€” the maximum depth of a loop nest suitable for complete peeling. ๐Ÿช†
  • --param max-unswitch-insns โ€” the maximum number of insns of an unswitched loop. ๐Ÿ”€
  • --param max-unswitch-level โ€” the maximum number of branches unswitched in a single loop. ๐ŸŒฟ
  • --param lim-expensive โ€” the minimum cost of an expensive expression in the loop invariant motion. ๐Ÿ’ธ
  • --param min-loop-cond-split-prob โ€” when FDO profile information is available, min-loop-cond-split-prob specifies the minimum threshold for probability of a semi-invariant condition statement to trigger loop split. thresholds, but make it FDO ๐Ÿ“ˆ
  • --param iv-consider-all-candidates-bound โ€” a bound on the number of candidates for induction variables, below which all candidates are considered for each use in induction variable optimizations. If there are more candidates than this, only the most relevant ones are considered, to avoid quadratic time complexity. ๐Ÿ‘€
  • --param iv-max-considered-uses โ€” the induction variable optimizations give up on loops that contain more induction variable uses. it's giving "I'm tired, I'm going home" ๐Ÿ˜ญ
  • --param 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 when adding a new one. โœ‚๏ธ
  • --param avg-loop-niter โ€” the average number of iterations of a loop. ๐Ÿ”‚
  • --param dse-max-object-size โ€” the maximum size (in bytes) of objects tracked bytewise by dead store elimination. Larger values may result in larger compilation times. โณ
  • --param dse-max-alias-queries-per-store โ€” the maximum number of queries into the alias oracle per store. Larger values result in larger compilation times and may result in more removed dead stores. trade-off queen ๐Ÿ’…
  • --param scev-max-expr-size โ€” a bound on the size of expressions used in the scalar evolutions analyzer. Large expressions slow the analyzer. ๐ŸŒ
  • --param scev-max-expr-complexity โ€” a bound on the complexity of the expressions in the scalar evolutions analyzer. Complex expressions slow the analyzer. ๐ŸŒ€
  • --param max-tree-if-conversion-phi-args โ€” the maximum number of arguments in a PHI supported by TREE if conversion, unless the loop is marked with the simd pragma. ๐ŸŒณ
  • --param vect-max-version-for-alignment-checks โ€” the maximum number of run-time checks that can be performed when doing loop versioning for alignment in the vectorizer. ๐Ÿ“
  • --param vect-max-version-for-alias-checks โ€” the maximum number of run-time checks that can be performed when doing loop versioning for alias in the vectorizer. ๐Ÿ•ต๏ธโ€โ™€๏ธ
  • --param vect-max-peeling-for-alignment โ€” the maximum number of loop peels to enhance access alignment for the vectorizer. A value of -1 means no limit. minus one = infinite vibes ๐ŸŒˆ
  • --param max-iterations-to-track โ€” the maximum number of iterations of a loop the brute-force algorithm for analysis of the number of iterations of the loop tries to evaluate. ๐Ÿงฎ
  • --param hot-bb-count-fraction โ€” the denominator n of the fraction 1/n of the maximal execution count of a basic block in the entire program that a basic block needs to at least have in order to be considered hot. The default is 10000, which means a basic block is considered 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. the hotness threshold, literally ๐Ÿ”ฅ๐Ÿ‘‘

and that's the tea for this chunk โ€” more --param chaos incoming, don't you dare leave ๐Ÿซถ


okay so we're still deep in the --param zone, bestie, and this next stretch is so compiler-internals coded ๐ŸŽ€ buckle up, the numbers are real and you need every single one of them.

  • hot-bb-count-ws-permille โ€” the number of most-executed permilles (that's a range from 0 to 1000, slay) of the profiled execution of the whole entire program that a basic block's execution count has to be part of for it to count as hot ๐Ÿ”ฅ. default is 990, which literally means a basic block is hot if its count lands in the upper 990 permilles โ€” that's 99.0% โ€” of the profiled execution of the whole program. 0 means it's never considered hot, periodt. used in LTO mode.
  • hot-bb-frequency-fraction โ€” the denominator n of the fraction 1/n of the entry block's execution frequency that a basic block in that function needs to at least have to be considered hot ๐Ÿ’…. default is 1000, so a block is hot if it runs more often than 1/1000 of the entry block's frequency. 0 means never hot, nope.
  • unlikely-bb-count-fraction โ€” the denominator n of the fraction 1/n of the total profiled runs of the program below which a basic block's execution count must fall for it to be flagged unlikely executed ๐Ÿ™ˆ. default is 20, so a block is unlikely executed if it shows up in fewer than 1/20 โ€” that's 5% โ€” of the program's runs. 0 means it's always considered unlikely executed.
  • max-predicted-iterations โ€” the max number of loop iterations we predict statically โœจ. this hits different when a function has one loop with a known bound and another with an unknown bound: the known count gets predicted correctly, while the unknown one averages out to roughly 10. so that unbounded loop looks artificially cold next to the other one ๐Ÿฅถ.
  • builtin-expect-probability โ€” controls the probability of the expression having the specified value. it takes a percentage (like 0 ... 100) as input ๐Ÿ’ฏ.
  • builtin-string-cmp-inline-length โ€” the max length of a constant string for a builtin string cmp call that's eligible for inlining ๐Ÿงš.
  • align-threshold โ€” picks the fraction of the maximal execution frequency of a basic block in a function that gets used to align that basic block ๐Ÿ“.
  • align-loop-iterations โ€” a loop expected to iterate at least the selected number of iterations gets aligned, no cap ๐Ÿ”.
  • tracer-dynamic-coverage, tracer-dynamic-coverage-feedback โ€” this value limits superblock formation once the given percentage of executed instructions is covered, which caps unnecessary code size expansion ๐ŸŽˆ. the tracer-dynamic-coverage-feedback one is used only when profile feedback is available โ€” and fr fr, the real profiles (as opposed to the statically estimated ones) are way less balanced, which lets the threshold go to a larger value.
  • tracer-max-code-growth โ€” stop tail duplication once code growth hits the given percentage ๐Ÿ›‘. it's a pretty artificial limit, since most of those duplicates get eliminated later in cross jumping anyway, so you can set it way higher than the code growth you actually want.
  • tracer-min-branch-ratio โ€” stop reverse growth when the reverse probability of the best edge drops below this threshold (in percent) ๐Ÿ“‰.
  • tracer-min-branch-probability, tracer-min-branch-probability-feedback โ€” stop forward growth if the best edge's probability is lower than this threshold. just like with tracer-dynamic-coverage, there are two of these: tracer-min-branch-probability-feedback is for compiling with profile feedback and tracer-min-branch-probability is for compiling without it. the feedback one needs to be more conservative (higher) to actually make the tracer effective ๐Ÿ‘‘.
  • stack-clash-protection-guard-size โ€” specifies the size of the OS-provided stack guard as 2 raised to num bytes. higher values might cut down the number of explicit probes, but a value larger than the OS-provided guard leaves your code vulnerable to stack clash style attacks ๐Ÿ’€.
  • stack-clash-protection-probe-interval โ€” stack clash protection means probing the stack space as it gets allocated. this param controls the max distance between probes into the stack, as 2 raised to num bytes. again: higher values may reduce explicit probes, but anything larger than the OS-provided guard leaves code vulnerable to stack clash style attacks ๐Ÿšจ.
  • max-cse-path-length โ€” the max number of basic blocks on a path that CSE considers ๐Ÿ›ค๏ธ.
  • max-cse-insns โ€” the max number of instructions CSE processes before it flushes ๐Ÿšฝ.
  • ggc-min-expand โ€” GCC runs a garbage collector to manage its own memory allocation, and this param sets the minimum percentage by which the GC's heap is allowed to expand between collections ๐Ÿ“ˆ. tuning it might 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 can't calculate RAM on a particular platform, the lower bound of 30% is used. setting this parameter and ggc-min-heapsize to zero makes a full collection happen at every opportunity โ€” it's extremely slow, but it can be useful for debugging ๐Ÿ›.

  • ggc-min-heapsize โ€” the minimum size of the GC's heap before it even bothers collecting garbage ๐Ÿ—‘๏ธ. the first collection happens after the heap expands by ggc-min-expand% beyond ggc-min-heapsize. same deal: tuning it may improve compilation speed, and it has no effect on code generation.

the default is the smaller of RAM/8, RLIMIT_RSS, or a limit that tries to make sure RLIMIT_DATA or RLIMIT_AS aren't exceeded โ€” but with a lower bound of 4096 (four megabytes) and an upper bound of 131072 (128 megabytes). if GCC can't 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 makes a full collection occur at every opportunity.

  • max-reload-search-insns โ€” the max number of instructions reload should look backward for an equivalent register ๐Ÿ”Ž. increasing it means more aggressive optimization: compilation time goes up, with probably slightly better performance ๐Ÿ’….
  • max-cselib-memory-locations โ€” the max number of memory locations cselib should take into account. increasing values mean more aggressive optimization, so compilation time increases with probably slightly better performance โœจ.
  • max-sched-ready-insns โ€” the max number of instructions ready to be issued that the scheduler should consider at any given time during the first scheduling pass โฑ๏ธ. increasing values mean more thorough searches, making compilation time go up with probably, like, little benefit ๐Ÿ™ƒ.
  • max-sched-region-blocks โ€” the max number of blocks in a region considered for interblock scheduling ๐Ÿงฉ.
  • max-pipeline-region-blocks โ€” the max number of blocks in a region considered for pipelining in the selective scheduler ๐Ÿšฐ.
  • max-sched-region-insns โ€” the max number of insns in a region considered for interblock scheduling ๐Ÿงฉ.
  • max-pipeline-region-insns โ€” the max number of insns in a region 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 max number of iterations through CFG to extend regions. a value of 0 disables region extensions ๐Ÿšซ.
  • max-sched-insn-conflict-delay โ€” the max 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 get 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 โ€” the minimal distance (in CPU cycles) between a store and a load targeting the same memory locations ๐Ÿ”.
  • selsched-max-lookahead โ€” the max size of the lookahead window of selective scheduling ๐Ÿ‘€. it's the depth of search for available instructions.
  • selsched-max-sched-times โ€” the max number of times an instruction gets scheduled during selective scheduling. this is the limit on how many iterations the instruction may be pipelined through ๐ŸŒ€.
  • selsched-insns-to-rename โ€” the max number of best instructions in the ready list that are considered for renaming in the selective scheduler ๐Ÿท๏ธ.
  • sms-min-sc โ€” the minimum value of the stage count that the swing modulo scheduler generates ๐ŸŽ›๏ธ.
  • max-last-value-rtl โ€” the max size, measured as the number of RTLs, that can be recorded in an expression in the combiner for a pseudo register as the last known value of that register ๐Ÿง .
  • max-combine-insns โ€” the max number of instructions the RTL combiner tries to combine ๐Ÿงฌ.
  • integer-share-limit โ€” small integer constants can share a data structure, which cuts down the compiler's memory usage and boosts its speed โšก. this sets the max value of a shared integer constant.
  • ssp-buffer-size โ€” the minimum size of buffers (like, arrays) that receive stack smashing protection when -fstack-protection is used ๐Ÿ›ก๏ธ.

This default, before Ubuntu 10.10, was "8". Right now it's "4", which bumps up the number of functions protected by the stack protector. ๐Ÿ’–

  • min-size-for-stack-sharing โ€” the minimum size of variables that get to take part in stack slot sharing when we're not optimizing.
  • max-jump-thread-duplication-stmts โ€” the max number of statements allowed in a block that needs to be duplicated when threading jumps. ๐Ÿงต
  • max-fields-for-field-sensitive โ€” the max number of fields in a struct that get treated in a field-sensitive way during pointer analysis.
  • prefetch-latency โ€” estimates, on average, how many instructions get executed before a prefetch finishes. The distance prefetched ahead is proportional to this constant. Heads up: raising this number may also mean less streams get prefetched (peep simultaneous-prefetches).
  • simultaneous-prefetches โ€” the max number of prefetches that can run at the same time. โœจ
  • l1-cache-line-size โ€” the size of a cache line in the L1 data cache, in bytes.
  • l1-cache-size โ€” the size of the L1 data cache, in kilobytes.
  • l2-cache-size โ€” the size of the L2 data cache, in kilobytes.
  • prefetch-dynamic-strides โ€” whether the loop array prefetch pass should drop software prefetch hints for strides that are non-constant. In some cases this can be a win, though the whole non-constant-stride thing makes it hard to predict when there's a clear benefit to issuing these hints.

Set it to 1 if prefetch hints should be issued for non-constant strides. Set it to 0 if prefetch hints should only go out for strides that are known to be constant and below prefetch-minimum-stride.

  • prefetch-minimum-stride โ€” the 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, because in that case there may be conflicts between the hardware prefetchers and the software prefetchers. If the hardware prefetchers have a max stride they can handle, that should be used here to improve how the software prefetchers get used.

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.

  • loop-interchange-max-num-stmts โ€” the max number of stmts in a loop to be interchanged.
  • loop-interchange-stride-ratio โ€” the minimum ratio between the stride of two loops for interchange to actually be profitable. ๐Ÿ’…
  • min-insn-to-prefetch-ratio โ€” the minimum ratio between the number of instructions and the number of prefetches to enable prefetching in a loop.
  • prefetch-min-insn-to-mem-ratio โ€” the minimum ratio between the number of instructions and the number of memory references to enable prefetching in a loop.
  • use-canonical-types โ€” whether the compiler should use the "canonical" type system. 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 causing compilation failures, 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.
  • max-partial-antic-length โ€” the max 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 run away and eat all the memory available on the host machine. This parameter sets a limit on the length of the sets that get computed, which prevents that runaway behavior. Setting a value of 0 for this parameter allows an unlimited set length. ๐Ÿ’€
  • rpo-vn-max-loop-depth โ€” the max 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 do not.
  • sccvn-max-alias-queries-per-access โ€” the max number of alias-oracle queries we perform when looking for redundancies for loads and stores. If this limit gets 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 the given number of the most frequently-executed loops form regions for regional register allocation.
  • ira-max-conflict-table-size โ€” okay so even though IRA uses a sophisticated algorithm to compress the conflict table, the table can still need 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 doesn't need to build a pseudo-register conflict table. ๐Ÿซถ
  • ira-loop-reserved-regs โ€” IRA can be used to evaluate more accurate register pressure in loops for decisions to move loop invariants (peep -O3). The number of available registers reserved for some other purposes is given by this parameter. The default of the parameter is the best found from numerous experiments. ๐Ÿ”ฅ
  • 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 the 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 are not 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 (like 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 get 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 than or equal to ipa-sra-ptr-growth-factor times the size of the original pointer parameter.
  • ipa-sra-max-replacements โ€” the max pieces of an aggregate that IPA-SRA tracks. As a consequence, it's also the max 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 max 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 max 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 โ€” okay so Graphite's loop transforms can go full exponential on you if you let them, so the number of parameters in a Static Control Part (SCoP) is bounded. Set it to zero and the bound justโ€ฆ lifts. ๐Ÿ’… And what even is a parameter here? It's a variable whose value you don't know at compile time and that's defined outside a SCoP. That's it, that's the vibe.
  • loop-block-tile-size โ€” loop blocking and strip mining (the transforms you turn on with -floop-block or -floop-strip-mine) strip mine every loop in the loop nest by a given number of iterations. Wanna change the strip length? That's literally this parameter. ๐ŸŽ€
  • ipa-jump-function-lookups โ€” says how many statements get visited during jump function offset discovery. ngl, it does exactly what it says on the tin.
  • ipa-cp-value-list-size โ€” IPA-CP is out here trying to track all the possible values and types passed to a function's parameter so it can propagate them and do devirtualization. This parameter is the max number of values and types it'll store per one formal parameter of a function. Bestie's got a memory limit, respect it. โœจ
  • ipa-cp-eval-threshold โ€” IPA-CP scores its own cloning profitability heuristics, and then only actually does the cloning opportunities whose scores beat ipa-cp-eval-threshold. It's giving "you must be this profitable to ride". ๐ŸŽข
  • ipa-cp-max-recursive-depth โ€” maximum depth of recursive cloning for a self-recursive function. Yes, recursion, we love her. ๐ŸŒธ
  • ipa-cp-min-recursive-probability โ€” recursive cloning happens only when the probability of the call actually being executed exceeds this parameter. Lowkey a bouncer at the club. ๐Ÿซถ
  • ipa-cp-recursion-penalty โ€” the percentage penalty that recursive functions get hit with when they're evaluated for cloning.
  • ipa-cp-single-call-penalty โ€” the percentage penalty that functions containing a single call to another function get hit with when they're evaluated for cloning.
  • ipa-max-agg-items โ€” IPA-CP can also propagate a number of scalar values passed in an aggregate, and this parameter controls the maximum number of such values per one parameter. ๐Ÿ‘‘
  • 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 adds a bonus of ipa-cp-loop-hint-bonus to that candidate's profitability score. Extra credit, slay. โญ
  • ipa-max-loop-predicates โ€” the maximum number of different predicates IPA will use to describe when loops in a function have known properties.
  • ipa-max-aa-steps โ€” while analyzing function bodies, IPA-CP uses alias analysis to track values pointed to by function parameters. But it's not about to spend forever on giant functions, so after examining ipa-max-aa-steps statements that modify memory, it gives up and considers all memory clobbered. ๐Ÿ˜ญ dramatic but fair.
  • ipa-max-switch-predicate-bounds โ€” maximal number of boundary endpoints of case ranges of 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 statement.
  • ipa-max-param-expr-ops โ€” IPA-CP will analyze a conditional statement that references some function parameter to estimate the benefit of cloning upon a certain constant value. But if the number of operations in a parameter expression exceeds ipa-max-param-expr-ops, that expression gets treated as a complicated one and is not handled by IPA analysis. Too messy, no thank you. ๐Ÿ™ˆ
  • lto-partitions โ€” specify the desired number of partitions produced during WHOPR compilation. And fr fr, the number of partitions should exceed the number of CPUs used for compilation. ๐ŸŒˆ
  • lto-min-partition โ€” size of the minimal partition for WHOPR (in estimated instructions). This exists so you don't waste effort splitting very small programs into too many partitions. Iconic efficiency behavior.
  • lto-max-partition โ€” size of the max partition for WHOPR (in estimated instructions), to provide an upper bound for the individual size of a partition. Meant to be used only with balanced partitioning. ๐Ÿ’–
  • lto-max-streaming-parallelism โ€” maximal number of parallel processes used for LTO streaming. Go off, multicore. ๐Ÿ”ฅ
  • cxx-max-namespaces-for-diagnostic-help โ€” the maximum number of namespaces to consult for suggestions when C++ name lookup fails for an identifier. Yes bestie, the compiler is trying to help you find your typo. ๐Ÿ’…
  • sink-frequency-threshold โ€” the maximum 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. Bigger 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. โœจ
  • max-stores-to-sink โ€” the maximum 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.
  • 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. ๐ŸŽ€
  • jump-table-max-growth-ratio-for-size โ€” the maximum code size growth ratio when expanding into a jump table (in percent). This one gets used when you're optimizing for size.
  • jump-table-max-growth-ratio-for-speed โ€” the maximum code size growth ratio when expanding into a jump table (in percent). This one gets used when you're optimizing for speed. ๐ŸŽ๏ธ
  • tree-reassoc-width โ€” set the maximum number of instructions executed in parallel in a reassociated tree. This parameter overrides the target dependent heuristics used by default, if it has a non zero value. ๐Ÿ‘‘
  • sched-pressure-algorithm โ€” pick 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 taken by algorithm 1 and the rather aggressive approach taken by the default scheduler โ€” it relies more heavily on having a regular register file and accurate register pressure classes. See haifa-sched.c in the GCC sources for more details. ๐Ÿงš And the default choice? Depends on the target.
  • max-slsr-cand-scan โ€” set the maximum number of existing candidates that are considered when seeking a basis for a new straight-line strength reduction candidate.
  • asan-globals โ€” enable buffer overflow detection for global objects. This kind of protection is enabled by default if you're using the -fsanitize=address option. To disable global objects protection, use --param asan-globals=0. ๐Ÿ›ก๏ธ
  • asan-stack โ€” enable buffer overflow detection for stack objects. This kind of protection is 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. This kind of protection is 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. This kind of protection is 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. This kind of protection is 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. This kind of protection is 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. ๐Ÿšจ
  • asan-instrumentation-with-call-threshold โ€” if the number of memory accesses in a function being instrumented is greater 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. This is 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. This kind of instrumentation is 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 โ€” turns on hwasan checks for memory writes โœ๏ธ. Instrumenting writes is on by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. Wanna stop checking writes? Then --param hwasan-instrument-writes=0.
  • hwasan-instrument-mem-intrinsics โ€” turns on hwasan instrumentation of builtin functions ๐Ÿงš. Also enabled by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. To turn the builtin instrumentation off, it's --param hwasan-instrument-mem-intrinsics=0.
  • use-after-scope-direct-emission-threshold โ€” if a local variable's size in bytes is smaller than or equal to this number, GCC just poisons (or unpoisons) the shadow memory directly instead of going through run-time callbacks. No middleman, no cap ๐Ÿ’….
  • tsan-distinguish-volatile โ€” emit special instrumentation for accesses to volatiles. Yes, volatiles get their own lil treatment โœจ.
  • tsan-instrument-func-entry-exit โ€” emit instrumentation calls to __tsan_func_entry() and __tsan_func_exit(). In and out, bestie ๐Ÿšช๐Ÿซถ.
  • max-fsm-thread-path-insns โ€” the maximum number of instructions to copy when duplicating blocks on a finite state automaton jump thread path.
  • max-fsm-thread-length โ€” the maximum number of basic blocks allowed on a finite state automaton jump thread path.
  • max-fsm-thread-paths โ€” the maximum number of new jump thread paths to create for a finite state automaton.
  • parloops-chunk-size โ€” the chunk size of the omp schedule for loops parallelized by parloops ๐Ÿ”.
  • parloops-schedule โ€” the schedule type of omp schedule for loops parallelized by parloops: static, dynamic, guided, auto, runtime. Pick your fighter ๐Ÿ’….
  • parloops-min-per-thread โ€” the minimum number of iterations per thread of an innermost parallelized loop where the parallelized variant is preferred over the single-threaded one. Heads up though: for a parallelized loop nest, the minimum number of iterations of the outermost loop per thread is two.
  • max-ssa-name-query-depth โ€” the maximum depth of recursion when querying properties of SSA names in stuff like fold routines. One level of recursion = following one use-def chain link ๐Ÿ”—.
  • max-speculative-devirt-maydefs โ€” the maximum number of may-defs analyzed while 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 maximum number of assertions to add along the default edge of a switch statement during VRP.
  • evrp-mode โ€” specifies the mode Early VRP should operate in.
  • unroll-jam-min-percent โ€” the minimum percentage of memory references that have to be optimized away before the unroll-and-jam transformation is considered profitable ๐Ÿ’ธ.
  • unroll-jam-max-unroll โ€” the maximum number of times the outer loop should be unrolled by the unroll-and-jam transformation.
  • max-rtl-if-conversion-unpredictable-cost โ€” the maximum 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 maximum number of times that an individual variable will be expanded during loop unrolling.
  • tracer-min-branch-probability-feedback โ€” stop forward growth if the probability of the best edge drops below this threshold (in percent). Only used when profile feedback is available ๐Ÿ“Š.
  • partial-inlining-entry-probability โ€” the maximum probability of the entry BB of a split region (in percent, relative to the entry BB of the function) for partial inlining to actually happen.
  • max-tracked-strlens โ€” the maximum 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-edge execution count that permits performing redundancy elimination after reload.
  • max-loop-header-insns โ€” the maximum 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 instead of 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. This parameter only has an effect on targets that support partial vector loads and stores โ€” so if your target doesn't, it's giving nothing ๐Ÿ’€.
  • avoid-fma-max-bits โ€” the maximum 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</scheduler>.
  • sms-dfa-history โ€” the number of cycles the swing modulo scheduler considers when checking conflicts using DFA.
  • max-inline-insns-recursive-auto โ€” the maximum number of instructions a non-inline function can grow to via recursive inlining.
  • 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 considered during spilling a non-reload pseudo.
  • max-pow-sqrt-depth โ€” the maximum depth of sqrt chains to use when synthesizing exponentiation by a real constant.
  • max-dse-active-local-stores โ€” the maximum number of active local stores in RTL dead store elimination.
  • asan-instrument-allocas โ€” enable asan allocas/VLAs protection ๐Ÿ›ก๏ธ.
  • max-iterations-computation-cost โ€” a bound on the cost of an expression that computes the number of iterations.
  • max-isl-operations โ€” the maximum number of isl operations; 0 means unlimited โˆž.
  • graphite-max-arrays-per-scop โ€” the maximum number of arrays per scop.
  • max-vartrack-reverse-op-size โ€” max size of a loc list for which reverse ops should be added.
  • tracer-dynamic-coverage-feedback โ€” the percentage of a function, weighted by execution frequency, that must be covered by trace formation. Used when profile feedback is available.
  • max-inline-recursive-depth-auto โ€” the maximum depth of recursive inlining for non-inline functions.
  • fsm-scale-path-stmts โ€” the scale factor to apply to the number of statements in a threading path when comparing against the number of (scaled) blocks.
  • fsm-maximum-phi-arguments โ€” the maximum number of arguments a PHI may have before the FSM threader refuses to try threading through its block ๐Ÿšซ.
  • uninit-control-dep-attempts โ€” the maximum number of nested calls to search for control dependencies during uninitialized variable analysis.
  • sra-max-scalarization-size-Osize โ€” the maximum size, in storage units, of an aggregate that should be considered for scalarization when compiling for size ๐Ÿ“.
  • fsm-scale-path-blocks โ€” the scale factor to apply to the number of blocks in a threading path when comparing against the number of (scaled) statements.
  • sched-autopref-queue-depth โ€” hardware autoprefetcher scheduler model control flag. It's the number of lookahead cycles the model looks into; at ' ' only enable the instruction sorting heuristic. (Yes, that's a literal space character. Iconic honestly.)
  • loop-versioning-max-inner-insns โ€” the maximum number of instructions an inner loop can have before the loop versioning pass decides it's too big to copy.
  • loop-versioning-max-outer-insns โ€” the maximum number of instructions an outer loop can have before the loop versioning pass decides it's too big to copy โ€” and this is discounting any instructions in inner loops that directly benefit from versioning.
  • ssa-name-def-chain-limit โ€” the maximum number of SSA_NAME assignments to follow when determining a property of a variable, like its value. This caps the number of iterations or recursive calls GCC performs when optimizing certain statements, or when determining their validity before issuing diagnostics ๐Ÿ•ต๏ธ.
  • store-merging-max-size โ€” the maximum 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 โ€” the maximum number of VALUEs handled during a single find_base_term call.
  • analyzer-max-enodes-per-program-point โ€” the maximum number of exploded nodes per program point within the analyzer, before it terminates analysis of that point ๐Ÿ’€.
  • analyzer-max-constraints โ€” the maximum 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 maximum depth of exploded nodes that should show up in a dot dump before switching to a less verbose format.
  • analyzer-max-recursion-depth โ€” the maximum number of times a callsite can appear in a call stack within the analyzer, before it terminates analysis of a call that would recurse deeper ๐ŸŒ€.
  • analyzer-max-svalue-depth โ€” the maximum depth of a symbolic value, before approximating the value as unknown.
  • analyzer-max-infeasible-edges โ€” the maximum 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 that makes it count as hot ๐Ÿ”ฅ. This parameter is used only in GIMPLE FE.
  • analyzer-bb-explosion-factor โ€” the maximum number of 'after supernode' exploded nodes the analyzer will tolerate per supernode before it just throws its hands up and terminates the analysis. ๐Ÿ’€
  • ranger-logical-depth โ€” the maximum depth of logical expression evaluation that the ranger will look through when it's evaluating outgoing edge ranges.
  • openacc-kernels โ€” picks the mode for handling OpenACC kernels constructs. With --param=openacc-kernels=decompose, OpenACC kernels constructs get decomposed into parts โ€” a sequence of compute constructs โ€” and each one is then handled individually. (This is work in progress, bestie.) With --param=openacc-kernels=parloops, OpenACC kernels constructs are handled by the parloops pass, en bloc. That one is the current default. โœจ

The following choices of name are available on AArch64 targets:

  • 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. It also uses 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 โ€” the number of Newton iterations for calculating the reciprocal for double type. The precision of division is proportional to this param when division approximation is enabled. The default value is 2.
  • aarch64-autovec-preference โ€” force an ISA selection strategy for auto-vectorization. Accepts values from 0 to 4, inclusive.
    • 0 โ€” use the default heuristics.
    • 1 โ€” use only Advanced SIMD for auto-vectorization.
    • 2 โ€” use only SVE for auto-vectorization.
    • 3 โ€” use both Advanced SIMD and SVE. Prefer Advanced SIMD when the costs are deemed equal.
    • 4 โ€” use both Advanced SIMD and SVE. Prefer SVE when the costs are deemed equal.

The default value is 0.

  • aarch64-loop-vect-issue-rate-niters โ€” the tuning for some AArch64 CPUs tries to take both latencies and issue rates into account when deciding whether a loop should be vectorized using SVE, vectorized using Advanced SIMD, or not vectorized at all. If this parameter is set to n, GCC will not use this heuristic for loops that are known to execute in fewer than n Advanced SIMD iterations. ๐ŸŒ€

โœจ Program Instrumentation Options โœจ

GCC supports a whole bunch of command-line options that control adding run-time instrumentation to the code it normally generates. Like, one purpose of instrumentation is collecting profiling statistics โ€” for finding program hot spots, doing code coverage analysis, or profile-guided optimizations. ๐ŸŽ€

Another class of program instrumentation is adding run-time checking to detect programming errors like invalid pointer dereferences or out-of-bounds array accesses, plus deliberately hostile attacks such as stack smashing or C++ vtable hijacking. ๐Ÿ˜ค

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. iykyk. ๐Ÿ’…

  • -p, -pg โ€” generate extra code to write profile information suitable for the analysis program prof (for -p) or gprof (for -pg). You must use this option when compiling the source files you want data about, and you must also use it when linking. fr fr.

You can use the function attribute no_instrument_function to suppress profiling of individual functions when compiling with these options.

  • -fprofile-arcs โ€” add code so that program flow arcs are instrumented. During execution the program records how many times each branch and call is executed and how many times it is 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. The 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 is not the final executable, otherwise it is 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).

  • --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. ๐Ÿ”ฅ
    • 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. ๐Ÿง 

  • -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 convert 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. ๐Ÿ“
  • -fprofile-dir= path โ€” set 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 similar option -fprofile-note.

When an executable is run in a massive parallel environment, it is 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 application to produce 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 is specified, otherwise the section name defaults to ".gcov_info". A pointer to the profile information generated by -fprofile-arcs or -ftest-coverage 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 systems with limited resources which do not support constructors and destructors. The linker could collect the input sections in a continuous memory block and define start and end symbols. The runtime support could dump the profiling information registered in this linker set during program termination to a serial line for example. ๐Ÿฆ‹

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 = .);
                     }

  • -fprofile-note=path โ€” bestie, if you hand it a path, GCC drops the .gcno file riiight into that path location ๐Ÿ’…. But heads up: if you pair this option with multiple source files, the .gcno file will be overwritten ๐Ÿ˜ญ. One note file, many sources, chaos. You've been warned.
  • -fprofile-prefix-path=path โ€” this one is the โœจglow-upโœจ companion to profile-generate=profile_dir and profile-use=profile_dir, and its whole job is telling GCC where the base directory of your built source tree lives ๐Ÿ . Why do you care? Because by default profile_dir gets filled with files carrying mangled absolute paths of every object file in the project ๐Ÿ™ˆ. And that is not the vibe when the directory you used to build the instrumented binary is a different directory than the one you use to build the optimized-with-profile-feedback binary โ€” because then the profile data just... won't be found during the optimized build ๐Ÿ’€. So 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 ๐ŸŽ€. Slay.
  • -fprofile-update=method โ€” changes up the update method for an app that's been instrumented for profile-feedback-based optimization. The method argument should be one of single, atomic or prefer-atomic.
    • single โ€” perfect for single-threaded applications ๐Ÿงš.
    • atomic โ€” this one stops profile corruption by emitting thread-safe code ๐Ÿ”ฅ.
    • prefer-atomic โ€” gets transformed into either atomic (when the target supports it) or single otherwise. And guess what, the GCC driver automatically picks prefer-atomic when -pthread shows up on the command line ๐Ÿ‘‘.
Warning: When an application does not properly join all threads (or creates an detached thread), a profile file can be still corrupted. ๐Ÿ˜ฑ
  • -fprofile-filter-files=regex โ€” instruments only functions from files whose name matches any of the regular expressions (separated by semi-colons) ๐ŸŽฏ. For example, -fprofile-filter-files=main\.c;module.*\.c will instrument only main.c and all C files starting with 'module' ๐ŸŒธ.
  • -fprofile-exclude-files=regex โ€” the inverse energy ๐Ÿ™ƒ: instruments only functions from files whose name does not match any of the regular expressions (separated by semi-colons). For example, -fprofile-exclude-files=/usr/.* will prevent instrumentation of all files that are located in the /usr/ folder ๐Ÿšซ.
  • -fprofile-reproducible=[multithreaded|parallel-runs|serial] โ€” controls the level of reproducibility of the profile gathered by -fprofile-generate โœจ. This makes it possible to rebuild a program with the same outcome, which is useful for, like, distribution packages ๐Ÿ“ฆ.
    • 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, it 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 fork function is invoked ๐Ÿ‘€.
    • Okay real talk: it's quite common that execution counts of some part of programs depend, for example, on the length of temporary file names or on memory space randomization (which may affect hash-table collision rate) ๐Ÿ˜ตโ€๐Ÿ’ซ. Such non-reproducible parts of programs may be annotated by "no_instrument_function" function attribute. And gcov-dump with -l can be used to dump the gathered data and verify that they are indeed reproducible ๐Ÿ”.
    • With -fprofile-reproducible=parallel-runs the collected profile stays reproducible regardless of the order of streaming of the data into gcda files ๐ŸŒˆ. This setting makes it possible to run multiple instances of an instrumented program in parallel (such as with "make -j"). But it reduces the quality of gathered data, in particular of indirect call profiling ๐Ÿ“‰.
  • -fsanitize=address โ€” enables AddressSanitizer, a fast memory error detector ๐Ÿ•ต๏ธ. Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. This option enables -fsanitize-address-use-after-scope. See <https://github.com/google/sanitizers/wiki/AddressSanitizer> for more details. The run-time behavior can be influenced using the ASAN_OPTIONS environment variable ๐ŸŽ›๏ธ. When set to "help=1", the available options are shown at startup of the instrumented program. See <https://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flags> for a list of supported options. The option cannot be combined with -fsanitize=thread or -fsanitize=hwaddress ๐Ÿšซ. Note that the only target -fsanitize=hwaddress is currently supported on is AArch64.
  • -fsanitize=kernel-address โ€” enables AddressSanitizer for the Linux kernel ๐Ÿง. See <https://github.com/google/kasan> for more details.
  • -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 a low memory overhead โšก. Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. This option enables -fsanitize-address-use-after-scope. See <https://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html> for more details. The run-time behavior can be influenced using the HWASAN_OPTIONS environment variable ๐ŸŽ›๏ธ. When set to "help=1", the available options are shown at startup of the instrumented program. The option cannot be combined with -fsanitize=thread or -fsanitize=address, and is currently only available on AArch64 ๐Ÿ™….
  • -fsanitize=kernel-hwaddress โ€” enables Hardware-assisted AddressSanitizer for compilation of the Linux kernel ๐Ÿง. Similar to -fsanitize=kernel-address but using an alternate instrumentation method, and similar to -fsanitize=hwaddress but with instrumentation differences necessary for compiling 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 to the -fsanitize=hwaddress. Instrumenting the stack and alloca calls are not on by default but are still possible by specifying the command-line options --param hwasan-instrument-stack=1 and --param hwasan-instrument-allocas=1 respectively. Using a random frame tag is not implemented for kernel instrumentation.
  • -fsanitize=pointer-compare โ€” instruments comparison operations (<, <=, >, >=) with pointer operands ๐Ÿ”Ž. The option must be combined with either -fsanitize=kernel-address or -fsanitize=address. The option 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 ๐Ÿ”Ž. The option must be combined with either -fsanitize=kernel-address or -fsanitize=address. The option 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=thread โ€” enables ThreadSanitizer, a fast data race detector ๐Ÿ. Memory access instructions are instrumented to detect data race bugs. See <https://github.com/google/sanitizers/wiki#threadsanitizer> for more details. The run-time behavior can be influenced using the TSAN_OPTIONS environment variable ๐ŸŽ›๏ธ; see <https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags> for a list of supported options. The option cannot be combined with -fsanitize=address, -fsanitize=leak ๐Ÿšซ.
Note that sanitized atomic builtins cannot throw exceptions when operating on invalid memory addresses with non-call exceptions (-fnon-call-exceptions).
  • -fsanitize=leak โ€” enables LeakSanitizer, a memory leak detector ๐Ÿ’ง. This option only matters for linking of executables, and the executable is linked against a library that overrides malloc and other allocator functions. See <https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer> for more details. The run-time behavior can be influenced using the LSAN_OPTIONS environment variable ๐ŸŽ›๏ธ. The option cannot be combined with -fsanitize=thread ๐Ÿšซ.
  • -fsanitize=undefined โ€” enables UndefinedBehaviorSanitizer, a fast undefined behavior detector ๐ŸŒ€. Various computations are instrumented to detect undefined behavior at runtime. See <https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html> for more details. The run-time behavior can be influenced using the UBSAN_OPTIONS environment variable ๐ŸŽ›๏ธ. Current suboptions are:
    • -fsanitize=shift โ€” this option enables checking that the result of a shift operation is not undefined ๐Ÿค”. Note that what exactly is considered undefined differs slightly between C and C++, as well as between ISO C90 and C99, etc. This option has two suboptions, -fsanitize=shift-base and -fsanitize=shift-exponent.
    • -fsanitize=shift-exponent โ€” this option enables checking 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, check that the result of a shift operation is not undefined. Note that 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 as well as INT_MIN / -1 division โž—.
    • -fsanitize=unreachable โ€” with this option, the compiler turns the __builtin_unreachable call into a diagnostics message call instead ๐Ÿ“ข. When reaching the __builtin_unreachable call, the behavior is undefined.
    • -fsanitize=vla-bound โ€” this option instructs the compiler to check that the size of a variable length array is positive โœ….
  • -fsanitize=null โ€” pointer checking time ๐Ÿ’…. Build your app with this turned on and it will throw an error message at you 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 gets invoked on an object pointed to by a NULL pointer.
  • -fsanitize=return โ€” return statement checking โœจ. Programs built with this one turned on will error out when the end of a non-void function is reached without actually returning a value. C++ only, bestie.
  • -fsanitize=signed-integer-overflow โ€” signed integer overflow checking ๐Ÿ”ฅ. We check that the result of +, *, and both unary and binary - does not overflow in the signed arithmetics. Heads up tho: integer promotion rules must be taken into account. Meaning this next one is not an overflow:
signed char a = SCHAR_MAX;
a++;
  • -fsanitize=bounds โ€” instruments array bounds ๐ŸŽ€. Various out of bounds accesses get detected. Not instrumented: flexible array members, flexible array member-like arrays, and initializers of variables with static storage.
  • -fsanitize=bounds-strict โ€” strict instrumentation of array bounds ๐Ÿ’…. 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 โ€” checks alignment of pointers when they get 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 โ€” instruments memory references using the __builtin_object_size function ๐ŸŒธ. 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. It's giving "on purpose, actually."
  • -fsanitize=float-cast-overflow โ€” floating-point type to integer conversion checking ๐Ÿฆ‹. We check that the result of the conversion does not 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 โ€” instruments 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 โ€” instruments return statements in functions marked with the returns_nonnull function attribute, to detect returning null values from those functions ๐Ÿ’€.
  • -fsanitize=bool โ€” instruments loads from bool ๐ŸŒˆ. If a value other than 0/1 is loaded, a run-time error is issued.
  • -fsanitize=enum โ€” instruments 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 โ€” instruments C++ member function calls, member accesses, and some conversions between pointers to base and derived classes, to verify the referenced object has the correct dynamic type ๐Ÿงš.
  • -fsanitize=pointer-overflow โ€” instruments pointer arithmetics ๐Ÿ“. If the pointer arithmetics overflows, a run-time error is issued.
  • -fsanitize=builtin โ€” instruments 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.

While -ftrapv causes traps for signed overflows to be emitted, -fsanitize=undefined gives a diagnostic message ๐Ÿ“ข. This currently works only for the C family of languages.


  • -fno-sanitize=all โ€” this one disables all previously enabled sanitizers ๐Ÿ™ˆ. And no, -fsanitize=all is not allowed, because some sanitizers cannot be used together. Periodt.
  • -fasan-shadow-offset=number โ€” forces GCC to use a custom shadow offset in AddressSanitizer checks ๐ŸŽฏ. Useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer.
  • -fsanitize-sections=s1,s2,... โ€” sanitize global variables in selected user-defined sections โœจ. 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 causes it to attempt to continue 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 be used to 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 also needs to 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. This can be overridden through setting the halt_on_error flag in the corresponding environment variable.

Syntax without an explicit opts parameter is deprecated. It is 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 ๐Ÿ”. The 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 is not needed and is not linked in, so this is usable even in freestanding environments. Slay.
  • -fsanitize-coverage=trace-pc โ€” enables coverage-guided fuzzing code instrumentation ๐ŸŒˆ. Inserts a call to __sanitizer_cov_trace_pc into every basic block.
  • -fsanitize-coverage=trace-cmp โ€” enables dataflow guided fuzzing code instrumentation ๐Ÿ”ฌ. Inserts a call to __sanitizer_cov_trace_cmp1, __sanitizer_cov_trace_cmp2, __sanitizer_cov_trace_cmp4 or __sanitizer_cov_trace_cmp8 for integral comparison with both operands variable, or __sanitizer_cov_trace_const_cmp1, __sanitizer_cov_trace_const_cmp2, __sanitizer_cov_trace_const_cmp4 or __sanitizer_cov_trace_const_cmp8 for integral comparison with one operand constant, __sanitizer_cov_trace_cmpf or __sanitizer_cov_trace_cmpd for float or double comparisons, and __sanitizer_cov_trace_switch for switch statements.
  • -fcf-protection=[full|branch|return|none|check] โ€” enables code instrumentation of control-flow transfers to increase program security by checking that target addresses of control-flow transfer instructions (such as indirect function call, function return, indirect jump) are valid ๐Ÿ›ก๏ธ. This prevents diverting the flow of control to an unexpected target. It's intended to protect against such threats as Return-oriented Programming (ROP), and similarly call/jmp-oriented programming (COP/JOP).

The value branch tells the compiler to implement checking of validity of control-flow transfer at the point of indirect branch instructions, i.e. call/jmp instructions. The value return implements checking of validity at the point of returning from a function. The value full is an alias for specifying both branch and return. The value none turns off instrumentation.

The value check is used for the final link with link-time optimization (LTO) ๐Ÿ‘€. An error is issued if LTO object files are compiled with different -fcf-protection values. The value check is ignored at the compile time.

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 the return.

You can also use the nocf_check attribute to identify 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) which works for i686 processor or newer.

NOTE: In Ubuntu 19.10 and later versions, -fcf-protection is enabled by default for C, C++, ObjC, ObjC++, if none of -fno-cf-protection nor -fcf-protection=* are found. ๐Ÿ’…
  • -fstack-protector โ€” okay bestie, this is the bodyguard era ๐Ÿ›ก๏ธ. It emits extra code to check for buffer overflows, like stack smashing attacks. How? By adding a guard variable to functions with vulnerable objects โ€” which 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 the function exits. If a guard check fails, an error message is printed and the program exits. ๐Ÿ’€ Only variables that are actually allocated on the stack are considered, so optimized-away variables or variables allocated in registers don't count.
  • -fstack-protector-all โ€” like -fstack-protector except that all functions are protected. No favorites, everyone gets a bodyguard. ๐Ÿ‘‘
  • -fstack-protector-strong โ€” like -fstack-protector but it includes additional functions to be protected โ€” those that have local array definitions, or have references to local frame addresses. And same as before: only variables that are 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. If you didn't say the magic word, no protection for you. ๐Ÿ™ˆ
  • -fstack-check โ€” generates code to verify that you do not go beyond the boundary of the stack. You should specify this flag if you are 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 is only one stack. ๐Ÿงš
Heads up: 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. It's giving "I set up the vibe, you do the work". ๐Ÿ’…

You can additionally specify a string parameter:

  • no means no checking
  • generic means force the use of old-style checking
  • specific means use 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 it comes with the following drawbacks, and bestie, there are three:

  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. Not the slay we wanted.

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 ngl, it is not generally sufficient to protect against stack-clash attacks. To protect against those you want -fstack-clash-protection. ๐Ÿซถ

  • -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. ๐Ÿ”ฅ

Most targets do not fully support stack clash protection. However, on those targets -fstack-clash-protection will protect dynamic stack allocations. -fstack-clash-protection may also provide limited protection for static stack allocations if the target supports -fstack-check=specific.

NOTE: In Ubuntu 19.10 and later versions, -fstack-clash-protection is enabled by default for C, C++, ObjC, ObjC++, unless -fno-stack-clash-protection is found. ๐Ÿ‘€
  • -fstack-limit-register=reg, -fstack-limit-symbol=sym, -fno-stack-limit โ€” these three are a lil trio ๐Ÿ’œ. They generate code to ensure that 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 it is possible to 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, as it is no longer necessary to calculate a good stack size to use for each thread. This is currently only implemented for the x86 targets running GNU/Linux. ๐Ÿง

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 is not 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 one is only available when compiling C++ code, so C girlies sit this out. ๐Ÿ’… It turns on (or off, if 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 has not 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 are 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; 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. This information is written to a file named vtv_set_ptr_data.log in the directory named by the environment variable VTV_LOGS_DIR if that is 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. fr fr, don't skip this step. ๐Ÿ™ˆ
  • -fvtv-counts โ€” this is a debugging flag. When used in conjunction with -fvtable-verify=std or -fvtable-verify=preinit, this causes the compiler to keep track of the total number of virtual calls it encounters and the number of verifications it inserts. It also counts the number of calls to certain run-time library functions that it inserts and logs this information for each compilation unit. The compiler writes this information to a file named vtv_count_data.log in the directory named by the environment variable VTV_LOGS_DIR if that is defined, or the current working directory otherwise. It also counts the size of the vtable pointer sets for each class, and writes this information to vtv_class_set_sizes.log in the same directory. ๐Ÿ“Š
Note: This feature appends data to the log files. To get fresh log files, be sure to delete any existing ones. ๐Ÿ“
  • -finstrument-functions โ€” generates instrumentation calls for entry and exit to functions. Just after function entry and just before function exit, the following profiling functions are called with the address of the current function and its call site. (On some platforms, __builtin_return_address does not work beyond the current function, so the call site information may not be available to the profiling functions otherwise.)
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 may be looked up exactly in the symbol table. โœจ

This instrumentation is also done for functions expanded inline in other functions. The profiling calls indicate where, conceptually, the inline function is entered and exited. This means that addressable versions of such functions must be available. If all your uses of a function are expanded inline, this may mean an additional expansion of code size. If you use extern inline in your C code, an addressable version of such functions must be provided. (This is normally 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 may be given the attribute no_instrument_function, in which case this instrumentation is not done. This can be used, for example, for the profiling functions listed above, high-priority interrupt routines, and any functions from which the profiling functions cannot safely be called (perhaps signal handlers, if the profiling routines generate output or allocate memory). ๐Ÿงš

  • -finstrument-functions-exclude-file-list=file,file,... โ€” okay so this one sets the list of functions that are excluded from instrumentation (go read the description of -finstrument-functions if you need the lore, bestie). If the file that contains a function definition matches with one of file, then that function does not get instrumented. And how does the matching work? On substrings ๐Ÿ’… if the file parameter is a substring of the file name, it's considered a match. Periodt.

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,... โ€” this is similar to -finstrument-functions-exclude-file-list, but instead it sets the list of function names to be excluded from instrumentation. The function name you're matching against is its user-visible name, like vector<int> blah(const vector<int> &), not the internal mangled name (e.g., _Z4blahRSt6vectorIiSaIiEE) ๐Ÿ™ˆ. Matching is done 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] โ€” generate N NOPs right at the beginning of each function, with the function entry point before the *M*th NOP ๐ŸŽ€. If M is omitted, it defaults to 0 so the function entry points to the address just at the first NOP. The NOP instructions reserve extra space which can be used to patch in any desired instrumentation at run time, provided that 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 command-line option -fpatchable-function-entry=N,M. This can be used 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 โœจ

These options control the C preprocessor, which is run on each C source file before actual compilation, no cap ๐Ÿซถ.

If you use the -E option, nothing is done except preprocessing. Some of these options make sense only 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 โ€” predefine 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 to use the shell's quoting syntax to protect characters such as spaces that have a meaning in the shell syntax ๐ŸŒธ.

If you wish to define 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 you should quote the option. With sh and csh, -D'name(args...)=definition' works ๐Ÿ‘‘.

-D and -U options are processed in the order they are given on the command line. All -imacros file and -include file options are processed after all -D and -U options.

  • -U name โ€” cancel any previous definition of name, either built in or provided with a -D option. Gone. Deleted. Not me erasing your macro ๐Ÿ˜ญ
  • -include file โ€” process 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 is 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 remain defined. This allows you to acquire all the macros from a header without also processing its declarations, which is lowkey iconic.

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, bestie, don't panic ๐Ÿ’–
  • -pthread โ€” define additional macros required for using the POSIX threads library. You should use this option consistently for both compilation and linking. 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 object file suffix and with any leading directory parts removed. If there are many included files then the rule is 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 such debug output with the dependency rules you should explicitly specify the dependency output file with -MF, or use an environment variable like DEPENDENCIES_OUTPUT. Debug output is still sent 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 do not mention header files that are found in system header directories, nor header files that are 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 in 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 โ€” in conjunction with an option such as -M requesting dependency generation, -MG assumes missing header files are generated files and adds them to the dependency list without raising an error. The dependency filename is taken directly from the #include directive without prepending any path. -MG also suppresses preprocessed output, as a missing header file renders this useless.

This feature is used in automatic updating of makefiles ๐Ÿ’…

  • -Mno-modules โ€” disable dependency generation for compiled module interfaces. That's it, that's the whole vibe ๐Ÿฆ‹
  • -MP โ€” this option instructs CPP to add a phony target for each dependency other than the main file, causing each to depend on nothing. These dummy rules work around errors make gives if you remove header files without updating the Makefile to match.

This is typical output:

test.o: test.c test.h

test.h:
  • -MT target โ€” change the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as .c, and appends the platform's usual object suffix. The result is the target.

An -MT option sets the target to be exactly the string you specify. If you want multiple targets, you can specify them as a single argument to -MT, or use multiple -MT options ๐Ÿ‘‘

For example, -MT '$(objpfx)foo.o' might give

$(objpfx)foo.o: foo.c
  • -MQ target โ€” same as -MT, but it quotes any characters which are special to Make. -MQ '$(objpfx)foo.o' gives
$$(objpfx)foo.o: foo.c

The default target is automatically quoted, as if it were given with -MQ.

  • -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.

Since -E is not implied, -MD can be used to generate a dependency output file as a side effect of the compilation process โœจ

  • -MMD โ€” like -MD except mention only user header files, not system header files. Simple. Clean. Iconic ๐ŸŽ€

okay bestie we're still deep in preprocessor territory and it's giving very much "the compiler's inner monologue" energy. buckle up. ๐ŸŽ€

  • -fpreprocessed โ€” tells the preprocessor "bestie, this file is already preprocessed, chill." ๐Ÿ’… It suppresses stuff like macro expansion, trigraph conversion, escaped newline splicing, and the processing of most directives. It does still recognize and remove comments, so you can hand a file that was preprocessed with -C straight to the compiler with zero problems. In this mode, the integrated preprocessor is little more than a tokenizer for the front ends. And heads up: -fpreprocessed is implicit if your input file has one of the extensions .i, .ii or .mi โ€” those are literally the extensions GCC uses for preprocessed files created by -save-temps. โœจ
  • -fdirectives-only โ€” when preprocessing, handle directives, but do not expand macros. The way this behaves depends on the -E and -fpreprocessed options. ๐Ÿ‘€
    • 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. Also, -dD gets 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. ๐ŸŒˆ
  • -fdollars-in-identifiers โ€” accept $ in identifiers. that's it, that's the whole vibe. ๐Ÿ’€
  • -fextended-identifiers โ€” accept universal character names and extended characters in identifiers. This one is enabled by default for C99 (and later C standard versions) and C++. ๐ŸŒธ
  • -fno-canonical-system-headers โ€” when preprocessing, do not shorten system header paths with canonicalization. no glow-ups for your paths today. ๐Ÿ™ˆ
  • -fmax-include-depth=depth โ€” sets the maximum depth of the nested #include. The default is 200. ๐ŸŒ€
  • -ftabstop=width โ€” sets 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. โญ
  • -ftrack-macro-expansion[=level] โ€” tracks the locations of tokens across macro expansions. This lets the compiler emit a diagnostic about the current macro expansion stack when a compilation error happens inside a macro expansion. Using this option makes the preprocessor and the compiler consume more memory. The level parameter picks how precise the token location tracking is, so you can dial the memory consumption down if you need to. ๐Ÿงš
    • 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. This value is the most memory hungry.
    • When this option is given no argument, the default parameter value is 2.
ngl, note that -ftrack-macro-expansion=2 is activated by default. so it's already on, bestie. ๐Ÿ‘‘
  • -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. You can use this 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 โ€” sets 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. ๐Ÿ’œ
  • -fwide-exec-charset=charset โ€” sets the wide execution character set, used for wide string and character constants. The default is one of UTF-32BE, UTF-32LE, UTF-16BE, or UTF-16LE, whichever corresponds to the width of wchar_t and the big-endian or little-endian byte order being used for code generation. 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. ๐Ÿ˜ญ
  • -finput-charset=charset โ€” sets 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. ๐Ÿฆ‹
  • -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. ๐Ÿ“š
  • -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.

bestie, do not write this #pragma in your own code. it is safe to edit the filename if the PCH file is available in a different location, though. The filename may be absolute or it may be relative to GCC's current directory. ๐Ÿ™
  • -fworking-directory โ€” enables 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. ๐Ÿšซ
  • -A predicate=answer โ€” makes 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. โœจ
  • -A -predicate=answer โ€” cancels an assertion with the predicate predicate and answer answer. ๐Ÿ’…
  • -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 #. ๐Ÿ˜ฑ
  • -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. ๐Ÿ™ˆ

The -CC option is generally used to support lint comments.

  • -P โ€” inhibits generation of linemarkers in the output from the preprocessor. This might be useful when running the preprocessor on something that is not C code, and will be sent to a program which might be confused by the linemarkers. ๐ŸŒ€
  • -traditional
  • -traditional-cpp โ€” 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. ๐Ÿ‘‘
  • -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 โ€” enables special code to work around file systems which only permit very short file names, such as MS-DOS. ๐Ÿ’พ
  • -H โ€” prints 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 ...!. ๐Ÿ”
  • -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. ๐Ÿ’€
    • -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

and boom, every single predefined macro just shows up. ๐Ÿ’…

ngl bestie, if you use -dM without -E, then -dM gets interpreted as a synonym for -fdump-rtl-mach instead. so like. keep -E there or you're getting something completely different. ๐Ÿ™ˆ
  • -dD โ€” basically -dM but with two lil differences: 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. โœจ
  • -dN โ€” like -dD, except it only emits the macro names, not their expansions. lowkey minimal of it.
  • -dI โ€” outputs #include directives in addition to the result of preprocessing. ๐ŸŽ€
  • -dU โ€” like -dD except only macros that are expanded, or whose definedness is tested in preprocessor directives, get output. the output is delayed until the use or test of the macro happens, and #undef directives are also output for macros that were tested but undefined at that time. iconic behavior fr fr.
  • -fdebug-cpp โ€” okay so this one is only useful for debugging GCC itself. when used from CPP or with -E, it dumps debugging information about location maps, and 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. that's it. that's the whole vibe.
  • -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 gets split into multiple options at the commas. but (and this is the important part bestie) 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. periodt. ๐Ÿ’€
  • -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. and if you wanna pass an option that takes an argument, you gotta use -Xpreprocessor twice โ€” once for the option and once for the argument. yes really, twice. ๐Ÿ™ˆ
  • -no-integrated-cpp โ€” perform preprocessing as a separate pass before compilation. by default, GCC does 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. โœจ
  • -flarge-source-files โ€” adjusts GCC to expect large source files, at the expense of slower compilation and higher memory usage. so like. trade-off city.

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. ๐Ÿซถ


๐ŸŒธ Passing Options to the Assembler ๐ŸŒธ

okay so you can also pass options to the assembler, bestie. here's how:

  • -Wa,option โ€” pass option as an option to the assembler. if option contains commas, it is split into multiple options at the commas. ๐ŸŽ€
  • -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. and again โ€” if you wanna pass an option that takes an argument, you must use -Xassembler twice, once for the option and once for the argument. same deal as before, no cap. ๐Ÿ’…

๐Ÿ’– Options for Linking ๐Ÿ’–

these options come into play when the compiler links object files into an executable output file. and they are meaningless if the compiler is not doing a link step. like, literally nothing. so don't stress about them otherwise. โœจ

  • 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. ๐Ÿฆ‹
  • -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. that's the whole note. three icons, one rule. ๐Ÿ’…
  • -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. ๐Ÿ‘‘

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 building 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 the 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 the object files in an 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 a static library instead. alternatively it is possible to use H.J. Lu's binutils with support for mixed objects. iykyk. ๐Ÿซถ

  • -fuse-ld=bfd โ€” use the bfd linker instead of the default linker.
  • -fuse-ld=gold โ€” use the gold linker instead of the default linker.
  • -fuse-ld=lld โ€” use the LLVM lld linker instead of the default linker.
  • -fuse-ld=mold โ€” use the Modern Linker (mold) instead of the default linker. yes mold. slay. ๐Ÿ”ฅ
  • -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.

static libraries are archives of object files, and have file names 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 the -static option is used.

it makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. if bar.o refers to functions in z, those functions may not be loaded. order matters bestie, fr fr. ๐Ÿ’€

  • -lobjc โ€” you need this special case of the -l option in order to link an Objective-C or Objective-C++ program. ๐Ÿ“
  • -nostartfiles โ€” do not use the standard system startup files when linking. the standard system libraries are used normally, unless -nostdlib, -nolibc, or -nodefaultlibs is used. โœจ
  • -nodefaultlibs โ€” do not use the standard system libraries when linking. 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 standard startup files are used normally, unless -nostartfiles is used.

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. still link 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. ๐Ÿฆ‹
  • -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. that's the big one. ๐Ÿ’…

So like, bestie, your compiler is out here potentially generating calls to memcmp, memset, memcpy and memmove, okay? And those entries are usually resolved by entries in libc. But when this option is specified, you gotta supply those entry points through some other mechanism. No cap.

One of the standard libraries that gets bypassed by -nostdlib and -nodefaultlibs is libgcc.a โ€” and that's a whole library of internal subroutines that GCC uses to overcome shortcomings of particular machines, or just like, special needs for some languages. It's giving โœจsupport systemโœจ.

In most cases you literally need libgcc.a, even when you're trying to avoid other standard libraries. In other words: when you specify -nostdlib or -nodefaultlibs, you should usually specify -lgcc as well. That's how you ensure you have no unresolved references to internal GCC library subroutines. (An example of such an internal subroutine is __main, which is used to make sure C++ constructors get called. ๐Ÿซถ)


  • -e entry โ€” --entry=entry โ€” Specify that the program entry point is entry. The argument gets interpreted by the linker, and 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. Consistency is the vibe check here, fr fr.
  • -no-pie โ€” Don't produce a dynamically linked position independent executable. That's it, that's the whole thing. ๐Ÿ™ˆ
  • -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. Iconic behaviour, but you have to keep it consistent. ๐Ÿ‘‘
  • -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. Don't half-send it, bestie. ๐Ÿงต
  • -r โ€” Produce a relocatable object as output. This is also known as partial linking.
  • -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. Poof. Gone. Stripped. ๐Ÿ’€
  • -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 a flex on shared libraries.
  • -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, 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.

If you want to pass an option that takes a separate argument, you must use -Xlinker twice โ€” once for the option and once for the argument. For example, to pass -assert definitions, you must write:

-Xlinker -assert -Xlinker definitions

It does not work to write:

-Xlinker "-assert definitions"

because this passes the entire string as a single argument, which is not what the linker expects. ๐Ÿ˜ญ

When using the GNU linker, it is usually more convenient to pass arguments to linker options using the option=value syntax than as separate arguments. For example, you can specify:

-Xlinker -Map=output.map

rather than:

-Xlinker -Map -Xlinker output.map

Other linkers may not support this syntax for command-line options.

  • -Wl,option โ€” Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas. 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. When using the GNU linker, you can also get the same effect with -Wl,-Map=output.map.
NOTE: In Ubuntu 8.10 and later versions, for LDFLAGS, the option -Wl,-z,relro is used. To disable, use -Wl,-z,norelro. ๐Ÿ“Œ
  • -u symbol โ€” Pretend the symbol symbol is undefined, to force linking of library modules to define it. You can use -u multiple times with different symbols to force loading of additional library modules. ๐Ÿช„
  • -z keyword โ€” -z is passed directly on to the linker along with the keyword keyword. See the section in the documentation of your linker for permitted values and their meanings. Iykyk. ๐Ÿ’œ

These options specify directories to search for header files, for libraries, and for parts of the compiler: ๐ŸŽ€

  • -I dir โ€” -iquote dir โ€” -isystem dir โ€” -idirafter dir โ€” Add the directory dir to the list of directories to be searched for header files during preprocessing. If dir begins with = or $SYSROOT, then the = or $SYSROOT is replaced by the sysroot prefix; see --sysroot and -isysroot.

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 as follows:

  1. For the quote form of the include directive, the directory of the current file is searched first.
  1. For the quote form of the include directive, the directories you gave with -iquote get searched in left-to-right order, literally the order they show up on the command line. ๐Ÿ’…
  2. Directories you passed with -I get scanned left-to-right. periodt.
  3. Directories you passed with -isystem get scanned left-to-right too.
  4. Then the standard system directories get scanned.
  5. And finally, directories you passed with -idirafter get scanned left-to-right. last but not least bestie ๐Ÿซถ

You can use -I to override a system header file by swapping in your own version, because these directories get searched before the standard system header directories. ๐Ÿ’– BUT โ€” and this is the important part โ€” you should not use this option to add directories that hold vendor-supplied system header files. Use -isystem for that, okay? no cap.

The -isystem and -idirafter options also mark the directory as a system directory, so it gets the exact same special treatment that the standard system directories get. โœจ

Now this one is a lil tricky: if a standard system include directory, or a directory given with -isystem, is also specified with -I, then the -I option is ignored. ๐Ÿ˜ญ The directory is still searched โ€” but as a system directory, at its normal position in the system include chain. Why? To make sure GCC's procedure to fix buggy system headers, and the ordering for the "#include_next" directive, don't get inadvertently changed. If you really need to change the search order for system directories, use the -nostdinc and/or -isystem options instead.


  • -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 you specify additional directories with -I options after the -I-, those directories get searched for all #include directives.

On top of that, -I- inhibits the use of the directory of the current file directory as the first search directory for "#include "file"". And there is literally no way to override this effect of -I-. ๐Ÿ™ˆ

  • -iprefix prefix โ€” Specify prefix as the prefix for subsequent -iwithprefix options. If the prefix represents a directory, you should include the final /. ๐Ÿ“
  • -iwithprefix dir
  • -iwithprefixbefore dir โ€” Append dir to the prefix specified previously with -iprefix, and add 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 option 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 information. ๐Ÿ‘‘
  • -imultilib dir โ€” Use 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. so exclusive, we love that for you ๐ŸŽ€
  • -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 โ€” Set 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. so hands off bestie, it's not for us ๐Ÿ™ˆ
  • -Ldir โ€” Add 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. ๐Ÿ‘‘

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 is not found, or if -B is not 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 is found, the unmodified program name is searched for using the directories specified in your PATH environment variable. ๐Ÿ”

The compiler checks to see if 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 is not found there, the two standard prefixes above are tried, and that is all. The file is left out of the link if it is 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 is replaced by [dir/]include. This is to help with boot-strapping the compiler. ๐Ÿ’…

  • -no-canonical-prefixes โ€” Do not expand any symbolic links, resolve references to /../ or /./, or make the path absolute when generating a relative prefix. no shortcuts, no glow-ups, just vibes โœจ
  • --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. so they split the work, main character energy fr fr

The GNU linker (beginning with version 2.16) has the necessary support for this option. If your linker does not support this option, the header file aspect of --sysroot still works, but the library aspect does not. ๐Ÿ’€

  • --no-sysroot-suffix โ€” For some targets, a suffix is added to the root directory specified with --sysroot, depending on the other options used, so that 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. iykyk ๐Ÿ’…

  • -fstack-reuse=reuse-level โ€” This option controls stack space reuse for user declared local/auto variables and compiler generated temporaries. reuse_level can be all, named_vars, or none. all enables stack reuse for all local variables and temporaries, named_vars enables the reuse only for user defined local variables with names, and none disables stack reuse completely. The default value is all. The option is needed when the program extends the lifetime of a scoped local variable or a compiler generated temporary beyond the end point defined by the language. When a lifetime of a variable ends, and if the variable lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped local variables whose live range does not overlap with it. Legacy code extending local lifetime is likely to break with the stack reuse optimization. ๐Ÿ˜ญ

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. When a lifetime of a temporary ends, and if the temporary lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped local variables whose live range does not overlap with it. However some of the legacy code relies on the behavior of older compilers in which temporaries' stack space is not reused, the aggressive stack reuse can lead to runtime errors. This option is used to control the temporary stack reuse optimization. ๐Ÿ‘‘

  • -ftrapv โ€” This option generates traps for signed overflow on addition, subtraction, multiplication operations. 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. ๐Ÿ”ฅ
so order matters and active options are the ones that count โ€” don't get caught lacking bestie ๐Ÿ’…
  • -fwrapv โ€” bestie, this one tells the compiler: assume signed arithmetic overflow for addition, subtraction and multiplication just wraps around using twos-complement representation. Cute, right? It enables some optimizations and disables others. And here's the tea: -ftrapv and -fwrapv override each other, so if you put -ftrapv -fwrapv on the command-line, -fwrapv is the one that wins. But โ€” and this is important โ€” only active options override, so -ftrapv -fwrapv -fno-wrapv on the command-line means -ftrapv is the one that's effective. ๐Ÿ’…
  • -fwrapv-pointer โ€” this 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. โœจ
  • -fstrict-overflow โ€” this option implies -fno-wrapv -fno-wrapv-pointer and when negated implies -fwrapv -fwrapv-pointer. That's it, that's the whole vibe. ๐Ÿฆ‹
  • -fexceptions โ€” Enable exception handling. Generates 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 do not 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 do not normally require it. However, you may need to enable this option when compiling C code that needs to interoperate properly with exception handlers written in C++. You may also wish to disable this option if you are compiling older C++ programs that don't use exception handling. ๐Ÿซถ
  • -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. ๐Ÿ™ˆ
  • -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 option is enabled by default for the Ada compiler, as permitted by the Ada language specification. Optimization passes that cause dead exceptions to be removed are enabled independently at different optimization levels. ๐Ÿ’€
  • -funwind-tables โ€” Similar to -fexceptions, except that it just generates any needed static data, but does not affect the generated code in any other way. You normally do not need to enable this option; instead, a language processor that needs this handling enables it on your behalf. no cap ๐Ÿ’–
  • -fasynchronous-unwind-tables โ€” Generate unwind table in DWARF format, if supported by 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). ๐ŸŒธ
  • -fno-gnu-unique โ€” okay so on systems with 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 this causes dlclose to be ignored for affected DSOs; if your program relies on reinitialization of a DSO via dlclose and dlopen, you can use -fno-gnu-unique. the way that one sentence just kept goingโ€ฆ iconic ๐Ÿ˜ญ
  • -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).

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 is 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. main character energy fr fr ๐Ÿ‘‘

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. tiny enum, big slay ๐ŸŽ€
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. ๐ŸŒˆ

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.

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 is mainly useful to enable legacy code to link without errors. legacy code we're rooting for you ๐Ÿซถ

  • -fno-ident โ€” Ignore the #ident directive. bye bestie ๐Ÿ‘‹
  • -finhibit-size-directive โ€” Don't output a .size assembler directive, or anything else that would cause trouble if the function is split in the middle, and the two halves are placed at locations far apart in memory. This option is used when compiling crtstuff.c; you should not need to use it for anything else. ๐Ÿ’œ
  • -fverbose-asm โ€” Put extra commentary information in the generated assembly code to make it more readable. This option is generally only of use to those who actually need to read the generated assembly code (perhaps while debugging the compiler itself). ๐Ÿ˜ญ

-fno-verbose-asm, the default, causes the extra information to be omitted and is useful when comparing two assembler files.

The added comments include:

  • information 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

The comments are intended for humans rather than machines and hence the precise format of the comments is subject to change. iykyk ๐Ÿ’…

  • -frecord-gcc-switches โ€” okay so this one literally records the command line you used to invoke the compiler straight into the object file that's being created. Iconic. But bestie, heads up: it's only implemented on some targets, and the exact format of the recording is dependent on the target and the binary file format โ€” it usually takes the form of a section containing ASCII text. This switch is 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 storing compiler options into the object file.
  • -fpic โ€” generate position-independent code (PIC) that's suitable for use in a shared library, if it's supported for the target machine. This kind of code accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts (and no, the dynamic loader is not part of GCC โ€” it's part of the operating system ๐Ÿ’…). If the GOT size for the linked executable exceeds a machine-specific maximum size, you get an error message from the linker saying -fpic does not work; in that case, recompile with -fPIC instead. (Those maximums are 8k on the SPARC, 28k on AArch64 and 32k on the m68k and RS/6000. The x86 has no such limit, main character energy.)

Position-independent code requires special support, and therefore works only 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 it's supported for the target machine, emit position-independent code suitable for dynamic linking and avoiding any limit on the size of the global offset table. This option makes a difference on AArch64, m68k, PowerPC and SPARC.

Position-independent code requires special support, and therefore works only on certain machines.

When this flag is set, the macros __pic__ and __PIC__ are defined to 2.

  • -fpie
  • -fPIE โ€” these options 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 will be linked using the -pie GCC option.

-fpie and -fPIE both define the macros __pie__ and __PIE__. The 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 leads to more efficient code by eliminating PLT stubs and exposing GOT loads to optimizations. On architectures such as 32-bit x86 where PLT stubs expect the GOT pointer in a specific register, this gives more register allocation freedom to the compiler. Lazy binding requires use of 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 that are 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 would be more efficient than other code generation strategies. This option is of use in conjunction with -fpic or -fPIC for building code that forms part of a dynamic linker and cannot reference the address of a jump table. On some targets, jump tables do not require a GOT and this option is not needed.
  • -fno-bit-tests โ€” do not use bit tests for switch statements, even where it would be more efficient than other code generation strategies.
  • -ffixed-reg โ€” treat the register named reg as a fixed register; generated code should never refer to it (except perhaps 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.

  • -fcall-used-reg โ€” treat the register named reg as an allocable register that is clobbered by function calls. It may be allocated for temporaries or variables that do not 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. Use of 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. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results.

A different sort of disaster results from the use of 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 is specified (which must be a small power of two), pack structure members according to this 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. Additionally, it makes the code suboptimal. Use it to conform to a non-default application binary interface.
  • -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.
  • -ftls-model=model โ€” alter 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 is not given on the command line.

The default without -fpic is initial-exec; with -fpic the default is global-dynamic.

  • -ftrampolines โ€” for targets that normally need trampolines for nested functions, always generate them instead of using descriptors. Otherwise, for targets that do not need them โ€” like, for example, HP-PA or IA-64 โ€” do nothing.

A trampoline is a small piece of code that is created at run time on the stack when the address of a nested function is taken, and is used to call the nested function indirectly. Therefore, it requires the stack to be made executable in order for the program to work properly.

-fno-trampolines is enabled by default on a language by language basis to let the compiler avoid generating them, if it computes that this is safe, and replace them with descriptors. Descriptors are made up of data only, but the generated code must be prepared to deal with them. As of this writing, -fno-trampolines is enabled by default only for Ada.

Moreover, code compiled with -ftrampolines and code compiled with -fno-trampolines are not binary compatible if nested functions are present. This option must therefore be used on a program-wide basis and be manipulated with extreme care. ๐Ÿซถ

  • -fvisibility=[default|internal|hidden|protected] โ€” set the default ELF image symbol visibility to the specified option โ€” all symbols are marked with this unless overridden within the code. Using this feature 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. 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 offered by 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. This is 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. This is a great boon to those working with cross-platform projects. ๐ŸŒˆ

For those of you adding visibility support to code that already exists, bestie, you're gonna wanna know about #pragma GCC visibility โ€” it's lowkey a lifesaver ๐Ÿ’…. The way it works is you wrap the declarations you wanna set visibility for, like with #pragma GCC visibility push(hidden) and #pragma GCC visibility pop. Wrap it, set it, pop it. Iconic.

But fr fr, keep in mind that symbol visibility is part of the API interface contract โ€” so all new code should always specify visibility when it's not the default. Like, declarations that are only meant for use inside the local DSO should always be explicitly marked as hidden, so you dodge those PLT indirection overheads โ€” and making it abundantly clear also helps readability and self-documentation of the code. Self-documenting code is main character energy, no cap. ๐ŸŽ€

Heads up though: because of ISO C++ specification requirements, operator new and operator delete must always be of default visibility. That's not a vibe, that's a rule.

Also be aware that headers from outside your project โ€” especially system headers and headers from any other library you use โ€” might not be expecting to be compiled with anything other than default visibility. You may need to explicitly say #pragma GCC visibility push(default) before including any such headers. Protect your peace. ๐Ÿซถ

extern declarations are not affected by -fvisibility, so a lot of code can be recompiled with -fvisibility=hidden with zero modifications. Slay. But โ€” and this is the catch โ€” that means calls to extern functions with no explicit visibility go through the PLT, so it's more effective to use __attribute ((visibility)) and/or #pragma GCC visibility to tell the compiler which extern declarations should be treated as hidden. Do the extra step, babe, it's worth it. โœจ

Now, -fvisibility does affect C++ vague linkage entities. Which means, for instance, that an exception class thrown between DSOs must be explicitly marked with default visibility so that the type_info nodes are unified between the DSOs. Cross-DSO drama avoidance, honestly.

There's a whole overview of these techniques, their benefits, and how to use them at <http://gcc.gnu.org/wiki/Visibility>.


  • -fstrict-volatile-bitfields โ€” okay so use this one if accesses to volatile bit-fields (or other structure fields, though 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 those targets, obviously) 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 don't contain any portion of the bit-field, or memory-mapped registers unrelated to the one being updated. ๐Ÿ˜ฌ Not it.

In some cases โ€” like 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's correctly aligned for the target machine. In that case GCC falls back to generating multiple accesses rather than code that will fault or truncate the result at run time. It's giving "we tried, but safety first."

Note: due to restrictions of the C/C++11 memory model, write accesses are not allowed to touch non bit-field members. It's therefore recommended to define all bits of the field's type as bit-field members. Fr fr, do this.

The default value of this option is determined by the application binary interface for the target processor.

  • -fsync-libcalls โ€” this option 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. That's it, that's the whole thing. ๐Ÿฆ‹


๐Ÿ› ๏ธ GCC Developer Options ๐Ÿ› ๏ธ

Okay so this section? It's describing 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. This includes options that produce debug dumps at various points in the compilation, options that print statistics like memory use and execution time, and options that print information about GCC's configuration โ€” like where it searches for libraries. You should rarely need to use any of these options for ordinary compilation and linking tasks. This is the backstage pass section, bestie. ๐ŸŽŸ๏ธโœจ

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, a phase letter, and a 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's 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're 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.

Dumps and callgraphs, let's go ๐ŸŽ€

  • -fcallgraph-info
  • -fcallgraph-info=MARKERS โ€” makes the compiler output callgraph information for the program, on a per-object-file basis. The information is generated in the common VCG format. It can be decorated with additional, per-node and/or per-edge information, if a list of comma-separated markers is additionally specified. 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 โ€” -fdump-rtl-ce1, -fdump-rtl-ce2, and -fdump-rtl-ce3 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 โ€” -fdump-rtl-cse1 and -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 โ€” -fdump-rtl-dce1 and -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 โ€” -fdump-rtl-fwprop1 and -fdump-rtl-fwprop2 enable dumping after the two forward propagation passes.
  • -fdump-rtl-gcse1
  • -fdump-rtl-gcse2 โ€” -fdump-rtl-gcse1 and -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 โ€” -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.
  • -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 โ€” -fdump-rtl-sched1 and -fdump-rtl-sched2 enable dumping after the basic block scheduling passes.
  • -fdump-rtl-ree โ€” dumps everything right after sign/zero extension elimination happens ๐Ÿ’…
  • -fdump-rtl-seqabstr โ€” dumps after common sequence discovery, bestie ๐Ÿ”
  • -fdump-rtl-shorten โ€” dumps after branch shortening, so you can see those little branches get cute and compact ๐ŸŒธ
  • -fdump-rtl-sibling โ€” dumps after sibling call optimizations ๐Ÿ‘‘
  • -fdump-rtl-split1, -fdump-rtl-split2, -fdump-rtl-split3, -fdump-rtl-split4, -fdump-rtl-split5 โ€” these five enable dumping after five rounds of instruction splitting. five. rounds. the dedication is real ๐Ÿ˜ญ
  • -fdump-rtl-sms โ€” dumps after modulo scheduling. heads up tho: this pass only runs on some architectures, so don't come for me if your dump is empty ๐Ÿซถ
  • -fdump-rtl-stack โ€” dumps after conversion from GCC's "flat register file" registers to the x87's stack-like registers. this one's x86 variants only, so if you're on literally anything else, nothing happens ๐Ÿ’€
  • -fdump-rtl-subreg1, -fdump-rtl-subreg2 โ€” -fdump-rtl-subreg1 and -fdump-rtl-subreg2 enable dumping after the two subreg expansion passes โœจ
  • -fdump-rtl-unshare โ€” dumps after all rtl has been unshared ๐Ÿ”“
  • -fdump-rtl-vartrack โ€” dumps after variable tracking ๐Ÿ“
  • -fdump-rtl-vregs โ€” dumps after converting virtual registers to hard registers, glow-up complete ๐Ÿ’–
  • -fdump-rtl-web โ€” dumps 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 they always produce empty files. yes bestie, always. empty. it's giving ghost town ๐Ÿ‘ป
  • -da, -fdump-rtl-all โ€” produce all the dumps listed above. the whole buffet ๐Ÿ“

โœจ the little -d letters โœจ

  • -dA โ€” annotates the assembler output with miscellaneous debugging info ๐ŸŽ€
  • -dD โ€” dumps all macro definitions, at the end of preprocessing, on top of the normal output ๐Ÿ“
  • -dH โ€” produces a core dump whenever an error occurs. yes fr fr, an actual core dump. dramatic queen behavior but make it on purpose ๐Ÿ’ฅ
  • -dp โ€” annotates the assembler output with a comment saying which pattern and alternative is used. the length and cost of each instruction get printed too ๐Ÿ’…
  • -dP โ€” dumps the RTL in the assembler output as a comment before each instruction. also turns on -dp annotation, two-for-one ๐Ÿซถ
  • -dx โ€” just generates RTL for a function instead of compiling it. usually used with -fdump-rtl-expand ๐ŸŒฑ

๐Ÿฆ‹ more dump options ๐Ÿฆ‹

  • -fdump-debug โ€” dumps debugging information generated during the debug generation phase ๐Ÿ›
  • -fdump-earlydebug โ€” dumps debugging information generated during the early debug generation phase ๐ŸŒค๏ธ
  • -fdump-noaddr โ€” when doing debugging dumps, suppresses address output. this makes it way 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. iykyk ๐Ÿ”
  • -freport-bug โ€” collects and dumps debug information into a temporary file if an internal compiler error (ICE) occurs. cute little safety net for when things go ๐Ÿ’€
  • -fdump-unnumbered โ€” when doing debugging dumps, suppresses instruction numbers and address output. same energy as above: it makes using diff on debugging dumps for compiler invocations with different options way more feasible, especially with and without -g โœจ
  • -fdump-unnumbered-links โ€” when doing debugging dumps (see the -d option above), suppresses instruction numbers for the links to the previous and next instructions in a sequence ๐Ÿ”—

๐Ÿ’œ ipa dumps ๐Ÿ’œ

  • -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 made by appending a switch-specific suffix to the source file name, and the file gets created in the same directory as the output file. the following dumps are possible:
    • all โ€” enables all inter-procedural analysis dumps ๐Ÿ‘‘
    • cgraph โ€” dumps info about call-graph optimization, unused function removal, and inlining decisions ๐ŸŒณ
    • inline โ€” dump after function inlining ๐Ÿซ‚

also, 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 receipts, bestie ๐Ÿงพ

by default, the dump contains messages about successful optimizations (equivalent to -optimized) together with low-level details about the analysis.


๐ŸŒˆ language dumps ๐ŸŒˆ

  • -fdump-lang โ€” dumps 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 exactly like 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 info. this option is applicable to C++ only. (yes, Elrond. iconic reference, no notes ๐Ÿง)
    • raw โ€” dump the raw internal tree data. this option is applicable to C++ only.

๐ŸŽ€ the rest of the dump fam ๐ŸŽ€

  • -fdump-passes โ€” prints on stderr the list of optimization passes that are turned on and off by the current command-line options. the vibe check for your flags ๐Ÿ’…
  • -fdump-statistics-option โ€” enable and control dumping of pass statistics in a separate file. the file name is made 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 ๐Ÿ“Š
  • -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. the following options are available:
    • address โ€” print the address of each node. usually this is not meaningful since 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 ๐Ÿงฑ
  • details โ€” enable more detailed dumps (not honored by every dump option). also include information from the optimization passes ๐Ÿ”ฌ
  • stats โ€” enable dumping various statistics about the pass (not honored by every dump option) ๐Ÿ“ˆ
  • 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.

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 ๐Ÿ‘‘

to figure out what tree dumps are available, or to find the dump for a pass of interest, follow the steps below, 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 ๐ŸŒธ
  1. 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. bestie this is the whole toolkit ๐Ÿ’…

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. last one wins, no cap โœจ

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. the "aw bestie you almost had it" report ๐Ÿ™ˆ
  • 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 whole buffet ๐Ÿ“

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. ๐Ÿงš (devs only, iykyk)

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. one filename only, the rest get ghosted ๐Ÿ’€

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. do NOT let it overwrite your receipts ๐Ÿ˜ญ

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. order? irrelevant. she ate either way ๐Ÿ’…

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. first come first served, the loop one is just standing there ๐Ÿซถ


  • -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. fr fr, don't build your whole pipeline on this โš ๏ธ

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 output 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. turn the dial up, get more lore ๐ŸŒˆ


  • -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. dev tools, not a vibe for everyday users ๐Ÿ™ˆ
    • -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.
    • -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). same seed, same output, periodt โœจ

The string should be different for every file you compile.


  • -save-temps โ€” okay so this one keeps the "temporary" intermediate files forever instead of ghosting them at the end ๐Ÿ’พ. They get named as auxiliary output files, exactly like -dumpbase and -dumpdir say. And bestie, when you pair it with -x, -save-temps is actually smart enough to not overwrite an input source file that has the same extension as an intermediate file ๐Ÿซถ. Wanna grab that intermediate file anyway? Just rename the source file before you run -save-temps. easy.
  • -save-temps=cwd โ€” literally just -save-temps -dumpdir ./. same energy, one flag โœจ
  • -save-temps=obj โ€” this is -save-temps -dumpdir outdir/, where outdir/ is the directory of the output file you named after -o, directory separators and all. No -o? Then -save-temps=obj just acts like -save-temps=cwd. iconic behavior honestly ๐Ÿ’…
  • -time[=file] โ€” reports the CPU time each subprocess ate during the compilation sequence โฑ๏ธ. For C source files that's the compiler proper and the assembler (plus the linker if linking happens).

No output file specified? The output looks like this:

# cc1 0.12 0.01
# as 0.00 0.01

First number on each line = "user time", aka time spent actually running the program itself. Second number = "system time", aka time spent running operating system routines on the program's behalf. Both in seconds, no cap.

Specify an output file and the output gets appended to that named file instead, looking like this:

0.12 0.01 cc1 <options>
0.00 0.01 as <options>

Now "user time" and "system time" come before the program name, and the options passed to the program get shown too, so later you can tell exactly what file was being compiled and with which options ๐Ÿ‘‘

  • -fdump-final-insns[=file] โ€” dumps the final internal representation (RTL) to file ๐Ÿ—‚๏ธ. If you leave the optional argument out (or if file is .), the dump file name is made by appending .gkd to the dump base name โ€” go check -dumpbase for that.
  • -fcompare-debug[=opts] โ€” if no error happens during compilation, it runs the compiler a second time, adding opts and -fcompare-debug-second to the arguments of that second compilation ๐Ÿ”. It dumps the final internal representation in both compilations and prints an error if they differ. double trouble, but make it diagnostics.

Equal sign omitted? The default -gtoggle is used.

The environment variable GCC_COMPARE_DEBUG, if it's defined, non-empty and nonzero, implicitly enables -fcompare-debug. If GCC_COMPARE_DEBUG is defined to a string starting with a dash, that string is used for opts โ€” otherwise the default -gtoggle is used.

-fcompare-debug=, with the equal sign but no 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 ๐Ÿ™ˆ.

Wanna 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 (not preprocessing, assembly or linking, just so we're clear). Want only a warning instead? Setting GCC_COMPARE_DEBUG to -w%n-fcompare-debug not overridden will do it.

  • -fcompare-debug-second โ€” this option is implicitly passed to the compiler for that second compilation that -fcompare-debug asked for, along with options to silence warnings, and it omits other options that would make the compiler produce output to files or to standard output as a side effect ๐Ÿคซ. Dump files and preserved temporary files get renamed to include the extra .gk extension during the second compilation, so they don't overwrite the ones from the first. thoughtful!

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 โ€” turns off generation of debug info if leaving out this option would generate it, or turns it on at level 2 otherwise ๐Ÿ”„. Where you put this argument in the command line does not matter โ€” it takes effect after all other options are processed, and it only does so once, no matter how many times you give it. Mainly intended to be used with -fcompare-debug ๐Ÿ’–.
  • -fvar-tracking-assignments-toggle โ€” toggles -fvar-tracking-assignments, in the exact same way -gtoggle toggles -g. matchy matchy โœจ
  • -Q โ€” makes the compiler print out each function name as it's compiled, and print some statistics about each pass when it finishes ๐Ÿ“Š.
  • -ftime-report โ€” makes the compiler print some statistics about the time each pass consumed when it finishes โณ.
  • -ftime-report-details โ€” records the time consumed by infrastructure parts separately for each pass ๐Ÿ”.
  • -fira-verbose=n โ€” controls the verbosity of the dump file for the integrated register allocator ๐ŸŽ›๏ธ. Default value is 5. If the value n is greater than or equal to 10, the dump output gets sent to stderr using the same format as n minus 10.
  • -flto-report โ€” prints a report with internal details on how the link-time optimizer is working ๐Ÿ‘€. The contents of this report vary from version to version. It's meant to be useful to GCC developers when processing object files in LTO mode (via -flto). Disabled by default, so you gotta ask for it.
  • -flto-report-wpa โ€” like -flto-report, but only prints 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 the consistency of the (estimated) profile and the effect of individual passes ๐Ÿ“ˆ.
  • -fstack-usage โ€” makes the compiler output stack usage info for the program, per-function ๐Ÿฅž. The dump filename is made by appending .su to the auxname. auxname comes from the name of the output file if it was explicitly specified and it's not an executable โ€” otherwise it's the basename of the source file. Each 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 the function manipulates the stack statically: a fixed number of bytes get allocated for the frame on function entry and released on function exit, and no stack adjustments are otherwise made inside the function. The second field is that fixed number of bytes.

The qualifier dynamic means the function manipulates the stack dynamically: on top of the static allocation described above, stack adjustments happen in the body of the function, for example to push/pop arguments around function calls. 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 on 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 ๐Ÿ˜ญ.

  • -fstats โ€” emits statistics about front-end processing at the end of the compilation ๐Ÿ“‹. Only supported by the C++ front end, and the info is generally only useful to the G++ development team. iykyk.
  • -fdbg-cnt-list โ€” prints the name and the counter upper bound for all debug counters ๐Ÿ”ข.
  • -fdbg-cnt=counter-value-list โ€” sets the internal debug counter lower and upper bound. 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 a 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 ๐ŸŽฏ. And for dbg_cnt(tail_call), true is returned for the first 10 invocations.

  • -print-file-name=library โ€” prints the full absolute name of the library file library that would be used when linking โ€” and does nothing else ๐Ÿ’…. With this option GCC doesn't compile or link anything; it just prints the file name.
  • -print-multi-directory โ€” prints the directory name corresponding to the multilib selected by any other switches present in the command line ๐Ÿ“. That directory is supposed to exist in GCC_EXEC_PREFIX.
  • -print-multi-lib โ€” prints the mapping from multilib directory names to the 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, bestie.
  • -print-multi-os-directory โ€” prints 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 โ€” prints the path to OS libraries for the selected multiarch, relative to some lib subdirectory ๐Ÿงš.
  • -print-prog-name=program โ€” like -print-file-name, but searches for a program such as cpp instead ๐Ÿ”Ž.
  • -print-libgcc-file-name โ€” same as -print-file-name=libgcc.a.

Super useful when you use -nostdlib or -nodefaultlibs but you do want to link with libgcc.a ๐Ÿ’–. You can do:

gcc -nostdlib <files>... `gcc -print-libgcc-file-name`
  • -print-search-dirs โ€” prints the name of the configured installation directory and a list of program and library directories gcc searches โ€” and doesn't do anything else ๐Ÿซถ.

This is useful 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 /.

  • -print-sysroot โ€” prints the target sysroot directory that gets used during compilation. ๐Ÿ’… It's the sysroot you specified either at configure time or with the --sysroot option, possibly with an extra suffix that depends on your compilation options. If no target sysroot is specified, bestie, this option prints literally nothing. Silence. Crickets. ๐Ÿฆ—
  • -print-sysroot-headers-suffix โ€” prints the suffix that gets added to the target sysroot when it's searching for headers, or it throws an error if the compiler wasn't configured with such a suffix โ€” and it does nothing else. Just that one job. ๐Ÿ‘‘
  • -dumpmachine โ€” prints the compiler's target machine (like i686-pc-linux-gnu) โ€” and don't do anything else. That's the whole assignment. โœจ
  • -dumpversion โ€” prints 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). So like, it's giving "how much detail did your build config feel like today". ๐ŸŽ€
  • -dumpfullversion โ€” prints 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 half measures, periodt. ๐Ÿ’–
  • -dumpspecs โ€” prints the compiler's built-in specs โ€” and don't do anything else. (This one gets used when GCC itself is being built, iykyk.) ๐Ÿ”ง

## Machine-Dependent Options ๐Ÿ’ป

Every target machine GCC supports can have its own little set of options โ€” like, so you can compile for a specific processor variant or ABI, or control the optimizations that are special to that machine. By convention, machine-specific option names all start with -m. ๐Ÿท๏ธ

Some configurations of the compiler also support extra target-specific options, usually so it plays nice with other compilers on the same platform. ๐Ÿซถ


### AArch64 Options ๐Ÿฆ‹

These options are defined for AArch64 implementations:

  • -mabi=name โ€” generate code for the specified data model. The permissible values are ilp32 for a SysV-like data model where int, long int and pointers are 32 bits, and lp64 for a 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. Don't mix, bestie, it will NOT end well. ๐Ÿ˜ญ

  • -mbig-endian โ€” generate big-endian code. This is the default when GCC is configured for an aarch64_be-*-* target.
  • -mgeneral-regs-only โ€” generate code that uses only the general-purpose registers. This stops the compiler from using floating-point and Advanced SIMD registers, but it won't impose any restrictions on the assembler. ๐Ÿ™ˆ
  • -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. So smol. ๐Ÿ“
  • -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. โœจ
  • -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. The -mcmodel=large option is incompatible with -mabi=ilp32, -fpic and -fPIC. So don't even try it, it's giving doomed crossover episode. ๐Ÿ’€
  • -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. The 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 base register for reading the canary, and from what offset from that base register. There is no default register or offset, because this is entirely for use within the Linux kernel. ๐Ÿง

  • -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.
  • -mtls-size=size โ€” specify bit size of immediate TLS offsets. Valid values are 12, 24, 32, 48. This option requires binutils 2.26 or newer. โš ๏ธ
  • -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. Little band-aid for a hardware oopsie ๐Ÿฉน
  • -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.
  • -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 precision of reciprocal square root results to about 16 bits for single precision and to 32 bits for double precision. Fast and loose, bestie. ๐Ÿ”ฅ
  • -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 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.
  • -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 precision of division results to about 16 bits for single precision and to 32 bits for double precision.
  • -mtrack-speculation, -mno-track-speculation โ€” enable or disable generation of additional code to track speculative execution through conditional branches. The tracking state can then be used by the compiler when expanding calls to __builtin_speculation_safe_copy to permit a more efficient code sequence to be generated. Very security-core of you. ๐Ÿ•ต๏ธ
  • -moutline-atomics, -mno-outline-atomics โ€” enable or disable calls to out-of-line helpers to implement atomic operations. These helpers will, at runtime, determine if the LSE instructions from ARMv8.1-A can be used; if not, they will use the load/store-exclusive instructions that are present in the base ARMv8.0 ISA.

This option is only applicable when compiling for the base ARMv8.0 instruction set. If using a later revision, e.g. -march=armv8.1-a or -march=armv8-a+lse, the ARMv8.1-Atomics instructions will be used directly. The same applies when using -mcpu= when the selected cpu supports the lse feature. This option is on by default. โœจ

  • -march=name โ€” specify the name of the target architecture and, optionally, one or more feature modifiers. This option has the form -march=arch{+[no]feature}*.

The table below summarizes the permissible values for arch and the features that they enable by default:

  • armv8-a : Armv8-A : Includes by default +fp, +simd
  • armv8.1-a : Armv8.1-A : armv8-a, +crc, +lse, +rdma
  • armv8.2-a : Armv8.2-A : armv8.1-a
  • armv8.3-a : Armv8.3-A : armv8.2-a, +pauth
  • armv8.4-a : Armv8.4-A : armv8.3-a, +flagm, +fp16fml, +dotprod
  • armv8.5-a : Armv8.5-A : armv8.4-a, +sb, +ssbs, +predres
  • armv8.6-a : Armv8.6-A : armv8.5-a, +bf16, +i8mm
  • armv8-r : Armv8-R : armv8-r

The value native is available on native AArch64 GNU/Linux and causes the compiler to pick the architecture of the host system. This option has no effect if the compiler is unable to 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. Where conflicting feature modifiers are specified, the right-most feature is used. ๐Ÿ‘‘

GCC uses name to determine what kind of instructions it can emit when generating assembly code. If -march is specified without either of -mtune or -mcpu also being specified, the code is tuned to perform well across a range of target processors implementing the target architecture.

  • -mtune=name โ€” specify the name of the target processor for which GCC should tune the performance of the code. 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,neoverse-v2, grace, 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, ampere1, ampere1a, cobalt-100 and native.

okay so the big.LITTLE moment ๐Ÿ’… โ€” 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 are all like "bestie, tune me for a big.LITTLE system" โœจ

And the value neoverse-512tvb is the iconic generalist ๐ŸŽ€ โ€” it says tune for Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits per cycle. In other words, it's telling GCC: tune for Neoverse cores that can execute 4 128-bit Advanced SIMD arithmetic instructions a cycle, and that can execute an equivalent number of SVE arithmetic instructions per cycle (2 for 256-bit SVE, 4 for 128-bit SVE). Not me being more general than tuning for a specific core like Neoverse V1 but more specific than the default tuning described below ๐Ÿ˜ญ

Plus, on native AArch64 GNU/Linux systems, the value native tunes performance to the host system. Real talk though: this option does nothing if the compiler can't recognize the processor of the host system ๐Ÿ™ˆ

Where none of -mtune=, -mcpu= or -march= are specified, the code gets tuned to perform well across a range of target processors ๐ŸŒˆ

Important: this option cannot be suffixed by feature modifiers. Periodt.

  • -mcpu=name โ€” tells GCC the name of 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 as those available for -mtune. The permissible values for feature are documented in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Where conflicting feature modifiers are specified, the right-most feature is used ๐Ÿ‘‘

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 for which to tune for performance (as if by -mtune). Where this option is used in conjunction with -march or -mtune, those options take precedence over the appropriate part of this option. the way that it's two options in a trench coatโ€ฆ

-mcpu=neoverse-512tvb is special ๐Ÿ’ซ โ€” it does not refer to a specific core, but instead 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 for -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 in this option are not guaranteed to be consistent across releases ๐Ÿ˜ญ
This option is only intended to be useful when developing GCC. compiler-dev main character energy only, bestie
  • -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 โ€” enable or disable PC-relative literal loads ๐Ÿ’– With this option, literal pools are accessed using a single instruction and emitted after each function. This limits the maximum size of functions to 1MB. This is enabled by default for -mcmodel=tiny.
  • -msign-return-address=scope โ€” picks the function scope on which return address signing gets applied ๐ŸŽ€ Permissible values are none, which disables return address signing; non-leaf, which enables pointer signing for functions which are not leaf functions; and all, which enables pointer signing for all functions. The default value is none.
heads up: this option has been deprecated by -mbranch-protection. it's giving legacy ๐Ÿ’€
  • -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, then 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 ๐Ÿ‘‘

  • -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 allows GCC to make assumptions about the vector length when it is 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 ๐Ÿ˜ญ

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 โ€” enable FP16 fmla extension. This also enables FP16 extensions and floating-point instructions. This option is enabled by default for -march=armv8.4-a. Use of this option with architectures prior to Armv8.2-A is not supported.
  • rcpc โ€” enable the RcPc extension. This does not change code generation from GCC, but is passed on to the assembler, enabling inline asm statements to use instructions from the RcPc extension.
  • dotprod โ€” enable the Dot Product extension. This also enables Advanced SIMD instructions.
  • aes โ€” enable the Armv8-a aes and pmull crypto extension. This also enables Advanced SIMD instructions.
  • sha2 โ€” enable the Armv8-a sha2 crypto extension. This also enables Advanced SIMD instructions.
  • sha3 โ€” enable the sha512 and sha3 crypto extension. This also enables Advanced SIMD instructions. Use of this option with architectures prior to Armv8.2-A is not supported.
  • sm4 โ€” enable the sm3 and sm4 crypto extension. This also enables Advanced SIMD instructions. Use of this option with architectures prior to Armv8.2-A is not supported.
  • profile โ€” enable the Statistical Profiling extension. This option is only to enable the extension at the assembler level and does not affect code generation.
  • rng โ€” enable the Armv8.5-a Random Number instructions. This option is only to enable the extension at the assembler level and does not affect code generation.
  • memtag โ€” enable the Armv8.5-a Memory Tagging Extensions. Use of this option with architectures prior to Armv8.5-A is not supported.
  • sb โ€” enable the Armv8-a Speculation Barrier instruction. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for -march=armv8.5-a.
  • ssbs โ€” enable the Armv8-a Speculative Store Bypass Safe instruction. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for -march=armv8.5-a.
  • predres โ€” enable the Armv8-a Execution and Data Prediction Restriction instructions. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for -march=armv8.5-a.
  • sve2 โ€” enable the Armv8-a Scalable Vector Extension 2. This also enables SVE instructions.
  • sve2-bitperm โ€” enable SVE2 bitperm instructions. This also enables SVE2 instructions.
  • sve2-sm4 โ€” enable SVE2 sm4 instructions. This also enables SVE2 instructions.
  • sve2-aes โ€” enable SVE2 aes instructions. This also enables SVE2 instructions.
  • sve2-sha3 โ€” enable SVE2 sha3 instructions. This also enables SVE2 instructions.
  • tme โ€” enable the Transactional Memory Extension.
  • i8mm โ€” enable 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. This option is enabled by default for -march=armv8.6-a. Use of this option with architectures prior to Armv8.2-A is not supported.
  • f32mm โ€” enable 32-bit Floating point Matrix Multiply instructions. This also enables SVE instructions. Use of this option with architectures prior to Armv8.2-A is not supported.
  • f64mm โ€” enable 64-bit Floating point Matrix Multiply instructions. This also enables SVE instructions. Use of this option with architectures prior to Armv8.2-A is not supported.

okay that was a LOT of modifiers but we ate and left no crumbs ๐Ÿ’… and bestie we are SO not done yet, keep scrolling โœจ

  • bf16 โ€” turns on brain half-precision floating-point instructions ๐Ÿง โœจ and it also switches on Advanced SIMD and floating-point instructions while it's at it. This one is enabled by default for -march=armv8.6-a. Using it with architectures from before Armv8.2-A is not supported ๐Ÿšซ.
  • flagm โ€” enables the Flag Manipulation instructions Extension ๐ŸŽ€
  • pauth โ€” enables the Pointer Authentication Extension ๐Ÿ”

Okay so the tea on the feature deps โ˜•: feature crypto implies aes, sha2, and simd, which implies fp. And conversely, nofp implies nosimd, which implies nocrypto, noaes and nosha2. Chain reaction, bestie ๐Ÿ’….


๐ŸŒธ Adapteva Epiphany Options ๐ŸŒธ

These -m options are defined for Adapteva Epiphany, and yes we're going through every single one:

  • -mhalf-reg-file โ€” don't allocate any register in the range r32...r63 ๐Ÿšซ. That's what lets your code run on hardware variants that simply lack these registers.
  • -mprefer-short-insn-regs โ€” preferentially allocate registers that allow short instruction generation โœจ. Fair warning though: this can increase 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. 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. This is faster than a software comparison, 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. E.g., a value of 8 means that 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 ๐Ÿ’€. Note also that this option changes the ABI; compiling a program with a different stack offset than the libraries have been compiled with generally does not work. This option can be useful if you want to evaluate if a different stack offset would give you better code, but to actually use a different stack offset to build working programs, it is recommended to configure the toolchain with the appropriate --with-stack-offset=num option.
  • -mno-round-nearest โ€” make the scheduler assume that 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 is provided and expected at function call and return time. Making this mode match 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 retained or restored when the function returns, and when it calls other functions. This mode is useful for compiling libraries or other compilation units you might want to incorporate into different programs with different prevailing FPU modes, and the convenience of being able to use a single object file outweighs the size and speed overhead for any extra mode switching that might be needed, compared with what would be needed with a more specific choice of prevailing FPU mode.
  • truncate โ€” this is 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 โ€” this is the mode used for floating-point calculations with round-to-nearest-or-even rounding mode.
  • int โ€” this is 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. Note that 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, no cap:

  • -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 โ€” compile binaries suitable for devices with the SRAM-ECC feature enabled, disabled, or either mode. This feature can be enabled per-process on some devices. The compiled code must match the device mode. The default is any, for devices that support it.
  • -mstack-size=bytes โ€” specify how many bytes of stack space will be requested for each GPU thread (wave-front). Beware that there may be many threads and limited memory available ๐Ÿ‘€. The size of the stack allocation may also have an impact on run-time performance. The default is 32KB when using OpenACC or OpenMP, and 1MB otherwise.
  • -mxnack โ€” compile binaries suitable for devices with the XNACK feature enabled. Some devices always require XNACK and some allow the user to configure XNACK. The compiled code must match the device mode. The default is -mno-xnack. At present this option is a placeholder for support that is not yet implemented ๐Ÿšง.

๐Ÿ’œ ARC Options ๐Ÿ’œ

The following options control the architecture variant for which code is being compiled:

  • -mbarrel-shifter โ€” generate instructions supported by barrel shifter. This is the default unless -mcpu=ARC601 or -mcpu=ARCEM is in effect.
  • -mjli-always โ€” force to call a function using jli_s instruction. This option is valid only for ARCv2 architecture.
  • -mcpu=cpu โ€” set architecture type, register usage, and instruction scheduling parameters for cpu. There are also shortcut alias options available for backward compatibility and convenience. 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 โ€” disable lr and sr instructions from using FPX extension aux registers.
  • -mea โ€” generate extended arithmetic instructions. Currently only divaw, adds, subs, and sat16 are supported. Only valid for -mcpu=ARC700.
  • -mno-mpy โ€” bestie do not generate "mpy"-family instructions for ARC700. This option is deprecated. ๐Ÿ™ˆ
  • -mmul32x16 โ€” generates 32x16-bit multiply and multiply-accumulate instructions. slay โœจ
  • -mmul64 โ€” generates "mul64" and "mulu64" instructions. only valid for -mcpu=ARC600, no exceptions ๐Ÿ’…
  • -mnorm โ€” generates "norm" instructions. this is the default if -mcpu=ARC700 is in effect, so it's giving main character energy by default ๐Ÿ‘‘
  • -mspfp, -mspfp-compact โ€” generates single-precision FPX instructions, tuned for the compact implementation. โœจ
  • -mspfp-fast โ€” generates 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, so don't try it anywhere else ๐Ÿซถ
  • -msoft-float โ€” okay so this option is ignored; it's provided for compatibility purposes only. software floating-point code is emitted by default, and this default can overridden by FPX options: -mspfp, -mspfp-compact, or -mspfp-fast for single precision, and -mdpfp, -mdpfp-compact, or -mdpfp-fast for double precision. literally just there for the vibes ๐Ÿ’€
  • -mswap โ€” generates "swap" instructions. ๐Ÿฆ‹
  • -matomic โ€” this 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.
  • -mdiv-rem โ€” enables "div" and "rem" instructions for ARCv2 cores. ๐Ÿ’ช
  • -mcode-density โ€” enables code density instructions for ARC EM. this option is on by default for ARC HS. ๐ŸŽ€
  • -mll64 โ€” enables double load/store operations for ARC HS cores. โœจ
  • *-mtp-regno=regno* โ€” specify thread pointer register number. ๐Ÿ’…
  • *-mmpy-option=multo* โ€” compile ARCv2 code with a multiplier design option. you can specify the option using either a string or numeric value for multo. wlh1 is the default value. the recognized values are:
    • 0, none โ€” no multiplier available. ๐Ÿ’€
    • 1, w โ€” 16x16 multiplier, fully pipelined. the following instructions are enabled: "mpyw" and "mpyuw".
    • 2, wlh1 โ€” 32x32 multiplier, fully pipelined (1 stage). the following instructions are additionally enabled: "mpy", "mpyu", "mpym", "mpymu", and "mpy_s".
    • 3, wlh2 โ€” 32x32 multiplier, fully pipelined (2 stages). the following instructions are additionally enabled: "mpy", "mpyu", "mpym", "mpymu", and "mpy_s".
    • 4, wlh3 โ€” two 16x16 multipliers, blocking, sequential. the following instructions are additionally enabled: "mpy", "mpyu", "mpym", "mpymu", and "mpy_s".
    • 5, wlh4 โ€” one 16x16 multiplier, blocking, sequential. the following instructions are additionally enabled: "mpy", "mpyu", "mpym", "mpymu", and "mpy_s".
    • 6, wlh5 โ€” one 32x4 multiplier, blocking, sequential. the following instructions are additionally enabled: "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. ๐Ÿ”’
  • *-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. this option is 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. this option is 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. this option is 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. this option is 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 general-purposes registers that the processor automatically saves/restores on interrupt entry and exit. register-range is specified as two registers separated by a dash. the register range always starts with "r0", the upper limit is "fp" register. blink and lp_count are optional. this option is only valid for ARC EM and ARC HS cores. ๐Ÿ”’
  • *-mrgf-banked-regs=number* โ€” specifies the number of registers replicated in second register bank on entry to fast interrupt. fast interrupts are interrupts with the highest priority level P0. these interrupts save only PC and STATUS32 registers to avoid memory transactions during interrupt entry and exit sequences. use this option when you are using fast interrupts in an ARC V2 family processor. permitted values are 4, 8, 16, and 32. ๐Ÿ’…
  • *-mlpc-width=width* โ€” specify the width of the "lp_count" register. valid values for width are 8, 16, 20, 24, 28 and 32 bits. the default width is fixed to 32 bits. if the width is less than 32, the compiler does not attempt to transform loops in your program to use the zero-delay loop mechanism unless it is known that the "lp_count" register can hold the required loop-counter value. depending on the width specified, the compiler and run-time library might continue to use the loop mechanism for various needs. this option defines macro "__ARC_LPC_WIDTH__" with the value of width. โœจ
  • -mrf16 โ€” this option instructs the compiler to generate code for a 16-entry register file. this option defines the "__ARC_RF16__" preprocessor macro. ๐ŸŽ€
  • -mbranch-index โ€” enable use of "bi" or "bih" instructions to implement jump tables. ๐Ÿ”ฅ

the following options are passed through to the assembler, and also define preprocessor macro symbols. ๐Ÿ› ๏ธ

  • -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 following options control how the assembly code is annotated: ๐Ÿ“

  • -misize โ€” annotate assembler instructions with estimated addresses. ๐Ÿ’…
  • -mannotate-align โ€” explain what alignment considerations lead to the decision to make an instruction short or long. ๐Ÿ”

the following options 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. ๐Ÿ“Š

the following options control the semantics of generated code: ๐Ÿ‘‘

  • -mlong-calls โ€” generate calls as register indirect calls, thus providing access to the full 32-bit address range. ๐ŸŒˆ
  • -mmedium-calls โ€” don't use less than 25-bit addressing range for calls, which is the offset available for an unconditional branch-and-link instruction. conditional execution of function calls is suppressed, to allow use of the 25-bit range, rather than the 21-bit range with conditional branch-and-link. this is the default for tool chains built for "arc-linux-uclibc" and "arceb-linux-uclibc" targets. ๐Ÿ’–
  • -G num โ€” bestie, this one says: if some externally-visible data is no bigger than num bytes, plop its definition in a small data section. The default num is 4 for any ARC config, or 8 when we've got double load/store operations. โœจ
  • -mno-sdata โ€” do not generate sdata references. This is the default for toolchains built for arc-linux-uclibc and arceb-linux-uclibc targets.
  • -mvolatile-cache โ€” use ordinarily cached memory accesses for volatile references. This is the default, no cap.
  • -mno-volatile-cache โ€” enable cache bypass for volatile references.

The following options fine tune code generation โ€” yes they really said "fine tune", we're in the โœจartisanalโœจ zone now:

  • -malign-call โ€” do alignment optimizations for call instructions.
  • -mauto-modify-reg โ€” enable the use of pre/post modify with register displacement.
  • -mbbit-peephole โ€” enable bbit peephole2.
  • -mno-brcc โ€” this one disables a target-specific pass in arc_reorg to generate compare-and-branch (brcc) instructions. It has no effect on generation of these instructions driven by the combiner pass. So don't come for it about the combiner, it said what it said. ๐Ÿ’…
  • -mcase-vector-pcrel โ€” use PC-relative switch case tables to enable case table shortening. This is the default for -Os.
  • -mcompact-casesi โ€” enable compact casesi pattern. This is the default for -Os, and only available for ARCv1 cores. This option is deprecated. ๐Ÿซ 
  • -mno-cond-exec โ€” disable the ARCompact-specific pass to generate conditional execution instructions.

Okay so here's the lore: due to delay slot scheduling and interactions between operand numbers, literal sizes, instruction lengths, and the support for conditional execution, the target-independent pass to generate conditional execution is often lacking, so the ARC port has kept a special pass around that tries to find more conditional execution generation opportunities after register allocation, branch shortening, and delay slot scheduling have been done. This pass generally, but not always, improves performance and code size, at the cost of extra compilation time, which is why there is an option to switch it off. If you have a problem with call instructions exceeding their allowable offset range because they are conditionalized, you should consider using -mmedium-calls instead. โœจ noted.

  • -mearly-cbranchsi โ€” enable pre-reload use of the cbranchsi pattern.
  • -mexpand-adddi โ€” expand adddi3 and subdi3 at RTL generation time into add.f, adc etc. This option is deprecated.
  • -mindexed-loads โ€” enable the use of indexed loads. This can be problematic because some optimizers then assume that indexed stores exist, which is not the case. ๐Ÿ˜ญ lowkey a trap.
  • -mlra โ€” enable Local Register Allocation. This is still experimental for ARC, so by default the compiler uses standard reload (i.e. -mno-lra). Experimental, bestie, proceed accordingly.
  • -mlra-priority-none โ€” don't indicate any priority for target registers.
  • -mlra-priority-compact โ€” indicate target register priority for r0..r3 / r12..r15.
  • -mlra-priority-noncompact โ€” reduce 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 are often shortened by using call to a special function in libgcc; this is referred to as a millicode call. As these calls can pose performance issues, and/or cause linking issues when linking in a nonstandard way, this option is provided to turn on or off millicode call generation.
  • -mcode-density-frame โ€” this option enable the compiler to emit enter and leave instructions. These instructions are only valid for CPUs with code-density feature. (Yes, the original says "enable", we're quoting the vibe, not the grammar. ๐ŸŽ€)
  • -mmixed-code โ€” tweak register allocation to help 16-bit instruction generation. This generally has the effect of decreasing the average instruction size while increasing the instruction count. Trade-offs, babes.
  • -mq-class โ€” Ths option is deprecated. Enable q instruction alternatives. This is the default for -Os. (The typo is theirs, and honestly? iconic.)
  • -mRcq โ€” enable Rcq constraint handling. Most short code generation depends on this. This is the default.
  • -mRcw โ€” enable Rcw constraint handling. Most ccfsm condexec mostly depends on this. This is the default.
  • -msize-level=level โ€” fine-tune size optimization with regards to instruction lengths and alignment. The recognized values for level are:
    1. 0 โ€” No size optimization. This level is deprecated and treated like 1.
    2. 1 โ€” Short instructions are used opportunistically.
    3. 2 โ€” In addition, alignment of loops and of code after barriers are dropped.
    4. 3 โ€” In addition, optional data alignment is dropped, and the option Os is enabled.

This defaults to 3 when -Os is in effect. Otherwise, the behavior when this is not set is equivalent to level 1.

  • -mtune=cpu โ€” set instruction scheduling parameters for cpu, overriding any 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 โ€” cost to assume for a multiply instruction, with 4 being equal to a normal instruction.
  • -munalign-prob-threshold=probability โ€” set probability threshold for unaligning branches. When tuning for ARC700 and optimizing for speed, branches without filled delay slot are preferably emitted unaligned and long, unless profiling indicates that the probability for the branch to be taken is below probability. The default is (REG_BR_PROB_BASE/2), i.e. 5000.

The following options are maintained for backward compatibility, but are now deprecated and will be removed in a future release. Gather round, this is the retirement home section ๐Ÿซถ:

  • -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 โ€” Replaced by -mdsp-packa.
  • -mEA โ€” Replaced by -mea.
  • -mmac_24 โ€” Replaced by -mmac-24.
  • -mmac_d16 โ€” Replaced by -mmac-d16.
  • -mspfp_compact โ€” Replaced by -mspfp-compact.
  • -mspfp_fast โ€” Replaced by -mspfp-fast.
  • -mtune=cpu โ€” Values arc600, arc601, arc700 and arc700-xmac for cpu are replaced by ARC600, ARC601, ARC700 and ARC700-xmac respectively. (Yes, lowercase girlies, your time is up. ๐Ÿ’€)
  • -multcost=num โ€” Replaced by -mmultcost.

๐ŸŒˆ ARM Options ๐ŸŒˆ

These -m options are defined for the ARM port. New port, new energy, let's go ๐Ÿฆ‹:

  • -mabi=name โ€” generate code for the specified ABI. Permissible values are: apcs-gnu, atpcs, aapcs, aapcs-linux and iwmmxt.
  • -mapcs-frame โ€” generate a stack frame that is compliant with the ARM Procedure Call Standard for all functions, even if this is not strictly necessary for correct execution of the code. Specifying -fomit-frame-pointer with this option causes the stack frames not to be generated for leaf functions. The default is -mno-apcs-frame. This option is deprecated.
  • -mapcs โ€” this is a synonym for -mapcs-frame and is deprecated.
  • -mthumb-interwork โ€” generate code that supports calling between the ARM and Thumb instruction sets. Without this option, on pre-v5 architectures, the two instruction sets cannot be reliably used inside one program. The default is -mno-thumb-interwork, since slightly larger code is generated when -mthumb-interwork is specified. In AAPCS configurations this option is meaningless.
  • -mno-sched-prolog โ€” prevent the reordering of instructions in the function prologue, or the merging of those instruction with the instructions in the function's body. This means that all functions start with a recognizable set of instructions (or in fact one of a choice from a small set of different function prologues), and this information 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.

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. Fr fr, do not mix them, it will not end cute. ๐Ÿ˜ญ

  • -mgeneral-regs-only โ€” generate code which uses only the general-purpose registers. This will prevent the compiler from using floating-point and Advanced SIMD registers but will not impose any restrictions on the assembler. Compiler said "not my problem" about the assembler ๐Ÿ’…
  • -mlittle-endian โ€” generate code for a processor running in little-endian mode. This is the default for all standard configurations.
  • -mbig-endian โ€” generate code for a processor running in big-endian mode; the default is to compile code for a little-endian processor.
  • -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. 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, armv7-r, armv8-r, armv6-m, armv6s-m, armv7-m, armv7e-m, armv8-m.base, armv8-m.main, armv8.1-m.main, iwmmxt and iwmmxt2.

Also โ€” and bestie, listen, this one's on thin ice ๐ŸงŠ โ€” these next architectures are recognized, but they don't have Thumb execution state support, and support for them is deprecated: armv4.


โœจ extensions, aka the glow-up add-ons ๐Ÿ’…

Okay so a ton of these architectures support extensions. You slap one on by appending +extension to the architecture name. Extension options get processed in order, and the capabilities just accumulate โ€” it's giving stacking buffs in a video game, fr fr.

An extension will also switch on any base extensions it depends on. Like, the +crypto extension will always enable the +simd extension. It's a package deal, no solo acts here.

The one exception to this whole additive situation is extensions prefixed with +no...: โ€” those ones disable the specified option and any other extensions that might depend on that extension being present. Not me hitting the off switch on your whole dependency tree ๐Ÿ˜ญ

So for example:

-march=armv7-a+simd+nofp+vfpv4

is equivalent to writing

-march=armv7-a+vfpv4

because the +simd option is entirely disabled by the +nofp option that follows it. Order matters, bestie. It's a whole timeline situation.

Most extension names are generically named, but what they actually do depends on the architecture you apply them to. Case in point: the +simd option can be applied to both armv7-a and armv8-a, but it'll enable the original ARMv7-A Advanced SIMD (Neon) extensions for armv7-a, and the ARMv8-A variant for armv8-a. Same name, different era, main character energy ๐Ÿ‘‘

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. Heads up: floating-point is not supported by the base ARMv7-M architecture, but it 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.
  • +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.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

  • +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, plus the Dot Product extension. two for one, we love to see it ๐Ÿ’…
    • +crypto โ€” the cryptographic instructions โœจ and bestie, it also turns on the Advanced SIMD and floating-point instructions and the Dot Product extension. bundle deal, no cap.
    • +nocrypto โ€” disable the cryptographic extension. gone. bye ๐Ÿ’€
    • +nofp โ€” disable the floating-point, Advanced SIMD and cryptographic instructions. like, all of it ๐Ÿซถ
    • +i8mm โ€” 8-bit Integer Matrix Multiply instructions. this one also enables the Advanced SIMD and floating-point instructions.
    • +bf16 โ€” Brain half-precision floating-point instructions. also enables the Advanced SIMD and floating-point instructions. ๐Ÿงš
  • armv8.6-a โ€” okay so here's the whole menu for this one ๐Ÿ‘‘
    • +fp16 โ€” the half-precision floating-point data processing instructions. this also enables the Advanced SIMD and floating-point instructions, the Dot Product extension, and the half-precision floating-point fmla extension. it's giving combo meal ๐Ÿ“
    • +simd โ€” the ARMv8.3-A Advanced SIMD and floating-point instructions, plus the Dot Product extension.
    • +crypto โ€” the cryptographic instructions. also enables the Advanced SIMD and floating-point instructions and 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. also enables the Advanced SIMD and floating-point instructions.
    • +bf16 โ€” Brain half-precision floating-point instructions. also enables the Advanced SIMD and floating-point instructions.
  • armv7-r โ€” the roster for this one ๐ŸŒธ
    • +fp.sp โ€” the single-precision VFPv3 floating-point instructions. the extension +vfpv3xd can be used as an alias for this one โœจ
    • +fp โ€” the VFPv3 floating-point instructions with 16 double-precision registers. the extension +vfpv3-d16 can be used as an alias for this one.
    • +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 โ€” the lil set ๐Ÿ’œ
    • +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 โ€” here's what you can toggle ๐ŸŒˆ
    • +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. pick your coprocessor, bestie ๐Ÿ’…
  • armv8-m.main โ€” same energy, slightly different toggles โœจ
    • +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 โ€” the last architecture menu, we made it ๐ŸŽ€
    • +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.

-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, sometimes it just doesn't know ๐Ÿ˜ญ

  • -mtune=name โ€” this one names the target ARM processor GCC should tune the performance of the code for. for some ARM implementations you can get better performance by using it ๐Ÿ‘‘ the permissible names are:
arm7tdmi, arm7tdmi-s, arm710t, arm720t, arm740t, strongarm, strongarm110,
strongarm1100, 0strongarm1110, 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, ares,
cortex-r4, cortex-r4f, cortex-r5, cortex-r7, cortex-r8, cortex-r52,
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.

additionally, this option can specify that GCC should tune the performance of the code for a big.LITTLE system. the permissible names for that 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. โœจ

-mtune=generic-arch specifies that GCC should tune the performance for a blend of processors within architecture arch. the aim is to generate code that run well on the current most popular processors, balancing between optimizations that benefit some CPUs in the range and avoiding performance pitfalls of other CPUs. the effects of this option may change in future GCC versions as CPU models come and go. ๐Ÿฆ‹

-mtune permits the same extension options as -mcpu, but the extension options do not affect the tuning of the generated code.

-mtune=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. ๐Ÿ’€

  • -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 said -march) and the ARM processor type to tune for performance (as if you'd said -mtune). where this option is used alongside -march or -mtune, those options take precedence over the appropriate part of this one. periodt.

many of the supported CPUs implement optional architectural extensions. where that's the case, the architectural extensions are normally enabled by default. if implementations that lack the extension exist, you can use the extension syntax to disable those extensions that have been omitted. for floating-point and Advanced SIMD (Neon) instructions, the settings of -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. iconic behaviour honestly ๐Ÿ’…

permissible names for this option are the same as those for -mtune. ๐Ÿ‘‘

the following extension options are common to the listed CPUs:

  • +nodsp โ€” disable 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. 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. that's a long list bestie, read it twice ๐Ÿ˜ญ
  • +nofp.dp โ€” disables the double-precision component of the floating-point instructions on cortex-r5, cortex-r7, cortex-r8, cortex-r52 and cortex-m7.
  • +nosimd โ€” disables the SIMD (but not floating-point) instructions on generic-armv7-a, cortex-a5, cortex-a7 and cortex-a9.
  • +crypto โ€” turns on the crypto instructions, and it works for 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. that's the whole list bestie, don't @ me ๐Ÿ’…

Also, the generic-armv7-a pseudo target is lowkey special: it defaults to VFPv3 with 16 double-precision registers, and it supports these 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 literally the same as the extensions to -march=armv7-a, so no new lore to learn ๐Ÿซถ

You can also do -mcpu=generic-arch, which is permissible and equals -march=arch -mtune=generic-arch. Peep -mtune for more deets.

And -mcpu=native? That makes the compiler auto-detect the CPU of the build computer. As of rn this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect flops, the option has no effect. it's giving "we tried" ๐Ÿ˜ญ


โœจ -mfpu=name โœจ

This one specifies what floating-point hardware (or hardware emulation) is available on the target. The 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. girlboss shorthand, we love to see it โœจ

The setting auto is the default and it's special โ€” it makes the compiler pick the floating-point and Advanced SIMD instructions based on the settings of -mcpu and -march.

Real talk: if the selected floating-point hardware includes the NEON extension (e.g. -mfpu=neon), floating-point operations are not generated by GCC's auto-vectorization pass unless -funsafe-math-optimizations is also specified. Why? Because NEON hardware does not fully implement the IEEE 754 standard for floating-point arithmetic (in particular denormal values are treated as zero), so using NEON instructions may lead to a loss of precision. precision loss? not the vibe ๐Ÿ’€

You can also set the fpu name at function level by using the target("fpu=") function attributes or pragmas. per-function slay ๐ŸŽ€


โœจ -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 type for you ๐Ÿ™ˆ


โœจ -mstructure-size-boundary=n โœจ

The sizes of all structures and unions get 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.

Specifying a larger number can produce faster, more efficient code, but it 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. messy, honestly ๐Ÿซ 

This option is deprecated. โš ๏ธ

โœจ -mabort-on-noreturn โœจ

Generate a call to the function abort at the end of a noreturn function. It gets executed if the function tries to return. like, you said you weren't gonna return bestie, what happened ๐Ÿ˜ญ


โœจ -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.

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. exceptions on exceptions, the lore runs deep ๐Ÿ‘‘

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. pointers stay unbothered fr fr


โœจ -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. that's on runtime, not us ๐Ÿซก


โœจ -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 the compiler. For single PIC base case, the default is R9 if the target is EABI based or stack-checking is enabled, otherwise the default is R10. defaults doing defaults things ๐Ÿ’…


โœจ -mpic-data-is-text-relative โœจ

Assume that the displacement between the text and data segments is fixed at static link time. This permits using PC-relative addressing operations to access data known to be in the data segment. For non-VxWorks RTP targets, this option is enabled by default. When disabled on such targets, it will enable -msingle-pic-base by default. cascade behavior, iconic โœจ


โœจ -mpoke-function-name โœจ

Write the name of each function into the text section, directly preceding the function prologue. The generated code is similar to this:

             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 performing a stack backtrace, code can inspect 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 that there is a function name embedded immediately preceding this location and has length ((pc[-3]) & 0xff000000). bit math girlies rise ๐Ÿงš


โœจ -mthumb โœจ

โœจ -marm โœจ

Select between generating code that executes in ARM and Thumb states. The default for most configurations is to generate code that executes in ARM state, but the default can be changed by configuring GCC with the --with-mode=state configure option.

You can also override the ARM and Thumb mode for each function by using the target("thumb") and target("arm") function attributes or pragmas. per-function mood swings, valid ๐Ÿฆ‹


โœจ -mflip-thumb โœจ

Switch ARM/Thumb modes on alternating functions. This option is provided for regression testing of mixed Thumb/ARM code generation, and is not intended for ordinary use in compiling code. testing-only bestie, don't ship it โš ๏ธ


โœจ -mtpcs-frame โœจ

Generate a stack frame that is compliant with the Thumb Procedure Call Standard for all non-leaf functions. (A leaf function is one that does not call any other functions.) The default is -mno-tpcs-frame. lone-wolf functions get no special frame treatment ๐Ÿ’…


โœจ -mtpcs-leaf-frame โœจ

Generate a stack frame that is compliant with the Thumb Procedure Call Standard for all leaf functions. (A leaf function is one that does not call any other functions.) The default is -mno-apcs-leaf-frame. yes, the default really is spelled with apcs there, copy it exactly, no cap ๐Ÿ‘€


โœจ -mcallee-super-interworking โœจ

Gives all externally visible functions in the file being compiled an ARM instruction set header which switches to Thumb mode before executing the rest of the function. This allows these functions to be called from non-interworking code. This option is not valid in AAPCS configurations because interworking is enabled by default. already enabled? then this is giving redundant energy ๐Ÿ™ˆ


โœจ -mcaller-super-interworking โœจ

Allows calls via function pointers (including virtual functions) to execute correctly regardless of whether the target code has been compiled for interworking or not. There is a small overhead in the cost of executing a function pointer if this option is enabled. This option is not valid in AAPCS configurations because interworking is enabled by default. small cost, big correctness, the tradeoff of all time โš–๏ธ


โœจ -mtp=name โœจ

Specify 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. The default setting is auto. auto stays winning ๐Ÿ‘‘


โœจ -mtls-dialect=dialect โœจ

Specify the dialect to use 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 provides better performance for shared libraries. The GNU descriptor scheme is compatible with the original scheme, but 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. gnu2 is the glow-up, but it needs the whole squad to update first ๐Ÿ’–


โœจ -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 this restriction, and when -fpic or -fPIC is specified. This option conflicts with -mslow-flash-data. pick a lane bestie, they cannot coexist ๐Ÿ’€


โœจ -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 these instructions. This option is enabled by default when -mcpu=cortex-m3 is specified. data corruption? absolutely not, we're fixing that on sight ๐Ÿ”ฅ


โœจ -munaligned-access โœจ

โœจ -mno-unaligned-access โœจ

Enables (or disables) reading and writing of 16- and 32- bit values from addresses that are not 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 is not enabled then words in packed data structures are accessed a byte at a time. slow and steady, one byte at a time ๐Ÿ“

  • -munaligned-access, -mno-unaligned-access โ€” controls whether the compiler generates code that does unaligned accesses to memory. This sets the ARM attribute Tag_CPU_unaligned_access in the object file you get out, true or false, matching whichever of these you picked. And bestie, if unaligned access is enabled, the preprocessor symbol __ARM_FEATURE_UNALIGNED gets defined too. โœจ
  • -mneon-for-64bits โ€” deprecated, does literally nothing. It's giving ghost town. ๐Ÿ’€
  • -mslow-flash-data โ€” assume that loading data from flash is slower than fetching instructions. So it minimizes literal loads for better performance, periodt. Only supported when you're compiling for ARMv7 M-profile, and it's off by default. Also? It conflicts with -mword-relocations. Pick a lane. ๐Ÿ™ˆ
  • -masm-syntax-unified โ€” assume your inline assembler is using unified asm syntax. Default is currently off, which implies divided syntax. Heads up: this option has no impact on Thumb2. But that may change in future releases of GCC. And divided syntax should be considered deprecated. ๐Ÿ‘‘
  • -mrestrict-it โ€” restricts generation of IT blocks so they conform to the rules of ARMv8-A. IT blocks can only contain a single 16-bit instruction from a select set of instructions. This one 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. iykyk. ๐Ÿงš
  • -mverbose-cost-dump โ€” enables verbose cost model dumping in the debug dump files. Provided for use in debugging the compiler. ๐Ÿ”ฅ
  • -mpure-code โ€” do not allow constant data to be placed in code sections. Additionally, when compiling for ELF object format, give all text sections the ELF processor-specific section attribute SHF_ARM_PURECODE. Only available when generating non-pic code for M-profile targets. โœจ
  • -mcmse โ€” generate secure code as per the ARMv8-M Security Extensions: Requirements on Development Tools Engineering Specification, which you can find at <https://developer.arm.com/documentation/ecm0359818/latest/>. ๐Ÿ›ก๏ธ
  • -mfix-cmse-cve-2021-35465 โ€” mitigate 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. And if you need to turn the mitigation off? The option -mno-fix-cmse-cve-2021-35465 does exactly that. ๐Ÿ”’
  • -mfdpic, -mno-fdpic โ€” select 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, bestie.
Note that static linking is not supported, because it would still involve the dynamic linker when the program self-relocates. If that behavior is acceptable to you, use -static and -Wl,-dynamic-linker options.

The opposite -mno-fdpic option is useful (and required, fr fr) 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:

  • -mmcu=mcu โ€” specify Atmel AVR instruction set architectures (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" devices with 16 KiB up to 64 KiB of program memory and with the MOVW instruction. mcu = attiny167, attiny1634, atmega8u2, atmega16u2, atmega32u2, ata5505, ata6617c, ata664251, at90usb82, at90usb162.
  • avr4 โ€” "Enhanced" devices with up to 8 KiB of program memory. 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. 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, 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. mcu = atmega128, atmega128a, atmega128rfa1, atmega128rfr2, atmega1280, atmega1281, atmega1284, atmega1284p, atmega1284rfr2, at90can128, at90usb1286, at90usb1287.
  • avr6 โ€” "Enhanced" devices with 3-byte PC, i.e. with more than 128 KiB of program memory. 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. 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. 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. mcu = atxmega128a1, atxmega128a1u, atxmega128a4u.
  • avrtiny โ€” "TINY" Tiny core devices with 512 B up to 4 KiB of program memory. mcu = attiny4, attiny5, attiny9, attiny10, attiny20, attiny40.
  • avr1 โ€” this ISA is implemented by the minimal AVR core and supported for assembler only. mcu = attiny11, attiny12, attiny15, attiny28, at90s1200.
  • -mabsdata โ€” assume that all data in static storage can be accessed by LDS / STS instructions. This option has only an effect on reduced Tiny devices like ATtiny40. See also the absdata AVR Variable Attributes, variable attribute. ๐Ÿ’ซ
  • -maccumulate-args โ€” accumulate outgoing function arguments and acquire/release the needed stack space for outgoing function arguments once, in the function prologue/epilogue. Without this option, outgoing arguments are pushed before calling a function and popped afterwards. ๐Ÿซถ

Popping the arguments after the function call can be expensive on AVR, so accumulating the stack space might lead to smaller executables, because arguments need not be removed from the stack after such a function call. ๐Ÿ’ธ

This option can lead to reduced code size for functions that perform several calls to functions that get their arguments on the stack โ€” like calls to printf-like functions. iykyk ๐Ÿซถ


  • -mbranch-cost=cost โ€” Sets the branch costs for conditional branch instructions to cost. Reasonable values for cost are small, non-negative integers. The default branch cost is 0. ๐Ÿ’…
  • -mcall-prologues โ€” Function prologues/epilogues get expanded as calls to the appropriate subroutines instead of being inlined. Code size is smaller. tiny but mighty โœจ
  • -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 or not a specific value for bits is allowed depends on the --with-double= and --with-long-double= configure options (https://gcc.gnu.org/install/configure.html#avr), and the same applies for the default values of the options. ๐ŸŽ€
  • -mgas-isr-prologues โ€” Interrupt service routines (ISRs) may use the __gcc_isr pseudo instruction supported by GNU Binutils. If this option is on, the feature can still be disabled for individual ISRs by means of the AVR Function Attributes no_gccisr function attribute. This feature is activated per default if optimization is on (but not with -Og, see Optimize Options), and if GNU Binutils support PR21683 (https://sourceware.org/PR21683). ๐Ÿ”ฅ
  • -mint8 โ€” Assume int to be 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. > Please note that this option does not conform to the C standards, but it results in smaller code size. โš ๏ธ
  • -mmain-is-OS_task โ€” Do not save registers in main. The effect is the same like attaching attribute AVR Function Attributes OS_task to main. It is activated per default if optimization is on. ๐Ÿ’ค
  • -mn-flash=num โ€” Assume that 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. ๐Ÿ˜ฌ
  • -mrelax โ€” Try to replace CALL resp. JMP instruction by 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 are not known before code is located. Therefore, the assembler code generated by the compiler is the same, but the instructions in the executable may differ from instructions in the assembler code. ๐Ÿ‘€

Relaxing must be turned on if linker stubs are needed, see the section on EIND and linker stubs below. ๐Ÿ‘‘

  • -mrmw โ€” Assume that 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. ๐Ÿ™ˆ

  • -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. ๐Ÿ’…

This option is used internally by the compiler to select and build multilibs for architectures avr2 and avr25. These 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 if the device or architecture has an 8-bit stack pointer and thus no SPH register or not. ๐Ÿงš

  • -mstrict-X โ€” Use address register X in a way proposed by the hardware. This means that X is only used in indirect, post-increment or pre-decrement addressing. ๐Ÿ’ฏ

Without this option, the X register may be used in the same way as Y or Z, which then is emulated by additional instructions. For example, loading a value with X+const addressing with a small non-negative const < 64 to 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. ๐Ÿฃ
  • -mfract-convert-truncate โ€” Allow to use truncation instead of rounding towards zero for fractional fixed-point types. โœ‚๏ธ
  • -nodevicelib โ€” Don't link against AVR-LibC's device specific library lib<mcu>.a. ๐Ÿšซ
  • -nodevicespecs โ€” Don't add -specs=device-specs/specs-mcu to the compiler driver's command line. The user takes responsibility for supplying the sub-processes like compiler proper, assembler and linker with appropriate command line options. This means that the user has to supply her private device specs file by means of -specs=path-to-specs-file. There is no more need for option -mmcu=mcu. ๐Ÿซก

This option can also serve as a replacement for the older way of specifying custom device-specs files that needed -B some-path to point to a directory which contains a folder named device-specs which contains a specs file named specs-mcu, where mcu was specified by -mmcu=mcu. ๐Ÿ“

  • -Waddr-space-convert โ€” Warn about conversions between address spaces in the case where the resulting address space is not contained in the incoming address space. ๐Ÿ“ฃ
  • -Wmisspelled-isr โ€” Warn if the ISR is misspelled, i.e. without __vector prefix. Enabled by default. โœ๏ธ

โœจ EIND and Devices with More Than 128 Ki Bytes of Flash โœจ

Pointers in the implementation are 16 bits wide. The address of a function or label is represented as word address so that indirect jumps and calls can target any code address in the range of 64 Ki words. ๐Ÿง 

In order to facilitate indirect jump on devices with more than 128 Ki bytes of program memory space, there is a special function register called EIND that serves as the most significant part of the target address when EICALL or EIJMP instructions are used. ๐Ÿ‘‘

Indirect jumps and calls on these devices are handled as follows by the compiler, and are subject to some limitations:

  • The compiler never sets EIND. ๐Ÿ™…
  • 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. ๐Ÿ˜ค
  • For indirect calls to functions and computed goto, the linker generates stubs. Stubs are jump pads, sometimes also called trampolines. Thus, the indirect call/jump jumps to such a stub. The stub contains a direct jump to the desired address. ๐Ÿ›
  • Linker relaxation must be turned on so that 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. ๐Ÿ’€
  • The default linker script is arranged for code with EIND = 0. If 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 is legitimate 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. ๐Ÿ“Œ

  • Stubs are generated automatically by the linker if the following 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 so 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 be linked with -Wl,--defsym,func_4=0x4. Alternatively, func_4 can be defined in the linker script. ๐Ÿ”—


๐ŸŒธ Handling of the RAMPD, RAMPX, RAMPY and RAMPZ Special Function Registers ๐ŸŒธ

Some AVR devices support memories way bigger than that 64 KiB range you can reach with 16-bit pointers, bestie. And to get at memory outside that 64 KiB range, the content of a "RAMP" register gets used as the high part of the address ๐Ÿ’ซ โ€” so the "X", "Y", "Z" address register gets concatenated with the "RAMPX", "RAMPY", "RAMPZ" special function register, respectively, to build a wide address. And similarly, "RAMPD" is used together with direct addressing. Teamwork, honestly ๐Ÿซถ

  • The startup code initializes the "RAMP" special function registers with zero.
  • If a AVR Named Address Spaces, 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.
  • 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. Not optional, bestie, that's the rule ๐Ÿ’…

โœจ AVR Built-in Macros โœจ

GCC defines several built-in macros so that your user code can vibe-check 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__" โ€” Build-in macro that resolves to a decimal number that identifies the architecture and 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. Fancy ๐Ÿ’…
  • "__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. Slay.
  • "__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 that 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 8-bit respectively 16-bit register by the compiler. The definition of these macros is affected by -mtiny-stack.
  • "__AVR_HAVE_SPH__"
  • "__AVR_SP8__" โ€” The device has the SPH (high part of stack pointer) special function register or 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. 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 as 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 resp. 64-bit double. 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. 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. That's it, bestie, that's all you get ๐Ÿ˜ญ
  • -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. Free real estate โœจ
  • -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 โ€” bestie we're assuming the program is arbitrarily large. this is the default, no cap. ๐Ÿ’…
  • -mstack-check-l1 โ€” do the stack checking using info the uClinux kernel dropped into L1 scratchpad memory. iconic teamwork fr.
  • -mid-shared-library โ€” generate code that supports shared libraries via the library ID method. this lets you do execute in place AND shared libraries in an environment with no virtual memory management, which is giving "we make it work anywhere" energy. this option implies -fPIC. with a bfin-elf target, it implies -msim. โœจ
  • -mno-id-shared-library โ€” generate code that does not assume ID-based shared libraries are being used. this is the default, lowkey the chill option. ๐ŸŽ€
  • -mleaf-id-shared-library โ€” generate code that supports shared libraries via the library ID method, but assumes this library or executable won't link against any other ID shared libraries. that lets the compiler use faster code for jumps and calls. speed, slay. ๐Ÿ”ฅ
  • -mno-leaf-id-shared-library โ€” do not assume 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. so likeโ€ฆ 0 is the moment, the rest is just committing. ๐Ÿ’€
  • -msep-data โ€” generate code that lets the data segment live 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. main character memory layout. ๐Ÿ‘‘
  • -mno-sep-data โ€” generate code that assumes 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. iykyk. ๐Ÿฆ‹

  • -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. it's giving "rules are more like guidelines" ngl. ๐Ÿ’…
  • -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. periodt.
  • -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. so many models bestie, pick your vibe. ๐ŸŒˆ

  • -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. do not skip that step bestie. ๐Ÿ™ˆ
  • -micplb โ€” assume that ICPLBs are enabled at run time. this has an effect on certain anomaly workarounds. for Linux targets, the default is to assume ICPLBs are enabled; for standalone applications the default is off. ๐ŸŒธ

โœจ C6X Options โœจ

  • -march=name โ€” this specifies the name of the target architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. permissible names are: c62x, c64x, c64x+, c67x, c67x+, c674x. choose your fighter. ๐Ÿ‘‘
  • -mbig-endian โ€” generate code for a big-endian target. ๐Ÿ˜
  • -mlittle-endian โ€” generate code for a little-endian target. this is the default, the tiny icon. ๐Ÿญ
  • -msim โ€” choose startup files and linker script suitable for the simulator. ๐Ÿงš
  • -msdata=default โ€” put small global and static data in the .neardata section, which is pointed to by register B14. put small uninitialized global and static data in the .bss section, which is adjacent to the .neardata section. put small read-only data into the .rodata section. the corresponding sections used for large pieces of data are .fardata, .far and .const. small stuff gets the cozy spot, big stuff goes far. ๐Ÿซถ
  • -msdata=all โ€” put all data, not just small objects, into the sections reserved for small data, and use addressing relative to the B14 register to access them. everyone's small now, we don't gatekeep. ๐Ÿ’…
  • -msdata=none โ€” make no use of the sections reserved for small data, and use absolute addresses to access all data. put all initialized global and static data in the .fardata section, and all uninitialized data in the .far section. put all constant data into the .const section. absolute addresses only, no shortcuts. โญ

๐Ÿ’œ CRIS Options ๐Ÿ’œ

these options are defined specifically for the CRIS ports.

  • -march=architecture-type
  • -mcpu=architecture-type โ€” generate code for the specified architecture. the choices for architecture-type are v3, v8 and v10 for respectively ETRAX 4, ETRAX 100, and ETRAX 100 LX. default is v0. ๐ŸŽ€
  • -mtune=architecture-type โ€” tune to architecture-type everything applicable about the generated code, except for the ABI and the set of available instructions. the choices for architecture-type are the same as for -march=architecture-type. same menu, different intent bestie. ๐ŸŒธ
  • -mmax-stack-frame=n โ€” warn when the stack frame of a function exceeds n bytes. it's giving "we're watching you" energy. ๐Ÿ˜ญ
  • -metrax4
  • -metrax100 โ€” the options -metrax4 and -metrax100 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 active by default. ๐Ÿ’–
  • -mpdebug โ€” enable CRIS-specific verbose debug-related information in the assembly code. this option also has the effect of turning off the #NO_APP formatted-code indicator to the assembler at the beginning of the assembly file. tea spilled, literally. ๐Ÿซ–
  • -mcc-init โ€” do not use condition-code results from previous instruction; always emit compare and test instructions before use of condition codes. fresh check every single time, no leftovers. ๐Ÿ“
  • -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 (no- options) arrange (eliminate arrangements) for 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. alignment glow-up, but the ABI stays untouched. ๐Ÿ’…
  • -m32-bit
  • -m16-bit
  • -m8-bit โ€” similar to the stack- data- and const-align options above, these options arrange for 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 which set up the stack frame are omitted and no return instructions or return sequences are generated in the code.
use this option only together with visual inspection of the compiled code: no warnings or errors are generated when call-saved registers must be saved, or storage for local variables needs to be allocated. bestie please look at your output, it will not warn you. ๐Ÿ˜ญ
  • -melf โ€” legacy no-op option. it's giving "i'm here but i do nothing", honestly relatable. ๐Ÿ’€
  • -sim โ€” this option 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 pass linker options to locate initialized data at 0x40000000 and zero-initialized data at 0x80000000. โœจ

๐ŸŽ€ CR16 Options ๐ŸŽ€

these options are defined specifically for the CR16 ports.

  • -mmac โ€” enable the use of multiply-accumulate instructions. disabled by default. ๐ŸŒธ
  • -mcr16cplus
  • -mcr16c โ€” generate code for CR16C or CR16C+ architecture. CR16C+ architecture is default. ๐Ÿ‘‘
  • -msim โ€” links the library libsim.a which is in compatible with simulator. applicable to ELF compiler only. ๐Ÿฆ‹
  • -mint32 โ€” choose integer type as 32-bit wide. thicc ints. ๐Ÿ’…
  • -mbit-ops โ€” generates sbit/cbit instructions for bit manipulations. bit by bit, iconic. โญ
  • -mdata-model=model โ€” choose a data model. the choices for model are near, far or medium. medium is default. however, far is not valid with -mcr16c, as the CR16C architecture does not support the far data model. know the limits bestie. ๐Ÿ˜ญ

๐ŸŒˆ C-SKY Options ๐ŸŒˆ

GCC supports 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. pick your era, the default is the newest vibe. ๐Ÿ’–
  • -mcpu=cpu โ€” picks the C-SKY target processor, bestie. Valid values for cpu are a whole entire menu:
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.
  • -mbig-endian, -EB, -mlittle-endian, -EL โ€” pick big- or little-endian code. The default is little-endian. ๐Ÿฆ‹
  • -mfloat-abi=name โ€” says which floating-point ABI to use. Permissible values are: soft, softfp and hard.
    • Saying soft makes GCC spit out output containing library calls for floating-point operations.
    • softfp lets it generate 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.
    • The default depends on the specific target configuration.
Heads up, queen: 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. Periodt.
  • -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 โ€” selects 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 โ€” enables 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. Like, no -mistack, no interrupt magic. ๐Ÿ’…
  • -mmp โ€” enable multiprocessor instructions; the default is off.
  • -mcp โ€” enable coprocessor instructions; the default is off.
  • -mcache โ€” enable coprocessor instructions; the default is off.
  • -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 options 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 to allow use of 16-bit instructions. 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 is 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 required for correct code generation on CK801 and CK802, and is 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 โ€” permit scheduling of function prologue and epilogue sequences.
Okay so this one is spicy ๐ŸŒถ๏ธ: using -msched-prolog can result in code that is not compliant with the C-SKY V2 ABI prologue requirements, and that cannot be debugged or backtraced. It is disabled by default. So likeโ€ฆ be careful, bestie.
  • -msim โ€” links the library libsemi.a, which is compatible with the simulator. Applicable to ELF compiler only.

๐ŸŽ Darwin Options ๐ŸŽ

These options are defined for all architectures running the Darwin operating system.

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; it does so by running the compiler or linker multiple times and joining the results together with lipo. ๐Ÿ˜ฎโ€๐Ÿ’จ

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. The -force_cpusubtype_ALL option can be used to override this.

The Darwin tools vary in their behavior when presented with an ISA mismatch:

  • The assembler, as, only permits instructions to be used that are valid for the subtype of the file it is generating, so you cannot put 64-bit instructions in a ppc750 object file.
  • The linker for shared libraries, /usr/bin/libtool, fails and prints an error if asked to create a shared library with a less restrictive subtype than its input files (for instance, trying to put a ppc970 object file in a ppc7400 library).
  • The linker for executables, ld, quietly gives the executable the most restrictive subtype of any of its input files.
  • -Fdir โ€” add the framework directory dir to the head of the list of directories to be searched for header files. These directories are interleaved with those specified by -I options and are scanned in a left-to-right order.
    • 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 is in 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 is issued if this is violated. Currently a subframework cannot have subframeworks; in the future, the mechanism may be extended to support this. The standard frameworks can be found 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.
  • -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 โ€” emit debugging information for symbols that are used. For stabs debugging format, this enables -feliminate-unused-debug-symbols. This is by default ON.
  • -gfull โ€” emit debugging information for all symbols and types.
  • -fconstant-cfstrings โ€” the -fconstant-cfstrings is an alias for -mconstant-cfstrings.
  • -mconstant-cfstrings โ€” when the NeXT runtime is being used (the default on these systems), override any -fconstant-string-class setting and cause @"..." literals to be laid out as constant CoreFoundation strings.
  • -mmacosx-version-min=version โ€” the earliest version of MacOS X that this executable will run on is version. Typical values supported for version include 12, 10.12, and 10.5.8.
    • 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.
  • -mkernel โ€” enable kernel development mode. 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 โ€” override 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. It's giving "commit to the bit" energy, fr fr. ๐Ÿ˜ญ
  • -mfix-and-continue, -ffix-and-continue, -findirect-data โ€” generate code suitable for fast turnaround development, such as to allow 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 โ€” cause the errors having to do with files that have the wrong architecture to be fatal.
  • -bind_at_load โ€” marks the output file so the dynamic linker binds all undefined references the second the file gets loaded or launched. no lazy binding era, bestie.
  • -bundle โ€” produces a Mach-o bundle format file. wanna know more? man ld(1), she explains it ๐Ÿ’…
  • -bundle_loader executable โ€” tells it which executable is gonna load the build output file we're linking. again, man ld(1) has the tea โ˜•
  • -dynamiclib โ€” pass this and GCC makes a dynamic library instead of an executable when linking, using the Darwin libtool command. iconic behaviour tbh.
  • -force_cpusubtype_ALL โ€” makes GCC's output file have the ALL subtype instead of whatever the -mcpu or -march option was controlling. not me overriding the vibe check ๐Ÿ˜ญ
  • -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 โ€” okay so ALL of these get passed straight to the Darwin linker, and the Darwin linker man page describes them in detail. that's the whole vibe. iykyk ๐Ÿฆ‹

๐ŸŒˆ DEC Alpha Options ๐ŸŒˆ

these -m options are defined for the DEC Alpha implementations, and yes she's vintage but she still ate ๐Ÿ’œ

โœจ the floaty ones โœจ

  • -mno-soft-float
  • -msoft-float โ€” use (or don't use) the hardware floating-point instructions for floating-point operations. when -msoft-float is specified, functions in libgcc.a are used to do floating-point operations. and like โ€” unless those routines get replaced by stuff that emulates floating-point ops, or compiled so they call such emulation routines, these routines issue floating-point operations. so if you're compiling for an Alpha with no floating-point operations, you must make sure the library is built so it doesn't call them. no cap.
heads up bestie: Alpha implementations without floating-point operations are still required to have floating-point registers. yeah. that's just how she 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 get passed in integer registers as if they were integers, and floating-point results get 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. periodt.

a typical use of this option is building a kernel that doesn't use โ€” and therefore doesn't need to save and restore โ€” any floating-point registers. main character kernel energy fr fr.

  • -mieee โ€” the Alpha architecture implements floating-point hardware optimized for maximum performance. it's mostly compliant with the IEEE floating-point standard, but for full compliance you need software assistance. this option generates fully IEEE-compliant code except that the inexact-flag is not maintained (see below, bestie). turn this on and the preprocessor macro _IEEE_FP is defined during compilation. the resulting code is less efficient but can correctly support denormalized numbers and exceptional IEEE values like 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 this on makes the generated code implement fully-compliant IEEE math. and on top of _IEEE_FP, _IEEE_FP_EXACT is defined as a preprocessor macro. on some Alpha implementations the resulting code may execute significantly slower than the default code. since there's 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. ๐Ÿ’€

๐ŸŽ€ trap & rounding girlies ๐ŸŽ€

  • *-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 โ€” this is the default (normal) setting. the only traps that are enabled are the ones that can't be disabled in software (e.g., division by zero trap).
    • u โ€” in addition to the traps enabled by n, underflow traps are enabled as well.
    • su โ€” like u, but the instructions are marked to be safe for software completion (see Alpha architecture manual for the details, bestie).
    • sui โ€” like su, but inexact traps are enabled as well.
  • *-mfp-rounding-mode=rounding-mode* โ€” selects the IEEE rounding mode. other Alpha compilers call this option -fprm rounding-mode. the rounding-mode can be one of:
    • n โ€” normal IEEE rounding mode. floating-point numbers are rounded towards the nearest machine number, or towards the even machine number in case of a tie.
    • m โ€” round towards minus infinity.
    • c โ€” chopped rounding mode. floating-point numbers are rounded towards zero.
    • d โ€” dynamic rounding mode. a field in the floating-point control register (fpcr, see Alpha architecture reference manual) controls the rounding mode in effect. the C library initializes this register for rounding towards plus infinity. so unless your program modifies the fpcr, d corresponds to round towards plus infinity. ๐Ÿ’…
  • *-mtrap-precision=trap-precision* โ€” in the Alpha architecture, floating-point traps are imprecise. meaning: without software assistance it's literally impossible to recover from a floating trap, and program execution normally needs to be terminated. GCC can generate code that assists operating system trap handlers in determining the exact location that caused a floating-point trap. depending on what an application needs, you can pick different levels of precision:
    • p โ€” program precision. this is the default and means a trap handler can only identify which program caused a floating-point exception.
    • f โ€” function precision. the trap handler can determine the function that 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 provide the equivalent options called -scope_safe and -resumption_safe. ๐Ÿฆ‹

  • -mieee-conformant โ€” marks the generated code as IEEE conformant. 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 thing. ๐ŸŽ€
  • -mbuild-constants โ€” normally GCC examines 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 require GCC to construct all integer constants using code, even if it takes more instructions (the maximum is six).

you typically use this option to build a shared library dynamic loader. itself a shared library, it must relocate itself in memory before it can find the variables and constants in its own data segment. self-relocating queen ๐Ÿ‘‘

๐ŸŒธ instruction set vibes ๐ŸŒธ

  • -mbwx
  • -mno-bwx
  • -mcix
  • -mno-cix
  • -mfix
  • -mno-fix
  • -mmax
  • -mno-max โ€” indicate whether GCC should generate code to use the optional BWX, CIX, FIX and MAX instruction sets. the default is to use the instruction sets supported by the CPU type specified via -mcpu= option, or that of the CPU on which GCC was built if none is specified. slay.
  • -mfloat-vax
  • -mfloat-ieee โ€” generate code that uses (does not use) VAX F and G floating-point arithmetic instead of IEEE single and double precision.
  • -mexplicit-relocs
  • -mno-explicit-relocs โ€” older Alpha assemblers provided no way to generate symbol relocations except via assembler macros. and using those macros doesn't 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 capabilities of the assembler when it's built and sets the default accordingly.
  • -msmall-data
  • -mlarge-data โ€” when -mexplicit-relocs is in effect, static data is accessed via gp-relative relocations. when -msmall-data is used, 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 size of the small data area to 64KB, but lets the variables be directly accessed via a single instruction. iconic.

the default is -mlarge-data. with this option the data area is limited to just below 2GB. programs that require 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. periodt. ๐Ÿ’–

  • -msmall-text, -mlarge-text โ€” okay so with -msmall-text the compiler is like "bestie, I'm assuming the code of the whole entire program (or shared library) fits in 4MB", which means it's reachable with a branch instruction ๐Ÿ’…. And when -msmall-data is used, the compiler can assume that all local symbols share the same $gp value, which cuts the number of instructions a function call needs from 4 down to 1. glow up fr.

The default is -mlarge-text.

  • -mcpu=cpu_type โ€” sets the instruction set and the instruction scheduling parameters for machine type cpu_type. You can drop either the EV style name or the matching chip number, your choice ๐ŸŽ€. GCC supports scheduling parameters for the EV4, EV5 and EV6 family of processors, and it picks the default instruction-set values from whatever processor you name. If you don't specify a processor type at all, GCC just defaults to the processor it was built on.

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. Heads up tho: -mcpu=native has no effect if GCC doesn't recognize the processor ๐Ÿ™ˆ.

  • -mtune=cpu_type โ€” this one sets only the instruction scheduling parameters for machine type cpu_type. The instruction set stays exactly as it was, no touchy โœ‹.

Native toolchains also support the value native, which selects the best architecture option for the host processor. And again, -mtune=native has no effect if GCC doesn't recognize the processor.

  • -mmemory-latency=time โ€” sets the latency the scheduler should assume for typical memory references as seen by the application. And bestie, this number is highly dependent on the memory access patterns your app uses and the size of the external cache on the machine. very much a vibe check per-machine situation.

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 targeted.
  • -mkernel=version โ€” specifies the minimum version of the kernel that will run the compiled program. GCC uses this version to figure out 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 ๐Ÿ’….
  • -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.

  • -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. so, y'know, only if they actually do ๐Ÿ˜ญ.
  • -mno-lsim โ€” assume that runtime support has been provided and so there is no need to include the simulator library (libsim.a) on the linker command line.

๐Ÿฆ‹ FT32 Options ๐Ÿฆ‹

These options are defined specifically for the FT32 port.

  • -msim โ€” specifies that the program will be run on the simulator. This causes an alternate runtime startup and library to be linked.
You must not use this option when generating programs that will run on real hardware; you must provide your own runtime library for whatever I/O functions are needed. no cap, that's a real requirement ๐Ÿซถ.
  • -mlra โ€” enable Local Register Allocation. This is still experimental for FT32, so by default the compiler uses standard reload.
  • -mnodiv โ€” do not use div and mod instructions.
  • -mft32b โ€” enable use of the extended instructions of the FT32B processor.
  • -mcompress โ€” compress all code using the Ft32B code compression scheme.
  • -mnopm โ€” do not generate code that reads program memory.

โœจ FRV Options โœจ

  • -mgpr-32 โ€” only use the first 32 general-purpose registers.
  • -mgpr-64 โ€” use all 64 general-purpose registers.
  • -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.
  • -msoft-float โ€” use library routines for floating-point operations.
  • -malloc-cc โ€” dynamically allocate condition code registers.
  • -mfixed-cc โ€” do not try to dynamically allocate condition code registers, only use "icc0" and "fcc0".
  • -mdword โ€” change 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 โ€” select 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. With a bfin-elf target, this option implies -msim.
  • -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. It's enabled by default if 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 โ€” enable 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.
  • -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, literally never, it's giving "internal plumbing" ๐Ÿ”ง.
  • -mlinked-fp โ€” follow 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 โ€” use indirect addressing to call functions outside the current compilation unit. This allows the functions to be placed anywhere within the 32-bit address space.
  • -malign-labels โ€” try to align labels to an 8-byte boundary by inserting NOPs into the previous packet. This option only has an effect when VLIW packing is enabled. It doesn't create new packets; it merely adds NOPs to existing ones.
  • -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 โ€” enable the use of conditional-move instructions (default).

This switch is mainly for debugging the compiler and will likely be removed in a future version.

  • -mno-cond-move โ€” disable the use of conditional-move instructions.

This switch is mainly for debugging the compiler and will likely be removed in a future version.

  • -mscc โ€” enable 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 โ€” disable 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 โ€” enable 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 โ€” disable the use of conditional execution.

This switch is mainly for debugging the compiler and will likely be removed in a future version.

  • -mvliw-branch โ€” run 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 โ€” enable 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 โ€” turns off the optimization of && and || inside conditional execution. ๐Ÿ’…
bestie this switch is literally just for debugging the compiler itself and will probably get yeeted in a future version. so likeโ€ฆ don't build your whole personality on it.
  • -mnested-cond-exec โ€” turns ON the nested conditional execution optimizations (this is the default, so she's already on by default, slay). โœจ
again: mainly a compiler-debugging switch, and likely to be removed in a future version. just so you know.
  • -mno-nested-cond-exec โ€” turns OFF those nested conditional execution optimizations.
same disclaimer, same energy: mainly for debugging the compiler, likely to get removed someday.
  • -moptimize-membar โ€” this one yeets redundant membar instructions out of the compiler-generated code. it is enabled by default, no cap. ๐Ÿงน
  • -mno-optimize-membar โ€” this one turns OFF the automatic removal of redundant membar instructions from the generated code. so the membars stay. iconic of them honestly.
  • -mtomcat-stats โ€” makes gas print out tomcat statistics. numbers girlies rise ๐Ÿ“
  • *-mcpu=cpu* โ€” pick which processor type you're generating code for. the 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. so like, she's the main character everywhere else. ๐Ÿ’–
  • -muclibc โ€” use the 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 that's 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. and finally, this option causes the preprocessor macro __ANDROID__ to be defined. one option, three jobs, she's employed. ๐Ÿ’…

  • -tno-android-cc โ€” disable the compilation effects of -mandroid, i.e., do not enable -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default.
  • -tno-android-ld โ€” disable the 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 โ€” shorten some address references at link time when possible; it 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. like, it doesn't work alone bestie, it needs a buddy.
  • -ms2600 โ€” generate code for the H8S/2600. this switch must be used with -ms. ๐Ÿซถ
  • -mexr โ€” extended registers are stored on the stack before execution of a function with the monitor attribute. the default option is -mexr. this option is valid only for H8S targets.
  • -mno-exr โ€” extended registers are not stored on the stack before execution of a function with the monitor attribute. the default option is -mno-exr. this option is valid only for H8S targets.
  • -mint32 โ€” make int data 32 bits by default. glow up for your ints ๐Ÿ’…
  • -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. so don't come for her on the H8/300, she's not even listening.

๐Ÿ’œ 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. โฌ†๏ธ only, never โฌ‡๏ธ.
  • -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. same girl, different name tags. ๐ŸŽ€
  • -mcaller-copies โ€” the caller copies function arguments passed by hidden reference. use this one with care, bestie, because it is not compatible with the default 32-bit runtime. however, only aggregates larger than eight bytes are passed by hidden reference, and the option provides better compatibility with OpenMP. so it's giving "risky but sometimes worth it". ๐Ÿ™ˆ
  • -mjump-in-delay โ€” this option is ignored and provided for compatibility purposes only. she's here for the vibes, not for the function. ๐Ÿ’€
  • -mdisable-fpregs โ€” prevent floating-point registers from being used in any manner. this is necessary for compiling kernels that perform lazy context switching of floating-point registers. if you use this option and then attempt to perform floating-point operations, the compiler aborts. like, dead. gone. ๐Ÿ˜ญ so don't do that.
  • -mdisable-indexing โ€” prevent the compiler from using indexing address modes. this avoids some rather obscure problems when compiling MIG generated code under MACH.
  • -mno-space-regs โ€” generate code that assumes the target has no space registers. this allows GCC to generate faster indirect calls and use unscaled index address modes. ๐Ÿ”ฅ

such code is suitable for level 0 PA systems and kernels.

  • -mfast-indirect-calls โ€” generate code that assumes calls never cross space boundaries. this allows GCC to emit code that performs faster indirect calls. โšก
this option does not work in the presence of shared libraries or nested functions. no cap, it just won't.
  • -mfixed-range=register-range โ€” generate code treating the given register range as fixed registers. a fixed register is one that the register allocator **cannot use. this 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 โ€” generate 3-instruction load and store sequences, as sometimes required by the HP-UX 10 linker. this is equivalent to the +k option to the HP compilers.
  • -mportable-runtime โ€” use the portable calling conventions proposed by HP for ELF systems. โœจ
  • -mgas โ€” enable the use of assembler directives that only GAS understands. gas girlies only ๐Ÿ’…
  • *-mschedule=cpu-type* โ€” schedule code according to the constraints for the machine type cpu-type. the choices for cpu-type are 700, 7100, 7100LC, 7200, 7300 and 8000. refer to /usr/lib/sched.models on an HP-UX system to determine the proper scheduling option for your machine. the default scheduling is 8000. ๐Ÿ‘‘
  • -mlinker-opt โ€” enable 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 in which they give bogus error messages when linking some programs. so likeโ€ฆ spicy. ๐ŸŒถ๏ธ
  • -msoft-float โ€” generate 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; therefore, it is 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 in order for this to work. all or nothing bestie, it's giving commitment. ๐Ÿซถ

  • -msio โ€” generate the predefine _SIO for server IO. the default is -mwsio. this generates the predefines __hp9000s700, __hp9000s700__ and _WSIO, for workstation IO. these options are available under HP-UX and HI-UX.
  • -mgnu-ld โ€” use options specific to GNU ld. this passes -shared to ld when building a shared library. it is 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 are passed to that ld. the ld that is 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 โ€” use 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 is 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 are passed to that ld. the ld that is 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 โ€” generate code that uses long call sequences. this ensures that 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 is normally not desirable to use this option as it degrades performance. however, it may be useful in large applications, particularly when partial linking is used to build the application.

the types of long calls used depends 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. ๐Ÿ˜ญ she's long, she's indirect, she's doing her best.

  • -munix=unix-std โ€” bestie, this one makes the compiler spit out predefines and pick a startfile for a specific UNIX standard. Your 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. And the defaults? 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. ๐Ÿ’…

Okay so here's the tea on what each one actually does: -munix=93 gives you the exact same predefines as GCC 3.3 and 3.4. -munix=95 adds extra predefines for XOPEN_UNIX and _XOPEN_SOURCE_EXTENDED, plus the startfile unix95.o. And -munix=98 adds predefines for _XOPEN_UNIX, _XOPEN_SOURCE_EXTENDED, _INCLUDE__STDC_A1_SOURCE and _INCLUDE_XOPEN_SOURCE_500, plus the startfile unix98.o.

โš ๏ธ No cap, this is important: this option changes the interfaces for various library routines. It also messes with the operational behavior of the C library. So extreme care is needed when you use this option. It is giving "handle with oven mitts." ๐Ÿงค

Library code that's meant to work with more than one UNIX standard has to test, set, and restore the variable __xpg4_extended_mask as appropriate. And most GNU software? Doesn't provide this capability. ๐Ÿ’€

  • -nolibdld โ€” suppresses the generation of link options that search libdld.sl when the -static option is specified on HP-UX 10 and later. ๐Ÿซถ
  • -static โ€” so the HP-UX implementation of setlocale in libc depends on libdld.sl. And there's no archive version of libdld.sl. Which means when you pass -static, you need special link options to resolve that dependency. ๐Ÿ˜ญ

On HP-UX 10 and later, the GCC driver adds the necessary options to link with libdld.sl whenever -static is specified. Side effect? The resulting binary ends up dynamic. And on the 64-bit port, the linkers generate dynamic binaries by default anyway, so like, it was already that girl. If you want to stop the GCC driver from adding these link options, that's exactly what -nolibdld is for.

  • -threads โ€” adds support for multithreading with the dce thread library under HP-UX. Sets flags for both the preprocessor and the linker. Teamwork, fr fr. ๐Ÿค

โœจ IA-64 Options โœจ

These are the -m options defined for the Intel IA-64 architecture. Get comfy. ๐Ÿฆ‹

  • -mbig-endian โ€” generate code for a big-endian target. This is the default for HP-UX.
  • -mlittle-endian โ€” generate 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 โ€” generate 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 โ€” generate code that uses a single constant global pointer value. This is useful when compiling kernel code.
  • -mauto-pic โ€” generate code that is self-relocatable. This implies -mconstant-gp. This is useful when compiling firmware code.
  • -minline-float-divide-min-latency โ€” generate code for inline divides of floating-point values using the minimum latency algorithm.
  • -minline-float-divide-max-throughput โ€” generate 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 โ€” generate code for inline divides of integer values using the minimum latency algorithm.
  • -minline-int-divide-max-throughput โ€” generate 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 โ€” generate code for inline square roots using the minimum latency algorithm.
  • -minline-sqrt-max-throughput โ€” generate code for inline square roots using the maximum throughput algorithm.
  • -mno-inline-sqrt โ€” do not generate inline code for sqrt.
  • -mfused-madd, -mno-fused-madd โ€” do (don't) generate code that uses the fused multiply/add or multiply/subtract instructions. The default is to use these instructions.
  • -mno-dwarf2-asm, -mdwarf2-asm โ€” don't (or do) generate assembler code for the DWARF line number debugging info. This may be useful when you're not using the GNU assembler.
  • -mearly-stop-bits, -mno-early-stop-bits โ€” allow stop bits to be placed earlier than immediately preceding the instruction that triggered the stop bit. This can improve instruction scheduling, but not always. ๐Ÿ™ˆ
  • -mfixed-range=register-range โ€” generate code treating the given register range as fixed registers. A fixed register is one the register allocator cannot use. This is useful when compiling kernel code. A register range is specified as two registers separated by a dash. You can specify multiple register ranges separated by a comma. ๐ŸŽ€
  • -mtls-size=tls-size โ€” specify the bit size of immediate TLS offsets. Valid values are 14, 22, and 64.
  • -mtune=cpu-type โ€” tune 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.
  • -mno-sched-br-data-spec, -msched-br-data-spec โ€” (dis/en)able data speculative scheduling before reload. This results in generation of ld.a instructions and the corresponding check instructions (ld.c / chk.a). The default setting is disabled.
  • -msched-ar-data-spec, -mno-sched-ar-data-spec โ€” (en/dis)able data speculative scheduling after reload. This results in generation of ld.a instructions and the corresponding check instructions (ld.c / chk.a). The default setting is enabled.
  • -mno-sched-control-spec, -msched-control-spec โ€” (dis/en)able control speculative scheduling. This feature is available only during region scheduling (i.e. before reload). This results in generation of the ld.s instructions and the corresponding check instructions chk.s. The default setting is disabled.
  • -msched-br-in-data-spec, -mno-sched-br-in-data-spec โ€” (en/dis)able speculative scheduling of the instructions that are dependent on the data speculative loads before reload. This is effective only with -msched-br-data-spec enabled. The default setting is enabled.
  • -msched-ar-in-data-spec, -mno-sched-ar-in-data-spec โ€” (en/dis)able speculative scheduling of the instructions that are dependent on the data speculative loads after reload. This is effective only with -msched-ar-data-spec enabled. The default setting is enabled.
  • -msched-in-control-spec, -mno-sched-in-control-spec โ€” (en/dis)able speculative scheduling of the instructions that are dependent on the control speculative loads. This is effective only with -msched-control-spec enabled. The default setting is enabled.
  • -mno-sched-prefer-non-data-spec-insns, -msched-prefer-non-data-spec-insns โ€” if enabled, data-speculative instructions are chosen for schedule only if there are no other choices at the moment. This makes the use of data speculation much more conservative. The default setting is disabled.
  • -mno-sched-prefer-non-control-spec-insns, -msched-prefer-non-control-spec-insns โ€” if enabled, control-speculative instructions are chosen for schedule only if there are no other choices at the moment. This makes the use of control speculation much more conservative. The default setting is disabled.
  • -mno-sched-count-spec-in-critical-path, -msched-count-spec-in-critical-path โ€” if enabled, speculative dependencies are considered during computation of the instructions priorities. This makes the use of the speculation a bit more conservative. The default setting is disabled.
  • -msched-spec-ldc โ€” use a simple data speculation check. This option is on by default.
  • -msched-control-spec-ldc โ€” use a simple check for control speculation. This option is on by default.
  • -msched-stop-bits-after-every-cycle โ€” place a stop bit after every cycle when scheduling. This option is on by default.
  • -msched-fp-mem-deps-zero-cost โ€” assume that floating-point stores and loads are not likely to cause a conflict when placed into the same instruction group. This option is disabled by default.
  • -msel-sched-dont-check-control-spec โ€” generate checks for control speculation in selective scheduling. This flag is disabled by default.
  • -msched-max-memory-insns=max-insns โ€” a limit on the number of memory insns per instruction group, giving lower priority to subsequent memory insns attempting to schedule in the same instruction group. Frequently useful to prevent cache bank conflicts. The default value is 1.
  • -msched-max-memory-insns-hard-limit โ€” makes the limit specified 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 are preferred when the limit is reached, but memory operations may still be scheduled. ๐ŸŒธ

๐ŸŒˆ 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. โœจ

๐Ÿ’œ M32C Options ๐Ÿ’œ

  • -mcpu=name โ€” bestie, this picks the CPU your code is gonna be generated for ๐ŸŽฏ and name has to be one of exactly these: 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. periodt.
  • -msim โ€” says the program is gonna run on the simulator ๐Ÿ–ฅ๏ธ which makes an alternate runtime library get linked in โ€” one that supports, like, file I/O and stuff. > โš ๏ธ You must not use this option when generating programs that will run on real hardware; you must provide your own runtime library for whatever I/O functions are needed. no cap, real hardware needs real libraries ๐Ÿ’€
  • -memregs=number โ€” tells GCC how many memory-based pseudo-registers to use during code generation ๐Ÿงฎ These pseudo-registers get used like real registers, so it's giving a whole tradeoff: GCC's ability to fit the code into available registers vs. the performance penalty of using memory instead of registers. > Note that all modules in a program must be compiled with the same value for this option. Because of that, you must not use this option with GCC's default runtime libraries. consistency is the vibe or it's chaos ๐Ÿ™ˆ

๐Ÿ”ฅ M32R/D Options ๐Ÿ”ฅ

These -m options are defined for Renesas M32R/D architectures, bestie, let's go ๐Ÿฆ‹

  • -m32r2 โ€” generate code for the M32R/2 โœจ
  • -m32rx โ€” generate code for the M32R/X ๐Ÿ’ซ
  • -m32r โ€” generate code for the M32R. This is the default ๐Ÿ‘‘
  • -mmodel=small โ€” assume all objects live in the lower 16MB of memory (so their addresses can be loaded with the ld24 instruction), and assume 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 โ€” assume objects may be anywhere in the 32-bit address space (the compiler generates seth/add3 instructions to load their addresses), and assume all subroutines are reachable with the bl instruction ๐ŸŒˆ
  • -mmodel=large โ€” assume objects may be anywhere in the 32-bit address space (the compiler generates seth/add3 instructions to load their addresses), and assume subroutines may not be reachable with the bl instruction (the compiler generates the much slower seth/add3/jl instruction sequence) ๐Ÿ˜ญ slow but honest
  • -msdata=none โ€” disable use of the small data area. Variables are put 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 โ€” put small global and static data in the small data area, but do not generate special code to reference them ๐Ÿซถ
  • -msdata=use โ€” put small global and static data in the small data area, and generate special instructions to reference them ๐Ÿ’–
  • -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. The -msdata option must be set to one of sdata or use for this option to have any effect ๐Ÿ‘€

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---incorrect code is not generated. at least it's not silently cursed ๐Ÿ™

  • -mdebug โ€” makes the M32R-specific code in the compiler display some statistics that might help in debugging programs ๐Ÿ”
  • -malign-loops โ€” align all loops to a 32-byte boundary ๐Ÿ“
  • -mno-align-loops โ€” do not enforce a 32-byte alignment for loops. This is the default ๐Ÿ’…
  • -missue-rate=number โ€” issue number instructions per cycle. number can only be 1 or 2 โšก
  • -mbranch-cost=number โ€” number can only be 1 or 2. If it is 1 then branches are preferred over conditional code, if it is 2, then the opposite applies ๐Ÿ”€
  • -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 ๐Ÿ™…

๐ŸŒธ 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.

When used together, -march and -mtune select code that runs on a family of similar processors but that is optimized for a particular microarchitecture ๐Ÿ‘‘

  • -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 table below, which also classifies the CPUs into families:
Family : -mcpu arguments
51 : 51 51ac 51ag 51cn 51em 51je 51jf 51jg 51jm 51mm 51qe 51qm
5206 : 5202 5204 5206
5206e : 5206e
5208 : 5207 5208
5211a : 5210a 5211a
5213 : 5211 5212 5213
5216 : 5214 5216
52235 : 52230 52231 52232 52233 52234 52235
5225 : 5224 5225
52259 : 52252 52254 52255 52256 52258 52259
5235 : 5232 5233 5234 5235 523x
5249 : 5249
5250 : 5250
5271 : 5270 5271
5272 : 5272
5275 : 5274 5275
5282 : 5280 5281 5282 528x
53017 : 53011 53012 53013 53014 53015 53016 53017
5307 : 5307
5329 : 5327 5328 5329 532x
5373 : 5372 5373 537x
5407 : 5407
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 ๐Ÿ’€

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 table above.

  • -mtune=tune โ€” tune 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.

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.

  • -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.

  • -m68060 โ€” generate output for a 68060. This is the default when the compiler is configured for 68060-based systems. It is equivalent to -march=68060 ๐Ÿ”ฅ

This option inhibits the use of 68020 and 68881/68882 instructions that have to be emulated by software on the 68060. Use this option if your 68060 does not have code to emulate those instructions.

  • -mcpu32 โ€” generate output for a CPU32. This is the default when the compiler is configured for CPU32-based systems. It is equivalent to -march=cpu32 โญ

Use this option for microcontrollers with a CPU32 or CPU32+ core, including the 68330, 68331, 68332, 68333, 68334, 68336, 68340, 68341, 68349 and 68360.

  • -m5200 โ€” generate output for a 520X ColdFire CPU. This is the default when the compiler is configured for 520X-based systems. It is equivalent to -mcpu=5206, and is now deprecated in favor of that option ๐Ÿ™ˆ

Use this option for microcontroller with a 5200 core, including the MCF5202, MCF5203, MCF5204 and MCF5206.

  • -m5206e โ€” generate output for a 5206e ColdFire CPU. The option is now deprecated in favor of the equivalent -mcpu=5206e ๐Ÿ’€
  • -m528x โ€” generate output for a member of the ColdFire 528X family. The option is now deprecated in favor of the equivalent -mcpu=528x ๐Ÿšซ
  • -m5307 โ€” generate output for a ColdFire 5307 CPU. The option is now deprecated in favor of the equivalent -mcpu=5307 ๐Ÿ˜ญ
  • -m5407 โ€” makes output for a ColdFire 5407 CPU. Heads up tho bestie: this one is deprecated now, the glow-up replacement is the equivalent -mcpu=5407.
  • -mcfv4e โ€” output for a ColdFire V4e family CPU (like 547x/548x, iykyk). This one does bring hardware floating-point instructions into the mix. It's equivalent to -mcpu=547x, and yeah, it's deprecated in favor of that option. ๐Ÿซถ
  • -m68020-40 โ€” generates output for a 68040, but without touching any of the new instructions. The vibe is code that runs relatively efficiently on a 68020/68881, a 68030, or a 68040. It does still use the 68881 instructions that get emulated on the 68040.

This option is equivalent to -march=68020 -mtune=68020-40.

  • -m68020-60 โ€” generates output for a 68060, again without the new instructions. Code that can run relatively efficiently on a 68020/68881, a 68030, or a 68040. It does use the 68881 instructions that are emulated on the 68060.

This option is 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. โœจ
  • -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 with no FPU. ๐Ÿ“
  • -mdiv, -mno-div โ€” generate (or don't generate) ColdFire hardware divide and remainder instructions. If -march is used without -mcpu, the default is "on" for ColdFire architectures and "off" for M680x0 architectures. Otherwise the default comes from the target CPU (either the default CPU, or the one you named with -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 โ€” treats type int as 16 bits wide, like short int. Bonus lore: parameters passed on the stack are also aligned to a 16-bit boundary, even on targets whose API mandates promotion to 32-bit.
  • -mno-short โ€” do not treat int as 16 bits wide. This is the default.
  • -mnobitfield, -mno-bitfield โ€” don't 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're using a configuration designed for a 68020. ๐Ÿ’…
  • -mrtd โ€” uses 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. Saves one instruction in the caller since there's no need to pop the args there.
Warning bestie, this is a real one: this calling convention is incompatible with the one normally used on Unix, so you can't 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, but not here.)

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 โ€” controls 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. ๐ŸŒˆ
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. ๐Ÿ’€

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.

  • -mno-strict-align, -mstrict-align โ€” do not (do) assume that unaligned memory references are handled by the system.
  • -msep-data โ€” generates code that lets the data segment live 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 โ€” generates code that assumes the data segment follows the text segment. This is the default.
  • -mid-shared-library โ€” generates 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.
  • -mno-id-shared-library โ€” generates 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 just omitting this option.
  • -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 isn't needed; -fPIC suffices. ๐ŸŒธ

GCC normally uses a single instruction to load values from the GOT. While that's relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger makes the linker 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.

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. ๐Ÿ™ˆ

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.

  • -mhardlit, -mno-hardlit โ€” inline constants into the code stream if it can be done in two instructions or less.
  • -mdiv, -mno-div โ€” use the divide instruction. (Enabled by default). โœจ
  • -mrelax-immediate, -mno-relax-immediate โ€” allow arbitrary-sized immediates in bit operations.
  • -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.
  • -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.
  • -m210, -m340 โ€” generate code for the 210 processor.
  • -mno-lsim โ€” assume that runtime support has been provided and so omit the simulator library (libsim.a) from the linker command line.
  • -mstack-increment=size โ€” set the maximum amount for a single stack increment operation. Large values can increase the speed of programs that contain functions needing 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. ๐Ÿ˜ญ

MeP Options ๐ŸŽ€

  • -mabsdiff โ€” enables the abs instruction, which is the absolute difference between two registers.
  • -mall-opts โ€” enables all the optional instructions---average, multiply, divide, bit operations, leading zero, absolute difference, min/max, clip, and saturation. ๐Ÿ‘‘
  • -maverage โ€” enables the ave instruction, which computes the average of two registers.
  • -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.
  • -mbitops โ€” enables the bit operation instructions---bit test (btstm), set (bsetm), clear (bclrm), invert (bnotm), and test-and-set (tas).
  • -mc=name โ€” selects which section constant data is placed in. name may be tiny, near, or far.
  • -mclip โ€” enables the clip instruction. Note that -mclip is not useful unless you also provide -mminmax. ๐Ÿ’…
  • -mconfig=name โ€” selects one of the built-in core configurations. Each MeP chip has one or more modules in it; each module has a core CPU and a variety of coprocessors, optional instructions, and peripherals. The MeP-Integrator tool, not part of GCC, provides these configurations through this option; using this option is the same as using all the corresponding command-line options. The default configuration is default. โœจ
  • -mcop โ€” enables the coprocessor instructions. By default, this is a 32-bit coprocessor. Note that the coprocessor is normally enabled via the -mconfig= option.
  • -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. ๐Ÿ”ฅ
  • -mdc โ€” causes constant variables to be placed in the .near section.
  • -mdiv โ€” enables the div and divu instructions.
  • -meb โ€” generate big-endian code. ๐ŸŒˆ
  • -mel โ€” bestie, this makes little-endian code. ๐Ÿฆ‹
  • -mio-volatile โ€” tells the compiler that literally any variable tagged with the "io" attribute should be treated as volatile. no takebacks.
  • -ml โ€” variables get dumped into the .far section by default.
  • -mleadz โ€” turns on the "leadz" (leading zero) instruction. slay.
  • -mm โ€” now variables go to the .near section by default instead.
  • -mminmax โ€” enables the "min" and "max" instructions. icon behaviour tbh.
  • -mmult โ€” enables the multiplication and multiply-accumulate instructions. ๐Ÿ’…
  • -mno-opts โ€” turns OFF every optional instruction that -mall-opts turned on. the reverse card.
  • -mrepeat โ€” enables the "repeat" and "erepeat" instructions, which are the low-overhead looping ones.
  • -ms โ€” every variable defaults to the .tiny section. โš ๏ธ heads up: there's a 65536-byte limit on this section. accesses to these variables go through 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".
  • -msdram โ€” links the SDRAM-based runtime instead of the default ROM-based runtime.
  • -msim โ€” links the simulator run-time libraries.
  • -msimnovec โ€” links the simulator runtime libraries, but excluding the built-in support for reset and exception vectors and tables.
  • -mtf โ€” 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 use the $gp base register. default for this option is 4, but ๐Ÿซถ remember there's a 65536-byte limit on the .tiny section.

โœจ MicroBlaze Options โœจ

  • -msoft-float โ€” use software emulation for floating point (this is the default).
  • -mhard-float โ€” use hardware floating-point instructions instead. main character energy.
  • -mmemcpy โ€” do not optimize block moves, just use "memcpy".
  • -mno-clearbss โ€” โš ๏ธ this option is deprecated. use -fno-zero-initialized-in-bss instead, bestie.
  • -mcpu=cpu-type โ€” use the 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 โ€” โš ๏ธ deprecated, bestie. 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.
    • -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 is not supported.
    • xmdstub โ€” for use with the Xilinx Microprocessor Debugger (XMD) based software intrusive debug agent called xmdstub. this 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 do not require any of the MicroBlaze vectors. this one may be useful for applications running within a monitoring application. it uses crt3.o as a startup file.
also, the option -xl-mode-app-model is a deprecated alias for -mxl-mode-app-model. ๐Ÿ™ˆ

๐Ÿ’œ 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. 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 does not recognize the processor. ๐Ÿงš

in processor names, a final 000 can be abbreviated as k (for example, -march=r2k). prefixes are optional, and vr may be written r.

names of the form nf2_1 refer to processors with FPUs clocked at half the rate of the core, names of the form nf1_1 refer to processors with FPUs clocked at the same rate as the core, and names of the form nf3_2 refer to processors with FPUs clocked a ratio of 3:2 with respect to the core. for compatibility reasons, nf is accepted as a synonym for nf2_1 while nx and bfx are accepted as synonyms for nf1_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.

note that the _MIPS_ARCH macro uses the processor names given above. in other words, 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"). 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 is not used, GCC optimizes for the processor specified by -march. by using -march and -mtune together, it is possible to generate code that runs on a family of processors, but optimize the code for one particular member of that family. ๐Ÿ”ฅ

-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 "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. ๐Ÿ™ˆ
  • -minterlink-compressed, -mno-interlink-compressed โ€” require (do not require) that code using the standard (uncompressed) MIPS ISA be link-compatible with MIPS16 and microMIPS code, and vice versa.

for example, code using the standard ISA encoding cannot jump directly to MIPS16 or microMIPS code; it must either use a call or an indirect jump. -minterlink-compressed therefore disables direct jumps unless GCC knows that the target of the jump is not compressed.

  • -minterlink-mips16, -mno-interlink-mips16 โ€” aliases of -minterlink-compressed and -mno-interlink-compressed. these options predate the microMIPS ASE and are retained for backwards compatibility.
  • -mabi=32, -mabi=o64, -mabi=n32, -mabi=64, -mabi=eabi โ€” generate code for the given ABI.

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 information about the O64 ABI, see http://gcc.gnu.org/projects/mipso64-abi.html.

GCC supports a variant of the o32 ABI in which floating-point registers are 64 rather than 32 bits wide. you can select this combination with -mabi=32 -mfp64. this ABI relies on the "mthc1" and "mfhc1" instructions and is therefore only supported for MIPS32R2, MIPS32R3 and MIPS32R5 processors. ๐Ÿ‘‘

The register assignments for arguments and return values? unchanged bestie, still the same. But each scalar value gets passed in a single 64-bit register instead of a lil pair of 32-bit registers. So like, scalar floating-point values come back in $f0 only โ€” not a $f0/$f1 duo. And the call-saved registers? Also still the same set, in that the even-numbered double-precision registers are the ones that get saved. consistency era ๐Ÿ’…

Two extra variants of the o32 ABI exist so you can transition from 32-bit to 64-bit registers, and they are: FPXX (-mfpxx) and FP64A (-mfp64 -mno-odd-spreg).

  • The FPXX extension mandates that all code has to execute correctly whether it's run using 32-bit or 64-bit registers. It can be interlinked with either FP32 or FP64 โ€” but not both, ok?? pick a lane. ๐Ÿ™ˆ
  • The FP64A extension is basically FP64's cousin but it forbids the use of odd-numbered single-precision registers. You can pair it with the "FRE" mode of FPUs in MIPS32R5 processors, and that lets both FP32 and FP64A code interlink and run in the same process without having to switch FPU modes. multitasking icon behavior โœจ

๐ŸŒธ OPTIONS ๐ŸŒธ (still going, we're so back)

  • -mabicalls, -mno-abicalls โ€” generate (or don't generate, bestie) code that's suitable for SVR4-style dynamic objects. And -mabicalls is the default for SVR4-based systems. locked in ๐Ÿ”’
  • -mshared, -mno-shared โ€” generate (or don't) code that's fully position-independent, meaning it can be linked into shared libraries. Heads up: this option only affects -mabicalls.

All -mabicalls code has traditionally been position-independent, no matter what -fPIC and -fpic say. BUT โ€” as an extension, the GNU toolchain lets executables use absolute accesses for locally-binding symbols. It can also use shorter GP initialization sequences and generate direct calls to locally-defined functions. This mode is what you get with -mno-shared.

-mno-shared depends on binutils 2.16 or higher, and it generates objects that can only be linked by the GNU linker. ngl kind of picky. However โ€” the option does not affect the ABI of the final executable; it only affects the ABI of relocatable objects. And using -mno-shared generally makes executables both smaller and quicker. ate fr fr ๐Ÿ”ฅ

-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.

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 queen โœจ but it only works if the GOT is smaller than about 64k. Anything bigger and the linker gets mad and reports an error like:

relocation truncated to fit: R_MIPS_GOT16 foobar

If that happens to you, recompile your code with -mxgot. This works with very large GOTs, though the code is also less efficient, since it takes three instructions to fetch the value of a global symbol. trade-off vibes.

Note that some linkers can create multiple GOTs. If you have one of those fancy linkers, you should only need -mxgot when a single object file accesses more than 64k's worth of GOT entries. And very few do. rare occasion energy ๐Ÿ’…

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. we don't know her. ๐Ÿฆ‹
  • -mhard-float โ€” use floating-point coprocessor instructions.
  • -msoft-float โ€” do not use floating-point coprocessor instructions. Implement floating-point calculations using library calls instead. library girlies rise up ๐Ÿ“š
  • -mno-float โ€” equivalent to -msoft-float, but additionally asserts that the program being compiled does not perform any floating-point operations. This option is presently supported only 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 is likely to suffer a link-time or run-time failure. be careful bestie ๐Ÿ˜ญ
  • -msingle-float โ€” assume that the floating-point coprocessor only supports single-precision operations.
  • -mdouble-float โ€” assume that the floating-point coprocessor supports double-precision operations. This is the default. default queen ๐Ÿ‘‘
  • -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 that are known to support these registers. When using the o32 FPXX ABI, -mno-odd-spreg is set by default.
  • -mabs=2008, -mabs=legacy โ€” these options control the treatment of the special not-a-number (NaN) IEEE 754 floating-point data with the abs.fmt and neg.fmt machine instructions.

By default, or when -mabs=legacy is used, the legacy treatment is selected. In this case these instructions are considered arithmetic and avoided where correct operation is required and the input operand might be a NaN. A longer sequence of instructions that manipulate 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 these instructions are considered non-arithmetic and therefore operating correctly in all cases, including in particular where the input operand is a NaN. These instructions are therefore always used for the respective operations. no thoughts, just abs โœจ

  • -mnan=2008, -mnan=legacy โ€” these options control the encoding of the special not-a-number (NaN) IEEE 754 floating-point data.

The -mnan=legacy option 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.

The -mnan=2008 option selects the IEEE 754-2008 encoding. In this case qNaNs are denoted by the first bit of their trailing significand field being 1, whereas sNaNs are denoted by the first bit of their trailing significand field being 0. they literally just swapped, iconic ๐Ÿ’…

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. iykyk ๐Ÿ“–

  • -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.
  • -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.
  • -msmartmips, -mno-smartmips โ€” use (or don't use) the MIPS SmartMIPS ASE. smart girl summer ๐ŸŒธ
  • -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.
  • -mips3d, -mno-mips3d โ€” use (or don't use) the MIPS-3D ASE. The option -mips3d implies -mpaired-single. package deal โœจ
  • -mmicromips, -mno-micromips โ€” generate (or don't generate) microMIPS code.

MicroMIPS code generation can also be controlled on a per-function basis by means of micromips and nomicromips attributes. per-function drama ๐Ÿ’…

  • -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. virtual baddie era ๐Ÿฆ‹
  • -mxpa, -mno-xpa โ€” use (or don't use) the MIPS eXtended Physical Address (XPA) instructions.
  • -mcrc, -mno-crc โ€” use (or don't use) the MIPS Cyclic Redundancy Check (CRC) instructions.
  • -mginv, -mno-ginv โ€” use (or don't use) the MIPS Global INValidate (GINV) instructions.
  • -mloongson-mmi, -mno-loongson-mmi โ€” use (or don't use) the MIPS Loongson MultiMedia extensions Instructions (MMI).
  • -mloongson-ext, -mno-loongson-ext โ€” use (or don't use) the MIPS Loongson EXTensions (EXT) instructions.
  • -mloongson-ext2, -mno-loongson-ext2 โ€” use (or don't use) the MIPS Loongson EXTensions r2 (EXT2) instructions.
  • -mlong64 โ€” force long types to be 64 bits wide. See -mlong32 for an explanation of the default and the way that the pointer size is determined. scroll down bestie โฌ‡๏ธ
  • -mlong32 โ€” force long, int, and pointer types to be 32 bits wide.

The default size of ints, longs and pointers depends on the ABI. All the supported ABIs use 32-bit ints. The n64 ABI uses 64-bit longs, as does the 64-bit EABI; the others use 32-bit longs. Pointers are the same size as longs, or the same size as integer registers โ€” whichever is smaller. tiny wins โœจ

  • -msym32, -mno-sym32 โ€” assume (or don't assume) that all symbols have 32-bit values, regardless of the selected ABI. This option is useful in combination with -mabi=64 and -mno-abicalls because it allows GCC to generate shorter and faster references to symbolic addresses. shorter AND faster?? we love an overachiever ๐Ÿ”ฅ
  • -G num โ€” okay so this one says: put definitions of externally-visible data in a small data section if that data is no bigger than num bytes. Then GCC can generate more efficient accesses to the data; peep -mgpopt for the tea. The default -G option depends on the configuration. ๐Ÿ’…
  • -mlocal-sdata, -mno-local-sdata โ€” extend (or do not extend) the -G behavior to local data too, like to static variables in C. -mlocal-sdata is the default for all configurations. If the linker is complaining that an application is using too much small data, bestie, you might want to try rebuilding the less performance-critical parts with -mno-local-sdata. You might also want to build large libraries with -mno-local-sdata, so that the libraries leave more room for the main program. ๐Ÿซถ
  • -mextern-sdata, -mno-extern-sdata โ€” assume (do not assume) that externally-defined data is in a small data section if the size of that data is within the -G limit. -mextern-sdata is the default for all configurations. If you compile a module Mod with -mextern-sdata -G num -mgpopt, and Mod references a variable Var that is 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. 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. However, you may wish to build a library that supports several different small data limits. You can do this 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. no cap โœจ
  • -mgpopt, -mno-gpopt โ€” use (do not 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 useful 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.) -mno-gpopt implies -mno-local-sdata and -mno-extern-sdata. ๐Ÿ’€
  • -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 reduces the amount of RAM required when executing, and thus may be preferred for some embedded systems. lowkey a vibe for tiny devices ๐ŸŒธ
  • -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. ๐Ÿ‘‘
  • -mcode-readable=setting โ€” specify whether GCC may generate code that reads from executable sections. There are three possible settings:
    • -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 option is useful on 4KSc and 4KSd processors when the code TLBs have the Read Inhibit bit set. It is 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 option 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 (disable) use of the %hi() and %lo() assembler relocation operators. This option has been superseded by -mexplicit-relocs but is retained for backwards compatibility. it's giving legacy but make it fashion ๐Ÿ’…
  • -mexplicit-relocs, -mno-explicit-relocs โ€” use (do not 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 (do not trap) on integer division by zero. The default is -mcheck-zero-division. bestie do not divide by zero unless you want the drama ๐Ÿ˜ญ
  • -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 is only supported on MIPS II and later. Also, 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 (disable) an optimization that pairs consecutive load or store instructions to enable load/store bonding. This option is enabled by default but only takes effect when the selected architecture is known to support bonding. pair them up, periodt ๐Ÿ’–
  • -mmemcpy, -mno-memcpy โ€” force (do not 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 (do not 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. This option has no effect on abicalls code. The default is -mno-long-calls. same 256 MB segment or it's awkward fr fr
  • -mmad, -mno-mad โ€” enable (disable) use of the "mad", "madu" and "mul" instructions, as provided by the R4650 ISA. ๐Ÿ”ฅ
  • -mimadd, -mno-imadd โ€” enable (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 (disable) use of the floating-point multiply-accumulate instructions, when they are 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. This may be undesirable in some circumstances. On other processors the result is numerically identical to the equivalent computation using separate multiply, add, subtract and negate instructions. ๐Ÿงš
  • -nocpp โ€” tell the MIPS assembler to not run its preprocessor over user assembler files (with a .s suffix) when assembling them. no preprocessor, no problem โœจ
  • -mfix-24k, -mno-fix-24k โ€” work 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 โ€” work 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.
  • -mfix-r4400, -mno-fix-r4400 โ€” work 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 โ€” work 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 โ€” do not attempt to schedule the preceding instruction into the delay slot of a branch instruction placed at the end of a short loop of six instructions or fewer and always schedule a "nop" instruction there instead. The short loop bug under certain conditions causes loops to execute only once or twice, due to a hardware bug in the R5900 chip. The workaround is implemented by the assembler rather than by GCC. short loop bug? not today ๐Ÿ’…
  • -mfix-rm7000, -mno-fix-rm7000 โ€” work around the RM7000 "dmult"/"dmultu" errata. The workarounds are implemented by the assembler rather than by GCC. ๐Ÿ› ๏ธ
  • -mfix-vr4120, -mno-fix-vr4120 โ€” work around certain VR4120 errata:
    • "dmultu" does not always produce the correct result.
    • "div" and "ddiv" do not 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 present, these functions are only provided by the "mips64vr*-elf" configurations. Other VR4120 errata require a NOP to be inserted between certain pairs of instructions. These errata are handled by the assembler, not by GCC itself. ๐Ÿ˜ญ

  • -mfix-vr4130 โ€” work 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. โœจ
  • -mfix-sb1, -mno-fix-sb1 โ€” work around certain SB-1 CPU core errata. (This flag currently works around the SB-1 revision 2 "F1" and "F2" floating-point errata.) ๐ŸŒˆ
  • -mr10k-cache-barrier=setting โ€” specify whether GCC should insert cache barriers to avoid the side effects of speculation on R10K processors. ๐Ÿงš

okay so bestie, listen up ๐Ÿ’… the R10K is out here doing the same thing as lots of other processors: it tries to predict which way a conditional branch is gonna go and then just speculatively runs instructions from the "taken" side. Then if it guessed wrong, it aborts those instructions. BUT โ€” and this is the tea โ€” on the R10K, even the aborted instructions can leave side effects. ๐Ÿ’€

This whole situation only affects kernel stores, and depending on your system, kernel loads too. Like, for example, a speculatively-executed store might load the target memory into cache and mark that cache line as dirty, even if the store itself gets aborted later. Then if a DMA operation writes to the same area of memory before that "dirty" line gets flushed, the cached data just overwrites the DMA-ed data. ๐Ÿ˜ญ For the full rundown, including other potential problems, check the R10K processor manual.

So one workaround? 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 how GCC implements this workaround. It assumes that aborted accesses to any byte in these regions don't 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's the kernel's responsibility to make sure speculative accesses to these regions are actually safe. ๐Ÿซถ

If your input program has a function declaration like:

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, and it expects non-GCC functions (like 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 โ€” Specifies the function to call to flush the I and D caches. If 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 commonly is either _flush_func or __cpu_flush.
  • -mno-flush-func โ€” Don't call any such function to flush the caches. ๐Ÿšซ
  • mbranch-cost=num โ€” Set the cost of branches to roughly num "simple" instructions. This cost is only a heuristic and 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 โ€” Enable use of Branch Likely instructions, regardless of the default for the selected architecture. By default, Branch Likely instructions may be generated if they are supported by the selected architecture. An exception is 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.
  • -mno-branch-likely โ€” Disable use of Branch Likely instructions, regardless of the default for the selected architecture.
heads up bestie: the MIPS32 and MIPS64 architectures deprecate Branch Likely, so they don't generate them by default. ๐Ÿซ 
  • -mcompact-branches=never โ€” Ensures that compact branch instructions will never be generated.
  • -mcompact-branches=optimal โ€” The default. 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 is not filled, a compact branch will be chosen if one is available.
  • -mcompact-branches=always โ€” Ensures that a compact branch instruction will be generated if available. If a compact branch instruction is not available, a delay slot form of the branch will be used instead.

These options are supported from MIPS Release 6 onwards. โœจ

  • -mfp-exceptions โ€” Specifies that 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 are emitting 64-bit code, then we can use both FP pipes. Otherwise, we can only use one FP pipe.
  • -mno-fp-exceptions โ€” Specifies that FP exceptions are disabled. (See the note above about scheduling on the SB-1 and other processors.) ๐ŸŽ›๏ธ
  • -mvr4130-align โ€” The VR4130 pipeline is two-way superscalar, but 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 is enabled by default at optimization level -O3.
  • -mno-vr4130-align โ€” Disable this alignment. ๐Ÿ“
  • -msynci โ€” Enable 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 is generally safe to use synci.
  • -mno-synci โ€” Disable generation of synci instructions. This is the default unless overridden by --with-synci.
warning bestie: on many multi-core (SMP) systems, synci does not invalidate the instruction caches on all cores and may lead to undefined behavior. ๐Ÿ˜ฑ
  • -mrelax-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 help from the compiler.
  • -mno-relax-pic-calls โ€” Do not try to turn PIC calls into direct calls. ๐Ÿ”—
  • -mmcount-ra-address โ€” 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 the following:
    • 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.
  • -mno-mcount-ra-address โ€” Do not emit such code. This is the default. ๐Ÿ“ฌ
  • -mframe-header-opt โ€” Enable 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 is unused. This optimization is off by default at all optimization levels.
  • -mno-frame-header-opt โ€” Disable frame header optimization. This is the default. ๐Ÿ–ผ๏ธ
  • -mlxc1-sxc1 โ€” When applicable, enable the generation of lwxc1, swxc1, ldxc1, sdxc1 instructions. Enabled by default.
  • -mno-lxc1-sxc1 โ€” When applicable, disable the generation of those instructions. ๐Ÿš€
  • -mmadd4 โ€” When applicable, enable the generation of 4-operand madd.s, madd.d and related instructions. Enabled by default.
  • -mno-madd4 โ€” When applicable, disable the generation of those instructions. โž•

โœจ MMIX Options โœจ

These options are defined for the MMIX:

  • -mlibfuncs โ€” Specify that intrinsic library functions are being compiled, passing all values in registers, no matter the size.
  • -mno-libfuncs โ€” Do not specify that. ๐Ÿ“š
  • -mepsilon โ€” Generate floating-point comparison instructions that compare with respect to the rE epsilon register.
  • -mno-epsilon โ€” Do not generate such instructions. ๐ŸŒŠ
  • -mabi=mmixware โ€” Generate code that passes function parameters and return values that (in the called function) are seen as registers $0 and up.
  • -mabi=gnu โ€” Generate code that uses the GNU ABI which uses global registers $231 and up. ๐Ÿ”„
  • -mzero-extend โ€” When reading data from memory in sizes shorter than 64 bits, use zero-extending load instructions by default, rather than sign-extending ones.
  • -mno-zero-extend โ€” Do not use zero-extending load instructions by default; use sign-extending ones instead. 0๏ธโƒฃ
  • -mknuthdiv โ€” Make the result of a division yielding a remainder have the same sign as the divisor.
  • -mno-knuthdiv โ€” With the default, the sign of the remainder follows the sign of the dividend. Both methods are arithmetically valid, the latter being almost exclusively used. โž—
  • -mtoplevel-symbols โ€” Prepend a : to all global symbols, so the assembly code can be used with the PREFIX assembly directive.
  • -mno-toplevel-symbols โ€” Do not prepend a :. ๐Ÿ”ค
  • -melf โ€” Generate an executable in the ELF format, rather than the default mmo format used by the mmix simulator. ๐Ÿง
  • -mbranch-predict โ€” Use the probable-branch instructions, when static branch prediction indicates a probable branch.
  • -mno-branch-predict โ€” Do not use the probable-branch instructions. ๐Ÿ”ฎ
  • -mbase-addresses โ€” Generate code that uses base addresses. Using a base address automatically generates a request (handled by the assembler and the linker) for a constant to be set up in a global register. The register is used for one or more base address requests within the range 0 to 255 from the value held in the register. This generally leads to short and fast code, but the number of different data items that can be addressed is limited. This means that a program that uses lots of static data may require -mno-base-addresses.
  • -mno-base-addresses โ€” Do not generate code that uses base addresses. ๐Ÿ 
  • -msingle-exit โ€” Force generated code to have a single exit point in each function.
  • -mno-single-exit โ€” Do not force generated code to have a single exit point in each function. ๐Ÿšช

โœจ MN10300 Options โœจ

These -m options are defined for Matsushita MN10300 architectures:

  • -mmult-bug โ€” Generate code to avoid bugs in the multiply instructions for the MN10300 processors. This is the default. ๐Ÿ›
  • -mno-mult-bug โ€” don't emit any code that dodges the buggy multiply instructions on MN10300 processors, bestie. we're just... not doing the workaround. ๐Ÿ’…
  • -mam33 โ€” generate code that flexes the features only the AM33 processor has. โœจ
  • -mno-am33 โ€” don't use those AM33-only features. this is the default, so it's giving "we're being normal about it". ๐ŸŒธ
  • -mam33-2 โ€” generate code using the features specific to the AM33/2.0 processor.
  • -mam34 โ€” generate code using the features specific to the AM34 processor.
  • -mtune=cpu-type โ€” when scheduling instructions, use the timing characteristics of whatever CPU type you name. lowkey important: this does not change the targeted processor type, it just tunes. the CPU type has to be one of mn10300, am33, am33-2 or am34, no exceptions. ๐Ÿ‘‘
  • -mreturn-pointer-on-d0 โ€” when you generate a function that returns a pointer, this makes it return the pointer in both a0 and d0. otherwise the pointer only comes back in a0, and if you try to call such functions without a prototype you get errors. heads up: this option is on by default, so use -mno-return-pointer-on-d0 to turn it off. ๐Ÿซถ
  • -mno-crt0 โ€” do not link in the C run-time initialization object file. bye, crt0.
  • -mrelax โ€” tells the linker to run a relaxation optimization pass so branches, calls and absolute memory addresses get shortened. this option only does anything when it's on the command line for the final link step, so don't expect it to do cardio earlier in the build.
fr fr: this option makes symbolic debugging impossible. ๐Ÿ’€
  • -mliw โ€” lets 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 โ€” do not let the compiler generate Long Instruction Word instructions. this option defines the preprocessor macro __NO_LIW__.
  • -msetlb โ€” lets 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 โ€” do not allow 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 she's back, different target, same energy.)

๐ŸŒˆ MSP430 Options ๐ŸŒˆ

these options are defined for the MSP430:

  • -masm-hex โ€” force assembly output to always use hex constants. normally these constants are signed decimals, but this option exists for testsuite and/or aesthetic purposes. it's giving โœจvibesโœจ.
  • -mmcu= โ€” pick the MCU to target. this gets 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 then used by the msp430.h header file to pick an MCU-specific supplementary header file.

the option also sets the ISA to use. if the MCU name is one that's known to only support the 430 ISA, then that's what gets 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. ๐Ÿ”ฅ

on top of that, 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 makes the linker search for a script called xxx.ld.

the ISA and hardware multiply supported for the different MCUs is hard-coded into GCC. but an external devices.csv file can be used to extend device support beyond the hard-coded stuff.

GCC searches for the devices.csv file using the following methods, in this precedence order โ€” first beats second, second beats third:

  • Include path specified with -I and -L โ€” devices.csv gets 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 โ€” set the global environment variable MSP430_GCC_INCLUDE_DIR to the full path to the directory containing devices.csv, and GCC will search that directory for devices.csv. if devices.csv is found, this directory also gets registered as an include path and linker library path. so header files and linker scripts in this directory can be used without manually specifying -I and -L on the command line. ๐Ÿซถ
  • 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 the user created it and copied devices.csv there, then the MCU data gets read. as above, this directory also gets 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.

  • -mwarn-mcu, -mno-warn-mcu โ€” turns warnings on or off about conflicts between the MCU name specified by the -mmcu option and the ISA set by the -mcpu option and/or the hardware multiply support set by the -mhwmult option. 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.
ngl bestie, this option is deprecated. use the -mmcu= option to select the ISA instead. ๐Ÿ™ˆ
  • -msim โ€” link to the simulator runtime libraries and linker script. this overrides any scripts that would've been selected by the -mmcu= option. main character energy, honestly.
  • -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 gets passed to the assembler and linker, and lets the linker perform certain optimizations that cannot be done until the final link. (she's on her final-link-step timing again, iconic.)
  • 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. you can also give a value of auto, which 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. but when compiling at -O3 or higher, the hardware multiplier is invoked inline, which makes for bigger but faster code. ๐Ÿ”ฅ

the hardware multiply routines disable interrupts whilst running and restore the previous interrupt state when they finish. this makes them safe to use inside interrupt handlers as well as in normal code. periodt.

  • -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. ๐Ÿงš
  • -mtiny-printf โ€” enable reduced code size printf and puts library functions.
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 is 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 only affects cases where a shift by multiple positions cannot be completed with a single instruction (e.g. 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 used instead.

  • -mcode-region=, -mdata-region= โ€” these options tell the compiler where to place functions and data that don't 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 option passes on a request to the assembler to enable the fixes for the named silicon errata.
  • -msilicon-errata-warn= โ€” this option 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 there are problems parsing it (default: on). ๐Ÿ“

๐Ÿ’œ 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. the full set, bestie. no skimping.
  • -mcmov โ€” generate conditional move instructions.
  • -mno-cmov โ€” do not generate conditional move instructions. not today. ๐Ÿ’…
  • -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 โ€” bestie, do not emit performance extension 2 instructions. Just say no ๐Ÿ’…
  • -mext-string โ€” go ahead and generate string extension instructions โœจ
  • -mno-ext-string โ€” and this one says nope, no string extension instructions.
  • -mv3push โ€” generate those v3 push25/pop25 instructions ๐Ÿซถ
  • -mno-v3push โ€” do not generate v3 push25/pop25 instructions.
  • -m16-bit โ€” generate 16-bit instructions. tiny but mighty ๐ŸŽ€
  • -mno-16-bit โ€” do not generate 16-bit instructions.
  • -misr-vector-size=num โ€” sets the size of each interrupt vector. It must be 4 or 16, no in-between, that's the vibe check ๐Ÿšซ
  • -mcache-block-size=num โ€” sets the size of each cache block. Has to be a power of 2, somewhere between 4 and 512 inclusive. Math class is in session ๐Ÿ“
  • -march=arch โ€” names the target architecture you want. literally just telling it what it's building for ๐Ÿ‘‘
  • -mcmodel=code-model โ€” picks the code model, and the options are:
    • small โ€” all the data and read-only data segments have to fit inside a 512KB addressing space, and the text segment has to fit within 16MB addressing space.
    • medium โ€” the data segment must be within 512KB, while the read-only data segment can live within 4GB addressing space. The text segment should still be within 16MB addressing space.
    • large โ€” everything can breathe: all the text and data segments can be within 4GB addressing space.
  • -mctor-dtor โ€” turns on the constructor/destructor feature ๐Ÿ”ฅ
  • -mrelax โ€” gently guides the linker to relax instructions. it's giving chill โœจ

๐ŸŒธ Nios II Options ๐ŸŒธ

These are the options defined for the Altera Nios II processor. Yes, a whole dedicated section, because she's special like that ๐Ÿ’–

  • -G num โ€” puts global and static objects that are 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 (or do not generate) GP-relative accesses. Here are the option names it recognizes:
    • 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 uses GP-relative addressing for objects that have been explicitly placed in a small data section via a "section" attribute.
    • global โ€” same as local, but also generates GP-relative accesses for small data objects that are external, weak, or common. If you use this one, you must make sure that all parts of your program (libraries included, bestie) are compiled with the same -G setting.
    • data โ€” generate GP-relative accesses for all data objects in the program. If you use this, 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, 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. Heads up: the Nios II ABI does not permit GP-relative accesses from shared libraries ๐Ÿ™ˆ

You may need to specify -mno-gpopt explicitly when building programs that include large amounts of small data, including large GOT data sections. In that case, the 16-bit offset for GP-relative addressing may not be large enough to allow access to the entire small data section. so like, watch out ๐Ÿซ 

  • -mgprel-sec=regexp โ€” specifies additional section names that can be accessed via GP-relative addressing. It's most useful alongside "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 โ€” 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. Most useful alongside "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 (that's the default ๐Ÿฅฐ) or big-endian (experimental, spicy ๐ŸŒถ๏ธ) code, respectively.
  • -march=arch โ€” this specifies the name of the target Nios II architecture. GCC uses this name to figure out what kind of instructions it can emit when generating assembly code. The permissible names are: r1, r2.

The preprocessor macro "__nios2_arch__" is available to programs, with value 1 or 2, indicating the targeted ISA level. cute, right? ๐ŸŽ€

  • -mbypass-cache
  • -mno-bypass-cache โ€” forces 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 bypasses 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 the "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. iconic behavior, honestly โœจ

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 โ€” conversion from floating point to signed or unsigned integer types, with truncation towards zero.
  • round โ€” conversion from single-precision floating point to signed integer, rounding to the nearest integer and ties away from zero. This corresponds to the "__builtin_lroundf" function when -fno-math-errno is used.
  • floatis, floatus, floatid, floatud โ€” conversion from signed or unsigned integer types to floating-point types.

In addition, all of the following transfer instructions for internal registers X and Y must be provided to use any of the double-precision floating-point instructions. Custom instructions taking two double-precision source operands expect the first operand in the 64-bit register X. The other operand (or only operand of a unary operation) is given to the custom arithmetic instruction with the least significant half in source register src1 and the most significant half in src2. A custom instruction that returns a double-precision result returns the most significant 32 bits in the destination register and the other half in 32-bit register Y. GCC automatically generates the necessary code sequences to write register X and/or read register Y when double-precision floating-point instructions are used. okay that's a lot of words but it's important, bestie ๐Ÿซถ

  • 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 store it in dest.
  • frdy โ€” read the value of Y and store it into dest.
Note that you can gain more local control over generation of Nios II custom instructions by using the target("custom-insn=N") and target("no-custom-insn") function attributes or pragmas.

okay so this one is the โœจchoose-your-own-adventureโœจ version of the custom instruction thing:

  • -mcustom-fpu-cfg=name โ€” turns on a predefined, named set of custom instruction encodings (peep -mcustom-insn up above if you missed it ๐Ÿ‘€). Right now, these are the sets that exist:
    • -mcustom-fpu-cfg=60-1 is literally equivalent to:
-mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -fsingle-precision-constant
  • -mcustom-fpu-cfg=60-2 is literally equivalent to:
-mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255 -fsingle-precision-constant
  • -mcustom-fpu-cfg=72-3 is literally 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 literally 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

bestie, the tea โ˜• custom instruction assignments you give with the individual -mcustom-insn= options override the ones from -mcustom-fpu-cfg=, no matter what order you put them in on the command line. order does not matter, periodt ๐Ÿ’…

ngl if you want more local control over which FPU config gets picked, you can use the target("custom-fpu-cfg=name") function attribute or pragma. ๐ŸŽ€

fph2 is just short for Nios II Floating Point Hardware 2 Component. heads up though: the custom instructions turned on by -mcustom-fmins=233 and -mcustom-fmaxs=234 are only generated if -ffinite-math-only is specified. and the custom instruction turned on by -mcustom-round=248 is only generated if -fno-math-errno is specified. also, in contrast to all 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 it's typically used together with -msys-crt0= to say where the alternate startup code provided by the HAL BSP lives. ๐Ÿซถ
  • -msmallc โ€” link with a limited version of the C library, -lsmallc, rather than 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, like read and write. this option is 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 64-bit ABI is supported, iykyk.
  • -misa=ISA-string โ€” generate code for the given specified PTX ISA (e.g. sm_35). ISA strings must be lower-case. valid ISA strings include sm_30 and sm_35. the default ISA is sm_35.
  • -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 so you can test 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 you execute all threads in each warp, 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 the current lane index to compute the master lane index. ๐Ÿ‘‘
  • -mgomp โ€” generate code for use in OpenMP offloading: enables the -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 for compatibility purposes only. it used to select linker and preprocessor options for use with newlib.
  • -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 perform 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 to perform unordered floating point compare and set flag operations.
  • -mcmov โ€” enable generation of conditional move (l.cmov) instructions. by default the equivalent will be generated using set and branch.
  • -mror โ€” enable generation of rotate right (l.ror) instructions. by default, functions from libgcc are used to perform rotate right operations.
  • -mrori โ€” enable generation of rotate right with immediate (l.rori) instructions. by default, functions from libgcc are used to perform rotate right with immediate operations.
  • -msext โ€” enable generation of sign extension (l.ext*) instructions. by default memory loads are used to perform sign extension.
  • -msfimm โ€” enable generation of compare and set flag with immediate (l.sf*i) instructions. by default extra instructions will be 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 will be generated to store the immediate to a register first.

๐ŸŽ€ PDP-11 Options ๐ŸŽ€

These options are defined for the PDP-11:

  • -mfpu โ€” use hardware FPP floating point. this is the default. (FIS floating point on the PDP-11/40 is not supported.) implies -m45.
  • -msoft-float โ€” do not use hardware floating point.
  • -mac0 โ€” return floating-point results in ac0 (fr0 in Unix assembler syntax).
  • -mno-ac0 โ€” return floating-point results in memory. this is the default.
  • -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.
  • -m10 โ€” generate code for a PDP-11/10. implies -msoft-float -mno-split.
  • -mint16, -mno-int32 โ€” use 16-bit int. this is the default.
  • -mint32, -mno-int16 โ€” use 32-bit int.
  • -msplit โ€” 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. this is the default.
  • -mlra โ€” use the new LRA register allocator. by default, the old "reload" allocator is used.

๐Ÿงš picoChip Options ๐Ÿงš

These -m options are defined for picoChip implementations:

  • -mae=ae_type โ€” set the instruction set, register set, and instruction scheduling parameters for array element type ae_type. supported values for ae_type are ANY, MUL, and MAC.
    • -mae=ANY selects a completely generic AE type. code generated with this option runs on any of the other AE types. the code is not as efficient as it would be if compiled for a specific AE type, and some types of operation (e.g., multiplication) do not work properly on all types of AE.
    • -mae=MUL selects a MUL AE type. this is the most useful AE type for compiled code, and is the default.
    • -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. ๐Ÿ’€
  • -msymbol-as-address โ€” enable the compiler to directly use a symbol name as an address in a load/store instruction, without first loading it into a register. typically, using this option generates larger programs, which run faster than when the option isn't used. however, the results vary from program to program, so it's left as a user option, rather than being permanently enabled.
  • -mno-inefficient-warnings โ€” disables warnings about the generation of inefficient code. these warnings can be generated, 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. this is inefficient, and a warning is generated to indicate that you should rewrite the code to avoid byte operations, or to target an AE type that has the necessary hardware support. this option disables these warnings. ๐Ÿ”ฅ

๐ŸŒˆ PowerPC Options ๐ŸŒˆ

These are listed under

๐ŸŒธ PRU Options ๐ŸŒธ

okay so if you're out here building for the PRU target, these are YOUR flags bestie, and there are five of them. Buckle up ๐ŸŽ€

  • -minrt โ€” link with a minimum runtime environment, which means no support for static initializers and constructors. Using this can shrink your final ELF binary a lot, which is giving major glow-up energy for tiny targets โœจ. BUT โ€” and this is the important part โ€” the compiler could still generate code with static initializers and constructors. Nobody's stopping it. It is up to you, the programmer to make sure your source program doesn't use those features. That's on you, not on GCC, fr fr.
  • -mmcu=mcu โ€” tells GCC which PRU MCU variant to use. Wanna know the exact list of supported MCUs? Check Newlib. That's where the list lives, go look ๐Ÿ‘€
  • -mno-relax โ€” makes GCC hand the linker --no-relax instead of --relax. That's the whole vibe. Passing the opposite flag, basically. ๐Ÿ’…
  • -mloop โ€” allows (or does not allow) GCC to use the LOOP instruction. Simple as that, no notes ๐ŸŒ€
  • -mabi=variant โ€” pick which ABI variant the code gets generated for. -mabi=ti selects the unmodified TI ABI, while -mabi=gnu selects a GNU variant that copes more naturally with certain GCC assumptions. And here's the tea on how they differ โ˜•:
    • Function Pointer Size โ€” TI ABI says function (code) pointers are 16-bit, whereas GNU supports only 32-bit data and code pointers. Not a vibe difference, an actual real difference.
    • Optional Return Value Pointer โ€” when a function returns something bigger than 64 bits, it gets passed using a hidden pointer as the first argument of the function. TI ABI, though, mandates that pointer can be NULL in case the caller isn't using the returned value. GNU always passes and expects a valid return value pointer. No NULL shenanigans allowed ๐Ÿšซ

The current -mabi=ti implementation simply raises a compile error when any of the above code constructs is detected ๐Ÿ˜ญ. And as a consequence of all that, the standard C library cannot be built, and it is omitted when linking with -mabi=ti. So likeโ€ฆ plan accordingly.

Also: relaxation is a GNU feature, and for safety reasons it's disabled when using -mabi=ti. Why? Because the TI toolchain does not emit relocations for QBBx instructions, so the GNU linker cannot adjust them when shortening adjacent LDI32 pseudo instructions. That's the technical reason, and I'm telling you because you deserve to know ๐Ÿซถ


๐Ÿฆ‹ RISC-V Options ๐Ÿฆ‹

RISC-V girlies rise up, this section is LONG and it's ICONIC, let's go ๐ŸŒˆ

  • -mbranch-cost=n โ€” set the cost of branches to roughly n instructions. That's it, that's the flag โญ
  • -mplt / -mno-plt โ€” when generating PIC code, do or don't allow the use of PLTs. Ignored for non-PIC (so like, if you're not doing PIC this flag is just sitting there minding its own business ๐Ÿ™ˆ). The default is -mplt.
  • -mabi=ABI-string โ€” specify integer and floating-point calling convention. The ABI-string has two parts: the size of integer types, and the registers used for floating-point types. Example time, because examples ate ๐Ÿ’…: -march=rv64ifd -mabi=lp64d means 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. Now contrast that with -march=rv64ifd -mabi=lp64f, which still lets the compiler 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 at all. Wild, right?

The default for this argument is system dependent, so if you want a specific calling convention, specify one explicitly. The valid calling conventions are: ilp32, ilp32f, ilp32d, lp64, lp64f, and lp64d. Heads up though: 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. That ABI is not well specified at present, and is subject to change โ€” so treat it like it's still in its experimental era.

  • -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. Nice โœจ
  • -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. Same energy as above ๐ŸŽ€
  • -march=ISA-string โ€” generate code for the given RISC-V ISA (e.g. rv64im). ISA strings must be lower-case (no shouting allowed ๐Ÿ“ข). 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 specific architecture extensions should specify one explicitly. Periodt.

  • -mcpu=processor-string โ€” use the architecture of and optimize the output for the given processor, specified by a 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. That's the whole roster, no substitutions ๐Ÿ‘‘
  • -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, and 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. It's giving internal-tooling-only, iykyk ๐Ÿคซ

  • -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 (that's 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. Do not mix and match, bestie, it will not end well ๐Ÿ˜ญ
  • -msmall-data-limit=n โ€” put global and static data smaller than n bytes into a special section (on some targets). Cute little optimization ๐ŸŒธ
  • -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. Small and slow, or big and fast โ€” your call ๐Ÿ’…
  • -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 (yes, the polarity is like that, read it twice ๐Ÿ™ˆ). The default is set depending on whether the processor we are optimizing for supports fast unaligned access or not.
  • -mcmodel=medlow โ€” generate code for the medium-low code model. The program and its statically defined symbols must lie within a single 2 GiB address range and must lie between absolute addresses -2 GiB and +2 GiB. Programs can be statically or dynamically linked. This is the default code model.
  • -mcmodel=medany โ€” generate code for the medium-any code model. The program and its statically defined symbols must be within any single 2 GiB address range. Programs can be statically or dynamically linked.
  • -mexplicit-relocs / -mno-exlicit-relocs โ€” use or do not use assembler relocation operators when dealing with symbolic addresses. The alternative is to use assembler macros instead, which may limit optimization. (And yes, that second one is spelled -mno-exlicit-relocs in the manual โ€” keep it exactly like that, I'm not touching it ๐Ÿ’€)
  • -mrelax / -mno-relax โ€” take advantage of linker relaxations to reduce the number of instructions required to materialize symbol addresses. The default is to take advantage of linker relaxations. Chill vibes, linker does the work ๐Ÿงš
  • -memit-attribute / -mno-emit-attribute โ€” emit (do not emit) RISC-V attribute to record extra information into ELF objects. This feature requires at least binutils 2.32 ๐Ÿ“Œ
  • -malign-data=type โ€” control 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 a canary at guard. Supported locations are global for a global canary, or tls for a per-thread canary in the TLS block ๐Ÿ”

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. There is no default register or offset, as this is entirely for use within the Linux kernel ๐Ÿง So like, if you're not in the kernel, this probably isn't your moment.


๐Ÿ“ RL78 Options ๐Ÿ“

tiny microcontroller time, let's get into it ๐Ÿงš

  • -msim โ€” links in additional target libraries to support operation within a simulator. Perfect for when you're not on real hardware yet ๐ŸŽฎ
  • -mmul=none / -mmul=g10 / -mmul=g13 / -mmul=g14 / -mmul=rl78 โ€” specifies the type of hardware multiplication and division support to be used. Let me break it down ๐Ÿ’…:
    • The simplest is "none", which uses software for both multiplication and division. This is 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".

In addition, a C preprocessor macro is defined, based upon 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. And the G10 or S1 core does not have register banks, so it uses a different calling convention ๐Ÿ‘€ Different core, different rules, that's the whole story.

So like, if this option is set it also picks which flavor of hardware multiply support you're getting, unless an explicit -mmul=none on the command line says "no bestie, not today". So specifying -mcpu=g13 enables the use of the G13 hardware multiply peripheral, and specifying -mcpu=g10 disables the use of hardware multiplications altogether. โœจ

Okay so here's the tea โ˜•: even though the RL78/G14 core is the default target, actually passing -mcpu=g14 or -mcpu=rl78 on the command line does change the behavior of the toolchain, because it also enables G14 hardware multiply support. And if those options are not specified on the command line? Then software multiplication routines get used, even though the code targets the RL78 core. Why? Backwards compatibility with older toolchains that didn't have hardware multiply and divide support. iykyk ๐Ÿ’…

Plus a C preprocessor macro gets defined based on the setting of this option. Possible values are: __RL78_G10__, __RL78_G13__ or __RL78_G14__.

  • -mg10, -mg13, -mg14, -mrl78 โ€” these are literally just aliases for the matching -mcpu= option. They exist for backwards compatibility, bestie. ๐Ÿซถ
  • -mallregs โ€” lets the compiler use all of the available registers. By default r24..r31 are reserved for use in interrupt handlers. Turn this on and those registers can be used in ordinary functions too. ๐Ÿ”ฅ
  • -m64bit-doubles, -m32bit-doubles โ€” makes 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 โ€” says 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, because that makes the interrupt handlers faster. โšก The target option -mg13 needs to be passed for this to work, since 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 if it calls another function.

๐Ÿฆ‹ 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 to specify which instructions are available on the processor you're using. The default value of these options is determined when configuring GCC. Specifying -mcpu=cpu_type overrides the specification of these options. We recommend you use the -mcpu=cpu_type option rather than the options listed above. Periodt.

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.

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.

-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 does not 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. ๐Ÿ˜ญ

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.

On AIX, the -maltivec and -mpowerpc64 options are not enabled or disabled by the -mcpu option at present, because AIX does not have full support for these options. You may still enable or disable them individually if you're sure it'll work in your environment. ๐ŸŒˆ

  • -mtune=cpu_type โ€” set the instruction scheduling parameters for machine type cpu_type, but do not set the architecture type or register usage the way -mcpu=cpu_type does. The same values for cpu_type are used for -mtune as for -mcpu. If both are specified, the code generated uses the architecture and registers set by -mcpu, but the scheduling parameters set by -mtune.
  • -mcmodel=small โ€” generate PowerPC64 code for the small model: the TOC is limited to 64k.
  • -mcmodel=medium โ€” generate 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 โ€” generate 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. ๐Ÿงš

  • -mvrsave, -mno-vrsave โ€” generate VRSAVE instructions when generating AltiVec code.
  • -msecure-plt โ€” generate 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 โ€” generate 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.
  • -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 the use (disable) 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 keep) 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 enable 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 โ€” turns on (or off) codegen that uses the atomic quad word memory instructions, bestie. Heads up though: -mquad-memory-atomic requires 64-bit mode, no exceptions ๐Ÿ’…
  • -mfloat128, -mno-float128 โ€” enables/disables the __float128 keyword for IEEE 128-bit floating point, and picks between software emulation and actual hardware instructions for it.

Okay so the tea โ˜•: the VSX instruction set (-mvsx) must be enabled to use IEEE 128-bit floating point support at all, and it's only supported on Linux.

Default vibe check: -mfloat128 is enabled on PowerPC Linux systems using the VSX instruction set, and disabled everywhere else.

Now if you're on a 64-bit system and you use the ISA 3.0 instruction set (-mpower9-vector or -mcpu=power9), the IEEE 128-bit floating point support also unlocks generation of ISA 3.0 IEEE 128-bit floating point instructions. Otherwise โ€” if you don't ask for ISA 3.0 instructions, or you're targeting a 32-bit big endian system โ€” IEEE 128-bit floating point gets done with software emulation, periodt.

  • -mfloat128-hardware, -mno-float128-hardware โ€” enable/disable using ISA 3.0 hardware instructions to support the __float128 data type. The default 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 (GNU/Linux included, bestie). 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, exactly like -mpowerpc64 does ๐Ÿ‘‘
  • -mfull-toc, -mno-fp-in-toc, -mno-sum-in-toc, -mminimal-toc โ€” these modify generation of the TOC (Table Of Contents), which gets created for every executable file. -mfull-toc is the default pick. In that case, GCC allocates at least one TOC entry for each unique non-automatic variable reference in your program, and it also drops floating-point constants into the TOC. Sad part: only 16,384 entries are available in the TOC ๐Ÿ˜ญ

So if the linker yells at you that you've overflowed the available TOC space, you can shrink how much TOC you're eating with -mno-fp-in-toc and -mno-sum-in-toc. -mno-fp-in-toc stops GCC from putting floating-point constants in the TOC, and -mno-sum-in-toc forces GCC to generate code that calculates the sum of an address and a constant at run time instead of stuffing that sum into the TOC. You can specify one or both. Either one makes GCC produce very slightly slower and larger code, in exchange for conserving TOC space.

Still out of TOC space even with both? Then specify -mminimal-toc instead. This one makes GCC create only one TOC entry per file. When you use it, GCC produces code that's slower and larger, but uses extremely little TOC space. Pro tip vibe: you might only want this on files that contain less frequently-executed code ๐Ÿซถ

  • -maix64, -maix32 โ€” enable 64-bit AIX ABI and calling convention: 64-bit pointers, 64-bit long type, and all 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. It passes floating-point arguments to prototyped functions beyond the register save area (RSA) on the stack in addition to argument FPRs. It does not assume that the most significant double in a 128-bit long double value is properly rounded when comparing values and converting to double. And it uses XL symbol names for long double support routines.

Story time ๐Ÿ“–: 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 don't 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 โ€” it's only necessary when calling subroutines compiled by IBM XL compilers without optimization.

  • -mpe โ€” support IBM RS/6000 SP Parallel Environment (PE). It links an application written to use message passing with special startup code so the application can actually run. The system must have PE installed in the standard location /usr/lpp/ppe.poe/, or the specs file has to be overridden with the -specs= option to point at the appropriate directory location. Also: the Parallel Environment does not support threads, so -mpe and -pthread are incompatible ๐Ÿšซ
  • -malign-natural, -malign-power โ€” on AIX, 32-bit Darwin, and 64-bit PowerPC GNU/Linux, -malign-natural overrides the ABI-defined alignment of larger types (like floating-point doubles) and aligns them on their natural size-based boundary. -malign-power tells 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 -msoft-float, and you must pass the option to GCC when linking too, iykyk.
  • -mmultiple, -mno-multiple โ€” generate code that uses (does not use) the load multiple word instructions and the store multiple word instructions. These 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 don't 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 โ€” generate code that uses (does not use) the load or store instructions that update the base register to the address of the calculated memory location. These are generated by default. If you use -mno-update, there's a small 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 get corrupted data ๐Ÿ’€
  • -mavoid-indexed-addresses, -mno-avoid-indexed-addresses โ€” generate code that tries to avoid (not avoid) the use of indexed load or store instructions. These instructions can incur a performance penalty on Power6 processors in certain situations, like when stepping through large arrays that cross a 16M boundary. This option is enabled by default when targeting Power6 and disabled otherwise.
  • -mfused-madd, -mno-fused-madd โ€” generate code that uses (does not use) the floating-point multiply and accumulate instructions. These are generated by default if hardware floating point is used. Note the glow-up: 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 โœจ
  • -mmulhw, -mno-mulhw โ€” generate code that uses (does not use) the half-word multiply and multiply-accumulate instructions on the IBM 405, 440, 464 and 476 processors. These instructions are generated by default when targeting those processors.
  • -mdlmzb, -mno-dlmzb โ€” generate code that uses (does not use) the string-search dlmzb instruction on the IBM 405, 440, 464 and 476 processors. This instruction is generated by default when targeting those processors.
  • -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 ๐Ÿ“: 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. With -mno-bit-align, that structure is aligned to a 1-byte boundary and is 1 byte in size. Slay.

  • -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.
  • -mrelocatable, -mno-relocatable โ€” generate code that allows (does not 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 the 4-byte locations listed in the .fixup section โ€” a table of 32-bit addresses generated by this option. For this to actually 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 let static executables be relocated at run time, but -mrelocatable-lib does not use the smaller stack alignment of -mrelocatable. Objects compiled with -mrelocatable-lib may be linked with objects compiled with any combination of the -mrelocatable options ๐Ÿซถ
  • -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.
  • -mlittle, -mlittle-endian โ€” on System V.4 and embedded PowerPC systems, compile code for the processor in little-endian mode. The -mlittle-endian option is the same as -mlittle, no cap.
  • -mbig, -mbig-endian โ€” on System V.4 and embedded PowerPC systems, compile code for the processor in big-endian mode. The -mbig-endian option is the same as -mbig, fr fr.
  • -mdynamic-no-pic โ€” on Darwin and Mac OS X systems, compile code so that it is not relocatable, but so that its external references are relocatable. The resulting code is suitable for applications, but not shared libraries ๐Ÿ‘‘
  • -msingle-pic-base โ€” okay so this one says: treat the register you use for PIC addressing as read-only ๐Ÿ’… instead of loading it up in the prologue of every single function. The runtime system is the one responsible for initializing this register with a suitable value before execution even begins. no cap, that's on them ๐Ÿซถ
  • -mprioritize-restricted-insns=priority โ€” this controls the priority handed out to dispatch-slot restricted instructions during the second scheduling pass โœจ. priority takes the value 0, 1, or 2 to assign no, highest, or second-highest priority (respectively) to dispatch-slot restricted instructions. pick your fighter bestie ๐ŸŽ€
  • -msched-costly-dep=dependence_type โ€” this one decides which dependences the target considers costly while it's doing instruction scheduling ๐Ÿ‘‘. 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 whose latency is greater than or equal to number is costly
  • -minsert-sched-nops=scheme โ€” this controls which NOP insertion scheme gets used during the second scheduling pass ๐ŸŒธ. scheme takes one of these values:
    • no โ€” don't insert NOPs, we're doing nothing ๐Ÿšซ
    • 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.
  • -mcall-sysv-eabi
  • -mcall-eabi โ€” specify both -mcall-sysv and -meabi options. two-for-one, we love a bundle ๐ŸŽ€
  • -mcall-sysv-noeabi โ€” specify both -mcall-sysv and -mno-eabi options โœจ
  • -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.
  • -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 an extension ๐Ÿฆ‹. Valid values are: altivec, no-altivec, ibmlongdouble, ieeelongdouble, elfv1, elfv2, and for AIX: vec-extabi, vec-default.
  • -mabi=ibmlongdouble โ€” change the current ABI to use IBM extended-precision long double. This is not likely to work if your system defaults to using IEEE extended-precision long double ๐Ÿ˜ญ. If you change the long double type from IEEE extended-precision, the compiler will issue a warning unless you use the -Wno-psabi option. Requires -mlong-double-128 to be enabled โš ๏ธ
  • -mabi=ieeelongdouble โ€” change the current ABI to use IEEE extended-precision long double. This is 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 โš ๏ธ
  • -mabi=elfv1 โ€” change the current ABI to use the ELFv1 ABI ๐Ÿ’…. This is the default ABI for big-endian PowerPC 64-bit Linux. Overriding the default ABI requires special system support and is likely to fail in spectacular ways ๐Ÿ’€ iconic honestly, but don't.
  • -mabi=elfv2 โ€” change the current ABI to use the ELFv2 ABI โœจ. This is the default ABI for little-endian PowerPC 64-bit Linux. Overriding the default ABI requires special system support and is likely to fail in spectacular ways ๐Ÿ’€ same energy, same warning bestie.
  • -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 ๐Ÿท๏ธ
  • -mprototype
  • -mno-prototype โ€” on System V.4 and embedded PowerPC systems, assume that all calls to variable argument functions are properly prototyped ๐Ÿ‘€. Otherwise, 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.
  • -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.
  • -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 ๐ŸŸก๐Ÿ”ช (yes that's literally the name, we love it)
  • -mvxworks โ€” on System V.4 and embedded PowerPC systems, specify that you are compiling for a VxWorks system ๐Ÿ‘‘
  • -memb โ€” on embedded PowerPC systems, set the PPC_EMB bit in the ELF flags header to indicate that eabi extended relocations are used ๐Ÿ”ง
  • -meabi
  • -mno-eabi โ€” on System V.4 and embedded PowerPC systems, do (or do not) adhere to the Embedded Applications Binary Interface (EABI), which is a set of modifications to the System V.4 specifications ๐Ÿงš. Selecting -meabi means that the stack is aligned to an 8-byte boundary, a function __eabi is 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. Selecting -mno-eabi means that the stack is aligned to a 16-byte boundary, no EABI initialization function is called from main, and the -msdata option 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 is adjacent to the .sdata section. The -msdata=eabi option is incompatible with the -mrelocatable option โš ๏ธ. The -msdata=eabi option 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 the .sdata section. 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. Do not use register r13 to address small data however ๐Ÿ™…. 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 ๐Ÿ’…
  • -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) 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) 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 end of 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. All modules should be compiled with the same -G num value โ€” no mixing, bestie, keep it consistent ๐Ÿ’…
  • -mregnames, -mno-regnames โ€” on System V.4 and embedded PowerPC systems, do (or don't) spit out register names in the assembly output using symbolic forms. ๐Ÿ’…
  • -mlongcall, -mno-longcall โ€” by default, assume every single call is far away, so a longer and wayyy more expensive calling sequence is needed. This is required for calls farther than 32 megabytes (33,554,432 bytes) from the current location. A short call gets generated if the compiler knows the call can't possibly be that far. This setting can be overridden by the shortcall function attribute, or by #pragma longcall(0).

Some linkers can detect out-of-range calls and generate glue code on the fly. On those systems, long calls are unnecessary and just generate slower code. As of this writing, the AIX linker can do this, and so can the GNU linker for PowerPC/64. There's a plan to add this feature to the GNU linker for 32-bit PowerPC systems too.

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 a 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 don't 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 don't mark) calls to __tls_get_addr with a relocation specifying the function argument. The relocation lets the linker reliably associate a function call with argument setup instructions for TLS optimization, which in turn lets GCC 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 bump up 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). Heads up tho โ€” 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 one 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 don't 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 don't provide an estimate that converges after three steps.
  • -mveclibabi=type โ€” specifies the ABI type to use for vectorizing intrinsics using an external library. The only type supported at present is mass, which says to use IBM's Mathematical Acceleration Subsystem (MASS) libraries for vectorizing intrinsics using 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. The MASS libraries must be specified at link time. ๐Ÿ“š
  • -mfriz, -mno-friz โ€” generate (or don't generate) the friz instruction when the -funsafe-math-optimizations option 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 don't 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 don't 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 isn't saved in the prologue, it gets 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 don't 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's 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 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 don't 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 don't 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 don't generate) the MMA instructions. The -mma option requires that the option -mcpu=power10 (or later) is enabled.
  • -mrop-protect, -mno-rop-protect โ€” generate (or don't 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 don't generate) code that will run in privileged state. ๐Ÿ‘‘
  • -mblock-ops-unaligned-vsx, -mno-block-ops-unaligned-vsx โ€” generate (or don't 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 โ€” ok so this is literally just choosing how big the double data type is ๐Ÿ’… -m64bit-doubles makes it 64 bits, -m32bit-doubles makes it 32 bits. The default is -m32bit-doubles, and bestie there's a reason: the RX floating-point hardware only works on 32-bit values. that's the whole tea ๐Ÿซ–
  • -fpu, -nofpu โ€” turns the RX floating-point hardware on (-fpu) or off (-nofpu). Default is on for the RX600 series and off for the RX200 series. but here's the catch: floating-point instructions are only generated for 32-bit floating-point values, so the FPU hardware is not used for doubles if you went and used -m64bit-doubles.
โš ๏ธ Note: if -fpu is enabled then -funsafe-math-optimizations is also enabled automatically. Why? because the RX FPU instructions are themselves unsafe ๐Ÿ˜ญ no cap.
  • -mcpu=name โ€” picks which type of RX CPU you're targeting. Currently three types are supported: the generic RX600 and RX200 series hardware, plus the specific RX610 CPU. Default is RX600. The only difference between RX600 and RX610 is that the RX610 does not support the MVTIPL instruction ๐Ÿ‘€ and the RX200 series has no hardware floating-point unit at all, so -nofpu gets enabled by default when you pick that type.
  • -mbig-endian-data, -mlittle-endian-data โ€” stores data (not code, bestie, only data) in big-endian format. Default is -mlittle-endian-data, i.e. data gets stored in the little-endian format โœจ
  • -msmall-data-limit=N โ€” sets the max size in bytes of global and static variables that can get placed into the small data area. Using the small data area can lead to smaller and faster code, but the size of the area is limited and it is up to the programmer to make sure the area does not overflow ๐Ÿซ  also, when the small data area is used, one of the RX's registers (usually r13) is reserved for pointing to this area, so it's no longer available for the compiler to use. which could mean slower and/or larger code if variables get pushed onto the stack instead of being held in this register.
๐Ÿ’€ Note: common variables (the ones that have not been initialized) and constants are not placed into the small data area, because they are assigned to other sections in the output executable.

The default value is zero, which disables this feature. and note that this feature is not enabled by default with higher optimization levels (-O2 etc) because of the potentially detrimental effects of reserving a register. it's 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 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's 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 an RX instruction. So like, the RX instruction set does allow constants up to 4 bytes long to be used in instructions, but a longer value equates to a longer instruction. so in some circumstances it can be beneficial to restrict the size of constants used in instructions. constants that are too big instead get 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 ๐Ÿ”ฅ which 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 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, because that 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.

the actual register chosen to hold the constant data base address depends upon whether the -msmall-data-limit and/or the -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 it is 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, because 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. iykyk ๐Ÿ’…

๐Ÿฆ‹ S/390 and zSeries Options ๐Ÿฆ‹

these are the -m options defined for the S/390 and zSeries architecture, bestie, and there's a whole lil family of them ๐Ÿ’–

  • -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 the 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 โ€” turn the packed stack layout on (or off). With -mno-packed-stack, the compiler uses all the fields of that 96/160 byte register save area for their default purpose only โ€” and yeah, unused fields still eat up stack space, no refunds ๐Ÿ’€. With -mpacked-stack, the register save slots get densely packed at the top of the register save area and the leftover space gets reused for other stuff, so you're making way better use of the stack you've got. BUT โ€” 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. Rules are rules bestie ๐Ÿ’…

As long as the stack frame backchain isn't used, code generated with -mpacked-stack is call-compatible with code generated with -mno-packed-stack. Lowkey important note though: 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. That 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. If you wanna build a linux kernel, use -msoft-float.

The default is to not use the packed stack layout.

  • -msmall-exec, -mno-small-exec โ€” generate (or don't 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 โ€” with -m31 you get code compliant to the GNU/Linux for S/390 ABI. With -m64 you get code compliant to the GNU/Linux for zSeries ABI. This is what lets GCC in particular generate 64-bit instructions ๐Ÿ‘‘. For the s390 targets the default is -m31, while s390x targets default to -m64.
  • -mzarch, -mesa โ€” -mzarch means generate code using the instructions available on z/Architecture. -mesa means generate code using the instructions available on ESA/390. Heads up: -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. If 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. On top of the GCC low-level builtins, -mzvector enables a set of builtins added for compatibility with AltiVec-style implementations like Power and Cell. 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 don't 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 โ€” generate code that uses (does not use) the floating-point multiply and accumulate instructions. These instructions are generated by default if hardware floating point is used.
  • *-mwarn-framesize=framesize* โ€” emit a warning if the current function exceeds the given frame size. Because this is a compile-time check it doesn't need to be a real problem when the program runs. It is intended to identify functions that most probably cause a stack overflow. It is useful to be used in an environment with limited stack size, e.g. the linux kernel.
  • -mwarn-dynamicstack โ€” emit a warning if the function calls alloca or uses dynamically-sized arrays. This is generally a bad idea with a limited stack size ๐Ÿ˜ฌ.
  • *-mstack-guard=stack-guard*, -mstack-size=stack-size โ€” if these options are provided, the S/390 back end emits additional instructions in the function prologue that trigger a trap if the stack size is stack-guard bytes above the stack-size (remember that the stack on S/390 grows downward). If the stack-guard option is omitted, the smallest power of 2 larger than the frame size of the compiled function is chosen. These options are intended to be used to help debugging stack overflow problems. The additionally emitted code causes only little overhead and hence can also be used in production-like systems without greater performance degradation. The given values have to be exact powers of 2 and stack-size has to be greater than stack-guard without exceeding 64k. In order to be efficient, the extra code makes the assumption that the stack starts at an address aligned to the value given by stack-size. The stack-guard option can only be used in conjunction with stack-size.
  • *-mhotpatch=pre-halfwords*,post-halfwords โ€” if the hotpatch option is enabled, a "hot-patching" function prologue is generated for all functions in the compilation unit. The funtion label is 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.

This option can be overridden 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 without 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 without 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. GCC doesn't generate any DSP instructions at the moment. (so likeโ€ฆ it's giving "same vibe, extra garnish" ๐ŸŽ€)
  • -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. Heads up bestie: 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. 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. fr fr, read that twice ๐Ÿ’€
  • -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. don't use it, bestie ๐Ÿ™ˆ
  • *-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 โ€” Generate software atomic sequences that temporarily disable interrupts by setting SR.IMASK = 1111. This model works only when the program runs in privileged mode and is only suitable for single-core systems. Additional support from the interrupt/exception handling code of the system is not required. This model is enabled by default when the target is sh*-*-linux* and SH1* or SH2*.
    • hard-llcs โ€” Generate hardware atomic sequences using the movli.l and movco.l instructions only. This is only available on SH4A and is suitable for multi-core systems. Since the hardware instructions support only 32 bit atomic variables access to 8 or 16 bit variables is emulated with 32 bit accesses. Code compiled with this option is also compatible with other software atomic model interrupt/exception handling systems if executed on an SH4A system. Additional support from the interrupt/exception handling code of the system is not required for this model.
    • gbr-offset= โ€” This parameter specifies the offset in bytes of the variable in the thread control block structure that should be used by the generated atomic sequences when the soft-tcb model has been selected. For other models this parameter is ignored. The specified value must be an integer multiple of four and in the range 0-1020.
    • strict โ€” This parameter prevents mixed usage of multiple atomic models, even if they are compatible, and makes the compiler generate atomic sequences of the specified model only.
  • -mtas โ€” Generate the tas.b opcode for __atomic_test_and_set. Notice that depending on the particular hardware and software configuration this can degrade overall performance due to the operand cache line flushes that are implied by the tas.b instruction. On multi-core SH4A processors the tas.b instruction must be used with caution since it can result in data corruption for certain cache configurations. data corruption?? not the vibe ๐Ÿ˜ญ
  • -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 generating privileged mode code. Specifying -musermode also implies -mno-inline-ic_invalidate if the inlined code would not work in user mode. -musermode is the default when the target is sh*-*-linux*. If the target is SH1* or SH2* -musermode has no effect, since there is no user mode.
  • *-multcost=number* โ€” Set the cost to assume for a multiply insn.
  • *-mdiv=strategy* โ€” Set the division strategy to be used for integer division operations. strategy can be one of:
    • call-div1 โ€” Calls a library function that uses the single-step division instruction div1 to perform 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 performs 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 do not 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 do not have dynamic shift instructions defaults to call-div1.

When a division strategy has not been specified the default strategy is selected based on the current target. For SH2A the default strategy is to use the divs and divu instructions instead of library function calls. lookup tables? we love a girl who plans ahead โœจ

  • -maccumulate-outgoing-args โ€” Reserve space once for outgoing arguments in the function prologue rather than around each call. Generally beneficial for performance and size. Also needed for unwinding to avoid changing the stack frame around conditional code.
  • *-mdivsi3_libfunc=name* โ€” Set 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 were not present.
  • *-mfixed-range=register-range* โ€” Generate code treating the given register range as fixed registers. A fixed register is one that the register allocator cannot use. This 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. kernel girlies, this one's for you ๐Ÿ’œ
  • -mbranch-cost=num โ€” bestie, this tells the compiler "okay so a branch instruction costs num, that's the vibe." Higher numbers make it try harder to spit out branch-free code whenever it can. If you don't specify anything, the value gets picked based on whatever processor type you're compiling for. ๐Ÿ’…
  • -mzdcbranch, -mno-zdcbranch โ€” assume (or like, don't assume) that the zero displacement conditional branch instructions bt and bf are fast. With -mzdcbranch, the compiler prefers zero displacement branch code sequences. It's on by default when generating code for SH4 and SH4A, and you can turn it off explicitly with -mno-zdcbranch.
  • -mcbranch-force-delay-slot โ€” forces the usage of delay slots for conditional branches, which stuffs the delay slot with a nop if no suitable instruction can be found. By default this option 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 (or doesn't use) the floating-point multiply and accumulate instructions. These get generated by default if hardware floating point is used. Heads up though: 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 from emitting the fsca instruction for sine and cosine approximations. The option -mfsca must be used in combination 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 from emitting the fsrra instruction for reciprocal square root approximations. The option -mfsrra must be used in combination 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 result in faster code on the SH4 processor. ๐Ÿš€
  • -mfdpic โ€” generate code using the FDPIC ABI.

๐ŸŒž Solaris 2 Options ๐ŸŒž

These -m options are supported on Solaris 2:

  • -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 check at runtime whether or not to use them. ๐Ÿ”
  • -mimpure-text โ€” used in addition to -shared, tells the compiler to not pass -z text to the linker when linking a shared object. Using this option, you can link position-dependent code into a shared object.

-mimpure-text suppresses the relocations remain against allocatable but non-writable sections linker error message. However, the necessary relocations trigger copy-on-write, and the shared object is not actually shared across processes.

Instead of using -mimpure-text, you should compile all source code with -fpic or -fPIC. Like, genuinely. Do that instead. ๐Ÿ™ˆ

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 the global register 1, each global register 2 through 4 is then treated as an allocable register that is 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 does not 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 are 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 this cannot be done directly in cross-compilation. You must 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.

-msoft-float changes the calling convention in the output file; therefore, it is 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 in order for this to work. ๐Ÿ˜ญ

  • -mhard-quad-float โ€” generate output containing quad-word (long double) floating-point instructions.
  • -msoft-quad-float โ€” generate output containing library calls for quad-word (long double) floating-point instructions. The functions called are those specified in the SPARC ABI. This is the default.

As of this writing, there are no SPARC implementations that have hardware support for the quad-word floating-point instructions. They all invoke a trap handler for one of these instructions, and then the trap handler emulates the effect of the instruction. Because of the trap handler overhead, this is much slower than calling the ABI library routines. Thus the -msoft-quad-float option is the default.

  • -mno-unaligned-doubles, -munaligned-doubles โ€” assume that doubles have 8-byte alignment. This is the default.

With -munaligned-doubles, GCC assumes that doubles have 8-byte alignment only if they are contained in another type, or if they have an absolute address. Otherwise, it assumes they have 4-byte alignment. Specifying this option avoids some rare compatibility problems with code generated by other compilers. It is not the default because it results in a performance loss, especially for floating-point code. ๐Ÿ’€

  • -muser-mode, -mno-user-mode โ€” do not 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. However, the use of this changed alignment directly violates the SPARC ABI. Thus, 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. ๐Ÿซฃ
  • -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.

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. โญ
  • -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.

Default instruction scheduling parameters are used for values that select an architecture and not an implementation. These are v7, v8, sparclite, sparclet, v9.

Here is a list 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.

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. And 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. it's giving "every chip ever, lovingly catalogued" energy fr fr โœจ

  • -mtune=cpu_type โ€” sets the instruction scheduling parameters for machine type cpu_type, but does NOT set the instruction set or register set that -mcpu=cpu_type does. Same values work for both, but the only ones actually useful here are the ones 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. And 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. ๐ŸŒธ
  • -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. (yes bestie, they stack, it's a whole vibe ๐Ÿ’–)
  • -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. โœจ
  • -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. ๐Ÿ”ฅ
  • -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 โ€” enables the documented workaround for the single erratum of the Atmel AT697F processor (which corresponds to erratum #13 of the AT697E processor). ๐Ÿ› ๏ธ
  • -mfix-ut699 โ€” enables the documented workarounds for the floating-point errata and the data cache nullify errata of the UT699 processor.
  • -mfix-ut700 โ€” enables the documented workaround for the back-to-back store errata of the UT699E/UT700 processor.
  • -mfix-gr712rc โ€” enables 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 โ€” 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. ๐Ÿซถ
  • -mcmodel=which โ€” sets the code model to one of:
    • medlow โ€” the Medium/Low code model: 64-bit addresses, 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. ๐Ÿ˜ญ
  • -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. ๐Ÿ“–

  • -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.

๐ŸŽ€ Options for System V ๐ŸŽ€

These additional options are available on System V Release 4 for compatibility with other compilers on those systems:

  • -G โ€” create a shared object. It is recommended that -symbolic or -shared be used instead.
  • -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.
  • -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. (a whole flag just vibing, doing nothing, iconic honestly) ๐Ÿ’…

โญ 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 โ€” okay so these two are a lil toggle: do not use (or 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. โœจ
  • -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. periodt. ๐Ÿ’–

  • -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. ๐Ÿ‘€
  • -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 โ€” do not output certain jump instructions (aobleq and so on) that the Unix assembler for the VAX cannot handle across long ranges. ๐Ÿšซ
  • -mgnu โ€” do output those jump instructions, on the assumption that the GNU assembler is being used. โœจ
  • -mg โ€” output code for G-format floating-point numbers instead of D-format. ๐Ÿ’…

โœจ Visium Options โœจ

  • -mdebug โ€” a program which performs file I/O and is destined to run on an MCM target should be linked with this option. It causes the libraries libc.a and libdebug.a to be linked. The program should be run on the target under the control of the GDB remote debugging stub. ๐Ÿ›
  • -msim โ€” a program which performs file I/O and is destined to run on the simulator should be linked with 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. ๐ŸŒŠ
  • -mno-fpu, -msoft-float โ€” generate code containing library calls for floating-point. -msoft-float changes the calling convention in the output file; therefore, it is 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 in order for this to work. โš ๏ธ
  • -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. 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. ๐Ÿ‘‘
  • -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 would. ๐ŸŽฏ
  • -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 the 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. ๐Ÿ”

โœจ 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. ๐Ÿ’…
  • -mdebug-main=prefix โ€” flag the first routine whose name starts with prefix as the main routine for the debugger. ๐Ÿ•ต๏ธ
  • -mmalloc64 โ€” default to 64-bit memory allocation routines. ๐Ÿง 
  • -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. โš ๏ธ

โœจ 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.

  • -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__. ๐Ÿš€
  • -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. ๐Ÿ’ซ
  • -Xbind-lazy โ€” enable lazy binding of function calls. This option is equivalent to -Wl,-z,now and is defined for compatibility with Diab. ๐Ÿ˜ด
  • -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.

  • -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. ๐Ÿ”ฅ

The choices for cpu-type are:

  • native โ€” this one's iconic: it picks the CPU to generate code for at compile time by literally sniffing out what processor type the compiling machine is. Using -march=native enables every instruction subset the local machine supports (which means, bestie, the result might not run on different machines ๐Ÿ‘€ โ€” it's giving "works on my machine" energy fr). And -mtune=native produces code optimized for the local machine, but only under the constraints of whatever instruction set you selected. ๐Ÿซถ
  • x86-64 โ€” a generic CPU with 64-bit extensions. Simple. Clean. Does what it says. โœจ
  • x86-64-v2
  • x86-64-v3
  • x86-64-v4 โ€” these three cpu-type choices 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 that particular micro-architecture level. ๐Ÿ’…

Since these cpu-type values do not have a corresponding -mtune setting, using -march with these values enables generic tuning. Want specific tuning instead? Enable it with the -mtune=other-cpu-type option, using an appropriate other-cpu-type value. ๐ŸŽ€

  • i386 โ€” the original Intel i386 CPU. The blueprint, the blueprint. ๐Ÿ‘‘
  • i486 โ€” Intel i486 CPU. (No scheduling is implemented for this chip.) ๐Ÿ’€
  • 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. ๐ŸŒธ
  • pentium2 โ€” Intel Pentium II CPU, based on Pentium Pro core with MMX instruction set support.
  • pentium3
  • pentium3m โ€” Intel Pentium III CPU, based on Pentium Pro core with MMX and SSE instruction set support.
  • pentium-m โ€” Intel Pentium M; a low-power version of the Intel Pentium III CPU with MMX, SSE and SSE2 instruction set support. Used by Centrino notebooks. ๐ŸŽ€
  • pentium4
  • pentium4m โ€” Intel Pentium 4 CPU with MMX, SSE and SSE2 instruction set support.
  • prescott โ€” improved version of Intel Pentium 4 CPU with MMX, SSE, SSE2 and SSE3 instruction set support.
  • nocona โ€” improved version of Intel Pentium 4 CPU with 64-bit extensions, MMX, SSE, SSE2 and SSE3 instruction set support.
  • core2 โ€” Intel Core 2 CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support.
  • nehalem โ€” Intel Nehalem CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2 and POPCNT instruction set support.
  • westmere โ€” Intel Westmere CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES and PCLMUL instruction set support.
  • sandybridge โ€” Intel Sandy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AES and PCLMUL instruction set support.
  • ivybridge โ€” Intel Ivy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AES, 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, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2 and F16C instruction set support.
  • broadwell โ€” Intel Broadwell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, 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, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC and XSAVES 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, AES, PREFETCHW, PCLMUL and RDRND instruction set support.
  • goldmont โ€” Intel Goldmont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT 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, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT, FSGSBASE, PTWRITE, RDPID, SGX and UMIP instruction set support. ๐Ÿ’…
  • tremont โ€” Intel Tremont CPU with 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, UMIP, GFNI-SSE, CLWB, MOVDIRI, MOVDIR64B, CLDEMOTE and WAITPKG instruction set support.
  • knl โ€” Intel Knight's Landing CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, PREFETCHWT1, AVX512F, AVX512PF, AVX512ER and AVX512CD instruction set support. ๐Ÿ”ฅ
  • knm โ€” Intel Knights Mill CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, PREFETCHWT1, AVX512F, AVX512PF, AVX512ER, AVX512CD, AVX5124VNNIW, AVX5124FMAPS and AVX512VPOPCNTDQ instruction set support.
  • skylake-avx512 โ€” Intel Skylake Server CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ and AVX512CD instruction set support.
  • cannonlake โ€” Intel Cannonlake Server CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VBMI, AVX512IFMA, SHA and UMIP instruction set support.
  • icelake-client โ€” Intel Icelake Client CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VBMI, AVX512IFMA, SHA, CLWB, UMIP, RDPID, GFNI, AVX512VBMI2, AVX512VPOPCNTDQ, AVX512BITALG, AVX512VNNI, VPCLMULQDQ, VAES instruction set support. ๐ŸงŠโœจ
  • icelake-server โ€” Intel Icelake Server CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VBMI, AVX512IFMA, SHA, CLWB, UMIP, RDPID, GFNI, AVX512VBMI2, AVX512VPOPCNTDQ, AVX512BITALG, AVX512VNNI, VPCLMULQDQ, VAES, PCONFIG and WBNOINVD instruction set support.
  • cascadelake โ€” Intel Cascadelake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD and AVX512VNNI instruction set support.
  • cooperlake โ€” Intel cooperlake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VNNI and AVX512BF16 instruction set support.
  • tigerlake โ€” Intel Tigerlake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VBMI, AVX512IFMA, SHA, CLWB, UMIP, RDPID, GFNI, AVX512VBMI2, AVX512VPOPCNTDQ, AVX512BITALG, AVX512VNNI, VPCLMULQDQ, VAES, PCONFIG, WBNOINVD, MOVDIRI, MOVDIR64B, AVX512VP2INTERSECT and KEYLOCKER instruction set support. ๐Ÿฏ
  • sapphirerapids โ€” Intel sapphirerapids 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, 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 and AVX512BF16 instruction set support. ๐Ÿ’Ž
  • alderlake โ€” Intel Alderlake CPU with 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, UMIP, 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 CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VBMI, AVX512IFMA, SHA, CLWB, UMIP, RDPID, GFNI, AVX512VBMI2, AVX512VPOPCNTDQ, AVX512BITALG, AVX512VNNI, VPCLMULQDQ, VAES instruction set support. ๐Ÿ’…
  • k6 โ€” AMD K6 CPU with MMX instruction set support.
  • k6-2, k6-3 โ€” improved versions of the AMD K6 CPU with MMX and 3DNow! instruction set support. โœจ
  • athlon, athlon-tbird โ€” AMD Athlon CPU with MMX, 3dNOW!, enhanced 3DNow! and SSE prefetch instructions support.
  • athlon-4, athlon-xp, athlon-mp โ€” improved AMD Athlon CPU with MMX, 3DNow!, enhanced 3DNow! and full SSE instruction set support.
  • 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 AMD K8 cores 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.)
  • znver4 โ€” 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, AVX512F, AVX512DQ, AVX512IFMA, AVX512CD, AVX512BW, AVX512VL, AVX512BF16, AVX512VBMI, AVX512VBMI2, AVX512VNNI, AVX512BITALG, AVX512VPOPCNTDQ, GFNI 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 CPU, dealt in same way as i486 with additional MMX instruction set support.
  • winchip2 โ€” IDT WinChip 2 CPU, dealt in same way as i486 with additional MMX and 3DNow! instruction set support.
  • c3 โ€” VIA C3 CPU with MMX and 3DNow! instruction set support. (No scheduling is implemented for this chip.) ๐Ÿ˜ญ
  • c3-2 โ€” VIA C3-2 (Nehemiah/C5XL) CPU with MMX and SSE instruction set support. (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 with MMX and 3DNow! instruction set support. (No scheduling is implemented for this chip.)
  • nehemiah โ€” VIA Eden Nehemiah CPU with MMX and SSE instruction set support. (No scheduling is implemented for this chip.)
  • esther โ€” VIA Eden Esther CPU with MMX, SSE, SSE2 and SSE3 instruction set support. (No scheduling is implemented for this chip.)
  • eden-x2 โ€” VIA Eden X2 CPU with x86-64, MMX, SSE, SSE2 and SSE3 instruction set support. (No scheduling is implemented for this chip.)
  • eden-x4 โ€” VIA Eden X4 CPU with x86-64, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, AVX and AVX2 instruction set support. (No scheduling is implemented for this chip.)
  • nano โ€” generic VIA Nano CPU with x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)
  • nano-1000 โ€” VIA Nano 1xxx CPU with x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)
  • nano-2000 โ€” VIA Nano 2xxx CPU with x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)
  • nano-3000 โ€” VIA Nano 3xxx CPU with 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 with 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 with 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 with MMX and 3DNow! instruction set support. ๐Ÿฆ‹

-mtune=cpu-type ๐ŸŽ€

Okay bestie, so this one is the vibe tuner, not the feature unlocker, and the distinction is everything.

-mtune=cpu-type tunes everything applicable about the generated code to cpu-type โ€” except for the ABI and the set of available instructions. So while picking a specific cpu-type schedules things appropriately for that particular chip, the compiler does not generate any code that cannot run on the default machine type unless you also use a -march=cpu-type option. ๐Ÿ‘‘

Like, fr fr: 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. Cute, right? ๐Ÿ’…

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. ๐Ÿซถ

Heads up: as new processors are deployed in the marketplace, the behavior of this option will change. So 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. Not a bug, just a moving target, bestie. ๐Ÿ˜ญ

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. That's the whole tea. ๐Ÿ“

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. ๐Ÿ’–

Same warning as above, and it's giving deja vu: 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. โญ

And yep, there is no -march=intel option either, 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 โ€” okay so this one is literally just a deprecated synonym for -mtune. that's it. that's the whole thing. use -mtune bestie, the glow-up already happened ๐Ÿ’…
  • -mfpmath=unit โ€” tells GCC which unit should be doing your floating-point arithmetic. your choices, queen:
    • 387 โ€” uses the standard 387 floating-point coprocessor that's chilling on the majority of chips, and emulated everywhere else. code compiled with this runs almost everywhere which is iconic tbh. the catch? temporary results get computed in 80-bit precision instead of whatever precision the type actually specified, so you get slightly different results compared to most other chips ๐Ÿ˜ญ. peep -ffloat-store for the whole detailed breakdown. this is the default choice for non-Darwin x86-32 targets.
    • sse โ€” uses the scalar floating-point instructions sitting in the SSE instruction set. supported by Pentium III and newer chips, and over in AMD land by the Athlon-4, Athlon XP and Athlon MP chips ๐Ÿฆ‹. the earlier version of SSE only supports single-precision arithmetic, so double and extended-precision arithmetic still get done with 387. a later version โ€” only present in Pentium 4 and AMD x86-64 chips โ€” supports double-precision too. for the x86-32 compiler you must use -march=cpu-type, -msse or -msse2 switches to enable SSE extensions and make this option actually do something. for the x86-64 compiler those extensions are enabled by default, no effort required โœจ. the resulting code should be considerably faster in the majority of cases and dodges the numerical instability problems of 387 code, but it 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 for x86-32 targets with the SSE2 instruction set when -ffast-math is enabled.
    • sse,387 / sse+387 / both โ€” attempts 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 one with care though, because it's still experimental โ€” the GCC register allocator does not model separate functional units well, resulting in unstable performance ๐Ÿ’€.
  • -masm=dialect โ€” outputs assembly instructions using the dialect you picked. it 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, sorry bestie.
  • -mieee-fp, -mno-ieee-fp โ€” controls 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 โ€” generates output containing 80387 instructions for floating point ๐Ÿ”ฅ.
  • -mno-80387, -msoft-float โ€” generates 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. no shortcuts, babe.

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's no FPU โ€” the whole idea being that the operating system should emulate an FPU. this option makes such values get 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. it gets overridden when -march indicates that the target CPU always has an FPU, so the instruction doesn't need emulation. heads up: these instructions are not generated unless you also use the -funsafe-math-optimizations switch.
  • -malign-double, -mno-align-double โ€” controls 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 ๐Ÿ’€. 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. lowkey a big deal.
  • -m96bit-long-double, -m128bit-long-double โ€” these switches control the size of the 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) prefer long double to be aligned to an 8- or 16-byte boundary. in arrays or structures conforming to the ABI, this is not possible ๐Ÿ™ˆ. so specifying -m128bit-long-double aligns long double to a 16-byte boundary by padding the long double with an additional 32-bit zero โœจ. in the x86-64 compiler, -m128bit-long-double is the default choice, as its ABI specifies that long double is aligned on a 16-byte boundary. notice that neither of these options enables any extra precision over the x87 standard of 80 bits for a long double โ€” no extra slay, just alignment.
โš ๏ธ 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.
  • -mlong-double-64, -mlong-double-80, -mlong-double-128 โ€” these switches control the size of the long double type. 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. (yes, same warning, different option, we're being thorough bestie ๐Ÿซถ)
  • -malign-data=type โ€” controls how GCC aligns variables. the supported values for type are: compat uses increased alignment value compatible uses GCC 4.8 and earlier, abi uses alignment value as specified by the psABI, and cacheline uses increased alignment value to match the cache line size. compat is the default ๐Ÿ’….
  • -mlarge-data-threshold=threshold โ€” when -mcmodel=medium is specified, data objects larger than threshold are placed in the large data section. this value must be the same across all objects linked into the binary, and defaults to 65535 ๐Ÿ”ข.
  • -mrtd โ€” uses a different function-calling convention, in which 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 ๐Ÿ‘‘. you can specify that an individual function is called with this calling sequence using 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.) so like, be normal about it.

  • -mregparm=num โ€” controls 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. all of them. no exceptions ๐Ÿ’€.
  • -msseregparm โ€” uses 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.
  • -mvect8-ret-in-mem โ€” returns 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 โ€” it's giving legacy-support-only, fr fr.
  • -mpc32, -mpc64, -mpc80 โ€” sets the 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), and -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 ๐Ÿ™ˆ.

Okay bestie, we're still deep in the x86 options and it's giving compiler sorcery โœจ. First up, a little tea about floating-point rounding: setting the rounding of floating-point operations to less than the default 80 bits can speed some programs by 2% or more. Butโ€”and this is a big butโ€”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. So like, know the risks, babe. ๐Ÿ’…

  • -mdaz-ftz โ€” The flush-to-zero (FTZ) and denormals-are-zero (DAZ) flags in the MXCSR register are used to control floating-point calculations. SSE and AVX instructions including scalar and vector instructions could benefit from enabling the FTZ and DAZ flags when -mdaz-ftz is specified. Don't set FTZ/DAZ flags when -mno-daz-ftz is specified. ๐Ÿงš
  • -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. ๐Ÿ’€
  • -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. ๐ŸŒธ

  • -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, -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 โ€” 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 or CLDEMOTE extended instruction sets. Each has a corresponding -mno- option to disable use of these instructions.

These extensions are also available as built-in functions: see x86 Built-in Functions, for details of the functions enabled and disabled by these switches.

To generate SSE/SSE2 instructions automatically from floating-point code (as opposed to 387 instructions), see -mfpmath=sse.

GCC depresses SSEx instructions when -mavx is used. Instead, it generates new AVX instructions or AVX equivalence for all SSEx instructions when needed.

These options enable GCC to use these extended instructions in generated code, even without -mfpmath=sse. Applications that perform run-time CPU detection must compile separate files for each supported architecture, using the appropriate flags. In particular, the file containing the CPU detection code should be compiled without these options. ๐Ÿ”ฅ

  • -mdump-tune-features โ€” This option instructs GCC to dump the names of the x86 performance tuning features and default settings. The names can be used in -mtune-ctrl=feature-list. ๐Ÿ‘‘
  • -mtune-ctrl=feature-list โ€” This option is used to do fine grain control of x86 code generation features. feature-list is a comma separated list of feature names. See also -mdump-tune-features. When specified, the feature is turned on if it is not preceded with ^, otherwise, it is turned off. -mtune-ctrl=feature-list is intended to be used by GCC developers. Using it may lead to code paths not covered by testing and can potentially result in compiler ICEs or runtime errors. ๐Ÿ’€
  • -mno-default โ€” This option instructs GCC to turn off all tunable features. See also -mtune-ctrl=feature-list and -mdump-tune-features. ๐Ÿฆ‹
  • -mcld โ€” This option instructs GCC to emit a "cld" instruction in the prologue of functions that use string instructions. String instructions depend on the DF flag to select between autoincrement or autodecrement mode. While the ABI specifies the DF flag to be cleared on function entry, some operating systems violate this specification by not clearing the DF flag in their exception dispatchers. The exception handler can be invoked with the DF flag set, which leads to 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. Generation of "cld" instructions can be suppressed with the -mno-cld compiler option in this case. ๐ŸŒˆ
  • -mvzeroupper โ€” This option instructs GCC to emit a "vzeroupper" instruction before a transfer of control flow out of the function to minimize the AVX to SSE transition penalty as well as remove unnecessary "zeroupper" intrinsics. โœจ
  • -mprefer-avx128 โ€” This option instructs GCC to use 128-bit AVX instructions instead of 256-bit AVX instructions in the auto-vectorizer. ๐Ÿ’…
  • -mprefer-vector-width=opt โ€” This option instructs GCC to use opt-bit vector width in instructions instead of default on the selected platform.
    • none โ€” No extra limitations applied to GCC other than 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 โ€” This option enables GCC to generate "CMPXCHG16B" instructions in 64-bit code to implement compare-and-exchange operations on 16-byte aligned 128-bit objects. This is useful for atomic updates of data structures exceeding one machine word in size. The compiler uses this instruction to implement __sync Builtins. However, for __atomic Builtins operating on 128-bit integers, a library call is always used. ๐ŸŽ€
  • -msahf โ€” This option enables generation of "SAHF" instructions in 64-bit code. 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 which are supported by AMD64. These are load and store instructions, respectively, for certain status flags. In 64-bit mode, the "SAHF" instruction is used to optimize "fmod", "drem", and "remainder" built-in functions; see Other Builtins for details. ๐Ÿงš
  • -mmovbe โ€” This option enables use of the "movbe" instruction to implement "__builtin_bswap32" and "__builtin_bswap64". ๐ŸŒธ
  • -mshstk โ€” The -mshstk option enables shadow stack built-in functions from x86 Control-flow Enforcement Technology (CET). ๐Ÿ’–
  • -mcrc32 โ€” This option enables built-in functions "__builtin_ia32_crc32qi", "__builtin_ia32_crc32hi", "__builtin_ia32_crc32si" and "__builtin_ia32_crc32di" to generate the "crc32" machine instruction. ๐Ÿ‘‘
  • -mmwait โ€” okay bestie, this one enables 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 (and their vectorized variants RCPPS and RSQRTPS) with an additional Newton-Raphson step to increase precision instead of DIVSS and SQRTSS (and their vectorized variants) for single-precision floating-point arguments. These instructions are generated only when -funsafe-math-optimizations is enabled together with -ffinite-math-only and -fno-trapping-math. Note that 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). ๐Ÿ˜ญ

Note that GCC implements 1.0f/sqrtf(x) in terms of RSQRTSS (or RSQRTPS) already with -ffast-math (or the above option combination), and doesn't need -mrecip.

Also note that GCC emits the above sequence with 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. no cap.

  • -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 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. ๐Ÿ’…

  • -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.

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 corresponding function type when -mveclibabi=svml is used, and:

__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. ๐Ÿฆ‹

  • -mabi=name โ€” Generate code for the specified calling convention. Permissible values are sysv for the ABI used on GNU/Linux and other systems, and ms for the Microsoft ABI. The default is to use the Microsoft ABI when targeting Microsoft Windows and the SysV ABI on all other systems. You can control this behavior for specific functions by using the function attributes ms_abi and sysv_abi.
  • -mforce-indirect-call โ€” Force all calls to functions to be indirect. This is useful when using Intel Processor Trace where it generates more precise timing information for function calls. ๐Ÿ”ฅ
  • -mmanual-endbr โ€” Insert ENDBR instruction at function entry only via the cf_check function attribute. This is useful when used with the option -fcf-protection=branch to control ENDBR insertion at the function entry.
  • -mcall-ms2sysv-xlogues โ€” Due to 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 these registers is emitted inline, resulting in fairly lengthy prologues and epilogues. Using -mcall-ms2sysv-xlogues emits prologues and epilogues that use stubs in the static portion of libgcc to perform these saves and restores, thus reducing function size at the cost of a few extra instructions.
  • -mtls-dialect=type โ€” Generate 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. ๐Ÿ’…
  • -mpush-args / -mno-push-args โ€” Use PUSH operations to store outgoing parameters. This method is shorter and usually equally fast as method using SUB/MOV operations and is enabled by default. In some cases disabling it may improve performance because of improved scheduling and reduced dependencies.
  • -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 because of reduced dependencies, improved scheduling and reduced stack usage when the preferred stack boundary is not equal to 2. The drawback is a notable increase in code size. This switch implies -mno-push-args.
  • -mthreads โ€” Support 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.
  • -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 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. periodt ๐Ÿ’…


  • -mno-align-stringops โ€” bestie, this says do not align the destination of inlined string operations. It makes your code smaller and faster if the destination is already aligned โ€” but GCC doesn't know that, so it's just doing extra work for no reason ๐Ÿ™ˆ
  • -minline-all-stringops โ€” okay so by default GCC only inlines string ops when the destination is known to be aligned to at least a 4-byte boundary. This flag unlocks way more inlining and grows your code size, but it can genuinely slay performance for code that leans on fast memcpy and memset for short lengths. It also turns on inline expansion of strlen for all pointer alignments. iconic โœจ
  • -minline-stringops-dynamically โ€” for string operations of unknown size, this does run-time checks: inline code for small blocks, library call for large blocks. little bit of both, main character energy ๐ŸŽ€
  • -mstringop-strategy=alg โ€” overrides the internal decision heuristic for which algorithm gets used to inline 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 for whether __builtin_memcpy should be inlined, and which inline algorithm to use when the expected size of the copy is known. strategy is a comma-separated list of alg:max_size:dest_align triplets. alg is specified in -mstringop-strategy, max_size says the max byte size that inline algorithm alg is allowed for. For the last triplet, max_size must be -1. The max_size values in the list must be in increasing order. The minimal byte size for alg is 0 for the first triplet, and max_size + 1 of the preceding range. no cap, just triplet math ๐Ÿ’€
  • -mmemset-strategy=strategy โ€” literally the same vibe as -mmemcpy-strategy= except it controls __builtin_memset expansion instead.
  • -momit-leaf-frame-pointer โ€” don't keep the frame pointer in a register for leaf functions. This skips the instructions to save, set up, and restore frame pointers, and frees up an extra register in leaf functions. Heads up: -fomit-leaf-frame-pointer removes the frame pointer for leaf functions, which might make debugging harder. ๐Ÿ˜ญ
  • -mtls-direct-seg-refs
  • -mno-tls-direct-seg-refs โ€” controls whether TLS variables can be accessed with offsets from the TLS segment register (%gs for 32-bit, %fs for 64-bit), or whether the thread base pointer has to be added. Whether this is even valid depends on your operating system and whether it maps the segment to cover the entire TLS area. ๐Ÿฆ‹

For systems using the GNU C Library, the default is on.

  • -msse2avx
  • -mno-sse2avx โ€” tells the assembler to encode SSE instructions with the VEX prefix. The option -mavx turns this on by default. โœจ
  • -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. ๐Ÿ’€
  • -mrecord-mcount
  • -mno-record-mcount โ€” if profiling is active (-pg), generate a __mcount_loc section containing pointers to each profiling call. This is useful for automatically patching and out calls. ๐Ÿงš
  • -mnop-mcount
  • -mno-nop-mcount โ€” if profiling is active (-pg), generate the calls to the profiling functions as NOPs. This is useful when they should be patched in later dynamically. This is likely only useful together with -mrecord-mcount. ๐Ÿ”ฅ
  • -minstrument-return=type โ€” instrument function exit in -pg -mfentry instrumented functions with a call to the specified function. This only instruments true returns ending with ret, not sibling calls ending with jump. Valid types are none to not instrument, call to generate a call to __return__, or nop5 to generate a 5 byte nop. ๐Ÿ‘‘
  • -mrecord-return
  • -mno-record-return โ€” generate a __return_loc section pointing to all return instrumentation code.
  • -mfentry-name=name โ€” set the name of the __fentry__ symbol called at function entry for -pg -mfentry functions.
  • -mfentry-section=name โ€” set the name of the section to record -mrecord-mcount calls (default __mcount_loc).
  • -mskip-rax-setup
  • -mno-skip-rax-setup โ€” when generating code for the x86-64 architecture with SSE extensions disabled, -mskip-rax-setup can be used to skip setting up the RAX register when there are no variable arguments passed in vector registers.
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 jump to a random location. GCC 4.4 or newer doesn't have those issues, regardless of the RAX register value. ๐Ÿ˜ญ
  • -m8bit-idiv
  • -mno-8bit-idiv โ€” on some processors, like Intel Atom, 8-bit unsigned integer divide is much faster than 32-bit/64-bit integer divide. This option generates a run-time check: if both dividend and divisor are within the range of 0 to 255, 8-bit unsigned integer divide is used instead of 32-bit/64-bit integer divide. ate ๐Ÿ’…
  • -mavx256-split-unaligned-load
  • -mavx256-split-unaligned-store โ€” split 32-byte AVX unaligned load and store.
  • -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 global canary or tls for per-thread canary in the TLS block (the default). This option only has an effect when -fstack-protector or -fstack-protector-all is specified. ๐Ÿ›ก๏ธ

With the tls choice, the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset additionally 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 โ€” generate code that uses only the general-purpose registers. This stops the compiler from using floating-point, vector, mask, and bound registers. strict queen behavior ๐Ÿ’œ
  • -mindirect-branch=choice โ€” convert indirect call and jump with 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 inlined call and return thunk. thunk-extern converts indirect call and jump to external call and return thunk provided in a separate object file. You can control this behavior for a specific function by using the function attribute indirect_branch. ๐ŸŒˆ
Note that -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 that -mindirect-branch=thunk-extern is compatible with -fcf-protection=branch, since the external thunk can be made to enable control-flow check. โœจ
  • -mfunction-return=choice โ€” convert function return with 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 inlined call and return thunk. thunk-extern converts function return to external call and return thunk provided in a separate object file. You can control this behavior for a specific function by using the function attribute function_return. ๐ŸŽ€
Note that -mindirect-return=thunk-extern is compatible with -fcf-protection=branch, since the external thunk can be made to enable control-flow check.
Note that -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 โ€” force indirect call and jump via register. no detours, we're going straight through ๐Ÿฆ‹
  • -mharden-sls=choice โ€” generate code to mitigate against straight line speculation (SLS) with 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 โ€” add a CS prefix to call and jmp to indirect thunk with branch target in r8-r15 registers, so that the call and jmp instruction length is 6 bytes โ€” letting them be replaced with lfence; call *%r8-r15 or lfence; jmp *%r8-r15 at run-time. ๐Ÿ”ฅ

These -m switches are supported in addition to the above on x86-64 processors in 64-bit environments.

  • -m32
  • -m64
  • -mx32
  • -m16
  • -miamcu โ€” generate code for a 16-bit, 32-bit or 64-bit environment. The -m32 option sets int, long, and pointer types to 32 bits, and generates code that runs in 32-bit mode. ๐ŸŒธ

The -m64 option sets int to 32 bits and long and pointer types to 64 bits, and generates code for the x86-64 architecture. For Darwin only, the -m64 option also turns off the -fno-pic and -mdynamic-no-pic options.

The -mx32 option sets int, long, and pointer types to 32 bits, and generates code for the x86-64 architecture.

The -m16 option is the same as -m32, except for the fact that it outputs the .code16gcc assembly directive at the beginning of the assembly output so that the binary can run in 16-bit mode.

The -miamcu option generates code which conforms to Intel MCU psABI. It requires the -m32 option to be turned on. ๐Ÿ’…

  • -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 is not modified by signal or interrupt handlers, and therefore can be used for temporary data without adjusting the stack pointer. The flag -mno-red-zone disables this red zone. ๐Ÿ“
  • -mcmodel=small โ€” the small code model, bestie. The program and its symbols have to be linked in the lower 2 GB of the address space. Pointers are 64 bits. Programs can be statically or dynamically linked. And guess what โ€” this is the default code model. It's giving main character energy by default, periodt. ๐Ÿ’…
  • -mcmodel=kernel โ€” the kernel code model. The kernel runs in the negative 2 GB of the address space. You have to use this model for Linux kernel code. No wiggle room, no vibe check, it's mandatory. ๐Ÿ‘‘
  • -mcmodel=medium โ€” the medium model. The program is linked in the lower 2 GB of the address space, and small symbols get placed there too. Symbols with sizes larger than -mlarge-data-threshold get yeeted into large data or BSS sections and can live above 2GB. Programs can be statically or dynamically linked. ๐Ÿฆ‹
  • -mcmodel=large โ€” the large model. This one makes zero assumptions about addresses and sizes of sections. It just doesn't speculate. Iconic, honestly. โœจ
  • -maddress-mode=long โ€” generates code for long address mode. Only supported for 64-bit and x32 environments. It's the default address mode for 64-bit environments. ๐ŸŽ€
  • -maddress-mode=short โ€” generates code for short address mode. Only supported for 32-bit and x32 environments. And it's the default address mode for 32-bit and x32 environments. ๐Ÿ’œ
  • -mneeded, -mno-needed โ€” emit the GNU_PROPERTY_X86_ISA_1_NEEDED GNU property for Linux target, which is basically your binary going "hey, this is the micro-architecture ISA level you need to execute me bestie." ๐ŸŒธ

๐Ÿ’ป x86 Windows Options ๐Ÿ’ป

These extra options are available for Microsoft Windows targets, iykyk:

  • -mconsole โ€” says a console application is what we're generating, by telling the linker to set the PE header subsystem type that console applications need. Available for Cygwin and MinGW targets, and it's enabled by default on those targets. ๐Ÿซถ
  • -mdll โ€” available for Cygwin and MinGW targets. It says a DLL โ€” a dynamic link library โ€” is what we're generating, which enables the selection of the required runtime startup object and entry point. Slay. ๐Ÿ’…
  • -mnop-fun-dllimport โ€” available for Cygwin and MinGW targets. It says the "dllimport" attribute should be ignored. Not me telling you to ignore things ๐Ÿ˜ญ
  • -mthread โ€” available for MinGW targets. It says MinGW-specific thread support is what's being used. ๐Ÿงต
  • -municode โ€” available for MinGW-w64 targets. It makes the "UNICODE" preprocessor macro get predefined, and it picks Unicode-capable runtime startup code. Very demure, very Unicode. โœจ
  • -mwin32 โ€” available for Cygwin and MinGW targets. It says the typical Microsoft Windows predefined macros get set in the pre-processor, but it does not influence the choice of runtime library/startup code. So it's a vibe, not a decision-maker. ๐Ÿ™ˆ
  • -mwindows โ€” available for Cygwin and MinGW targets. It says a GUI application is what's being generated, by instructing the linker to set the PE header subsystem type appropriately. ๐ŸŒˆ
  • -fno-set-stack-executable โ€” available for MinGW targets. It says the executable flag for the stack used by nested functions isn't set. This is necessary for binaries running in kernel mode of Microsoft Windows, because there the User32 API โ€” the one that's used to set executable privileges โ€” isn't available. ๐Ÿ‘‘
  • -fwritable-relocated-rdata โ€” available for MinGW and Cygwin targets. It says relocated-data in read-only section gets put into the ".data" section. This is necessary for older runtimes that don't support modification of ".rdata" sections for pseudo-relocation. ๐ŸŽ€
  • -mpe-aligned-commons โ€” available for Cygwin and MinGW targets. It says the GNU extension to the PE file format that permits the correct alignment of COMMON variables should be used when generating code. It's enabled by default if GCC detects that the target assembler found during configuration supports the feature. ๐Ÿ’–
Also, check under x86 Options for the standard options, bestie โ€” don't come for me, they're just listed there.

๐Ÿฆ‹ Xstormy16 Options ๐Ÿฆ‹

These options are defined for Xstormy16:

  • -msim โ€” choose startup files and linker script suitable for the simulator. That's it, that's the whole vibe. โœจ

๐ŸŒธ Xtensa Options ๐ŸŒธ

These options are supported for Xtensa targets:

  • -mconst16, -mno-const16 โ€” enable or disable use of "CONST16" instructions for loading constant values. Fun fact: 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 use of 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 fused multiply/add and multiply/subtract instructions forces the compiler to use separate instructions for the multiply and add/subtract operations. This may be desirable in some cases where strict IEEE 754-compliant results are required: the fused multiply add/subtract instructions don't round the intermediate result, thereby producing results with more bits of precision than the IEEE standard specifies. Disabling fused multiply add/subtract instructions also ensures the program output isn't sensitive to the compiler's ability to combine multiply and add/subtract operations. Math girlies, this one's for you. ๐Ÿงฎโœจ
  • -mserialize-volatile, -mno-serialize-volatile โ€” when this option is enabled, GCC inserts "MEMW" instructions before "volatile" memory references to guarantee sequential consistency. The default is -mserialize-volatile. Use -mno-serialize-volatile to omit the "MEMW" instructions. ๐ŸŽ€
  • -mforce-no-pic โ€” for targets like GNU/Linux, where all user-mode Xtensa code must be position-independent code (PIC), this option disables PIC for compiling kernel code. ๐Ÿ‘‘
  • -mtext-section-literals, -mno-text-section-literals โ€” these options control the treatment of literal pools. The default is -mno-text-section-literals, which places literals in a separate section in the output file. This allows the literal pool to be placed in a data RAM/ROM, and it also allows the linker to combine literal pools from separate object files to remove redundant literals and improve code size. With -mtext-section-literals, the literals are interspersed in the text section in order to keep them as close as possible to their references. This may be necessary for large assembly files. Literals for each function are placed right before that function. ๐Ÿ’…
  • -mauto-litpools, -mno-auto-litpools โ€” these options control the treatment of literal pools. The 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 literals are interspersed in the text section by the assembler. The compiler doesn't produce explicit ".literal" directives and loads literals into registers with "MOVI" instructions instead of "L32R" to let the assembler do relaxation and place literals as necessary. This option allows the assembler to 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 this option is enabled, GCC instructs the assembler to automatically align instructions to reduce branch penalties at the expense of some code density. The assembler attempts 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 is performed. The default is -mtarget-align. 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. ๐Ÿ’–
  • -mlongcalls, -mno-longcalls โ€” when this option is enabled, GCC instructs the assembler to translate direct calls to indirect calls unless it can determine that the target of a direct call is in the range allowed by the call instruction. This translation typically occurs for calls to functions in other source files. Specifically, the assembler translates a direct "CALL" instruction into an "L32R" followed by a "CALLX" instruction. The default is -mno-longcalls. This option should be used in programs where the call target can potentially be out of range. Now listen โ€” 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. And note that the assembler uses an indirect call for every cross-file call, not just those that really are out of range. Periodt. ๐Ÿ˜ญ
  • -mabi=name โ€” generate code for the specified ABI. Permissible values are: call0, windowed. Default ABI is chosen by the Xtensa core configuration. ๐ŸŽ€
  • -mabi=call0 โ€” when this option 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 option 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 that 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. ๐ŸชŸ๐Ÿ’œ

๐Ÿ‘‘ zSeries Options ๐Ÿ‘‘

These are listed under

โœจ ENVIRONMENT โœจ

okay bestie, this section is all about the env vars that change how GCC acts. Some give it directories or prefixes to search for files, some set other stuff about compilation. ๐Ÿ’…

Note: you can also tell GCC where to search with options like -B, -I, and -L. Those options beat environment variables. Environment variables beat whatever GCC's configuration says. Precedence chain, periodt. ๐Ÿ‘‘

LANG, LC_CTYPE, LC_MESSAGES, LC_ALL

These control localization info so GCC can work with different national conventions. GCC checks locale categories LC_CTYPE and LC_MESSAGES if it was configured to do so. Those categories can be set to any value your installation supports. A typical value is en_GB.UTF-8 for English in the United Kingdom encoded in UTF-8. ๐ŸŒ

LC_CTYPE specifies character classification. GCC uses it to figure out character boundaries in a string; needed for some multibyte encodings that contain quote and escape characters that are otherwise interpreted as string end or escape. ๐Ÿ˜ญ

LC_MESSAGES specifies language for diagnostic messages. ๐Ÿ’ฌ

If LC_ALL is set, it overrides LC_CTYPE and LC_MESSAGES; otherwise LC_CTYPE and LC_MESSAGES default to the value of LANG. If none set, GCC defaults to traditional C English behavior. ๐Ÿ‡ฌ๐Ÿ‡ง

TMPDIR

If TMPDIR is set, it specifies the directory for temporary files. GCC uses temp files to hold output of one compilation stage used as input to the next: e.g., output of the preprocessor, which is input to the compiler proper. ๐Ÿ—‚๏ธ

GCC_COMPARE_DEBUG

Setting GCC_COMPARE_DEBUG is nearly equivalent to passing -fcompare-debug to the compiler driver. See the docs of that option for details. ๐Ÿž

GCC_EXEC_PREFIX

If GCC_EXEC_PREFIX is set, it specifies a prefix to use in the names of subprograms executed by the compiler. No slash is added when this prefix is combined with the name of a subprogram, but you can specify a prefix that ends with a slash if you wish. ๐Ÿ› ๏ธ

If GCC_EXEC_PREFIX is not set, GCC attempts to figure out an appropriate prefix based on the pathname it is invoked with.

If GCC cannot find the subprogram using the specified prefix, it tries looking in the usual places for the subprogram.

The default value of GCC_EXEC_PREFIX is prefix/lib/gcc/ where prefix is the prefix to the installed compiler. In many cases prefix is the value of "prefix" when you ran the configure script.

Other prefixes specified with -B take precedence over this prefix.

This prefix is also used for finding files such as crt0.o that are used for linking.

In addition, the prefix is used in an unusual way in finding the directories to search for header files. For each of the standard directories whose name normally begins with /usr/local/lib/gcc (more precisely, with the value of GCC_INCLUDE_DIR), GCC tries replacing that beginning with the specified prefix to produce an alternate directory name. Thus, with -Bfoo/, GCC searches foo/bar just before it searches the standard directory /usr/local/lib/bar. If a standard directory begins with the configured prefix then the value of prefix is replaced by GCC_EXEC_PREFIX when looking for header files. ๐Ÿคฏ

COMPILER_PATH

The value of COMPILER_PATH is a colon-separated list of directories, much like PATH. GCC tries the directories thus specified when searching for subprograms, if it cannot find the subprograms using GCC_EXEC_PREFIX. ๐Ÿ”Ž

LIBRARY_PATH

The value of LIBRARY_PATH is a colon-separated list of directories, much like PATH. When configured as a native compiler, GCC tries the directories thus specified when searching for special linker files, if it cannot find them using GCC_EXEC_PREFIX. Linking using GCC also uses these directories when searching for ordinary libraries for the -l option (but directories specified with -L come first). ๐Ÿ“š

LANG (the multibyte-character one)

This variable is used to pass locale info to the compiler. One way the info is used is to determine the character set used when character literals, string literals, and comments are parsed in C and C++. When the compiler is configured to allow multibyte characters, the following values for LANG are recognized:

  • C-JIS โ€” recognize JIS characters. ๐Ÿ‡ฏ๐Ÿ‡ต
  • C-SJIS โ€” recognize SJIS characters.
  • C-EUCJP โ€” recognize EUCJP characters.

If LANG is not defined, or if it has some other value, then 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 the following values, then additional text will be emitted to stderr when fix-it hints are emitted. -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 โ€” as "fixits-v1", but columns are expressed as display columns, as per -fdiagnostics-column-unit=display. ๐Ÿ–ฅ๏ธ

Some additional environment variables affect the behavior of the preprocessor.

CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH, OBJC_INCLUDE_PATH

Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon. ๐ŸชŸ๐Ÿง

CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed. ๐ŸŒ

The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line. ๐Ÿ“

In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include. ๐Ÿ‘ป

DEPENDENCIES_OUTPUT

If this variable is set, its value specifies how to output dependencies for Make based on the non-system header files processed by the compiler. System header files are ignored in the dependency output. ๐Ÿ“

The value of DEPENDENCIES_OUTPUT can be just a file name, in which case the Make rules are written to that file, guessing the target name from the source file name. Or the value can have the form file target, in which case the rules are written to file file using target as the target name.

In other words, this environment variable is equivalent to combining the options -MM and -MF, with an optional -MT switch too. ๐Ÿงฉ

SUNPRO_DEPENDENCIES

This variable is the same as DEPENDENCIES_OUTPUT (see above), except that system header files are not ignored, so it implies -M rather than -MM. However, the dependence on the main input file is omitted. โ˜€๏ธ

SOURCE_DATE_EPOCH

If this variable is set, its value specifies a UNIX timestamp to be used in replacement of the current date and time in the "__DATE__" and "__TIME__" macros, so that the embedded timestamps become reproducible. โฐ

The value of SOURCE_DATE_EPOCH must be a UNIX timestamp, defined as the number of seconds (excluding leap seconds) since 01 Jan 1970 00:00:00 represented in ASCII; identical to the output of "date +%s" on GNU/Linux and other systems that support the %s extension in the "date" command.

The value should be a known timestamp such as 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 <file:///usr/share/doc/gcc-11/README.Bugs>. ๐Ÿž

๐Ÿ“ 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 in cases where they are not necessary is innocuous. ๐Ÿ’€

๐Ÿ‘€ 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. ๐Ÿซถ

๐Ÿ‘‘ AUTHOR ๐Ÿ‘‘

See the Info entry for gcc, or <http://gcc.gnu.org/onlinedocs/gcc/Contributors.html>, for contributors to GCC. ๐Ÿ‘‘

Copyright (c) 1988-2021 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.

๐Ÿ’– That's the whole page, bestie โ€” source/version gcc-11, dated 2024-07-19, page GCC(1). No cap, you made it. Periodt. ๐Ÿ’…

๐Ÿ“ฆ where this page comes from