GCC(1)

๐Ÿ“ฆ
version 13.5.0 ยท 5 versions
, in ubuntu stonking

โœจ GCC(1) โœจ โ€” GNU project C and C++ compiler ๐Ÿ‘‘

okay so bestie, this is the manual page for GCC(1), brought to you by GNU. It's literally the GNU project C and C++ compiler, and she's iconic. ๐Ÿ’…


NAME ๐ŸŽ€

gcc โ€” GNU project C and C++ compiler ๐Ÿ’–


SYNOPSIS ๐Ÿฆ‹

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

Real talk: only the most useful options are listed here; see below for the remainder. And g++ accepts mostly the same options as gcc. So don't panic. ๐Ÿซถ


DESCRIPTION ๐Ÿ’…

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

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

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

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

The gcc program accepts options and file names as operands. Many options have multi-letter names; therefore multiple single-letter options may not be grouped: -dv is very different from -d -v. The way one hyphen changes everything. ๐Ÿ˜ญ

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. So don't just yolo the order, bestie. ๐ŸŒธ

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. Keep that in mind. ๐Ÿงš

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


OPTIONS โœจ

Option Summary ๐ŸŽ€

Here is a summary of all the options, grouped by type. Explanations are in the following sections. So grab your strawberry matcha, bestie. ๐Ÿ“

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  -fcanon-prefix-map
-fplugin=file  -fplugin-arg-name=arg -fdump-ada-spec[-slim]
-fada-spec-parent=unit  -fdump-go-spec=file

C Language Options ๐Ÿ’œ

-ansi  -std=standard  -aux-info filename -fno-asm -fno-builtin
-fno-builtin-function  -fcond-mismatch -ffreestanding  -fgimple
-fgnu-tm  -fgnu89-inline  -fhosted -flax-vector-conversions
-fms-extensions -foffload=arg  -foffload-options=arg -fopenacc
-fopenacc-dim=geom -fopenmp  -fopenmp-simd
-fopenmp-target-simd-clone[=device-type]
-fpermitted-flt-eval-methods=standard -fplan9-extensions
-fsigned-bitfields  -funsigned-bitfields -fsigned-char
-funsigned-char -fstrict-flex-arrays[=n] -fsso-struct=endianness

C++ Language Options ๐Ÿฆ‹

-fabi-version=n  -fno-access-control -faligned-new=n
-fargs-in-order=n  -fchar8_t  -fcheck-new -fconstexpr-depth=n
-fconstexpr-cache-depth=n -fconstexpr-loop-limit=n
-fconstexpr-ops-limit=n -fno-elide-constructors
-fno-enforce-eh-specs -fno-gnu-keywords -fno-implicit-templates
-fno-implicit-inline-templates -fno-implement-inlines
-fmodule-header[=kind] -fmodule-only -fmodules-ts
-fmodule-implicit-inline -fno-module-lazy
-fmodule-mapper=specification -fmodule-version-ignore
-fms-extensions -fnew-inheriting-ctors -fnew-ttp-matching
-fno-nonansi-builtins  -fnothrow-opt  -fno-operator-names
-fno-optional-diags  -fpermissive -fno-pretty-templates -fno-rtti
-fsized-deallocation -ftemplate-backtrace-limit=n -ftemplate-depth=n
-fno-threadsafe-statics  -fuse-cxa-atexit -fno-weak  -nostdinc++
-fvisibility-inlines-hidden -fvisibility-ms-compat
-fext-numeric-literals -flang-info-include-translate[=header]
-flang-info-include-translate-not -flang-info-module-cmi[=module]
-stdlib=libstdc++,libc++ -Wabi-tag  -Wcatch-value  -Wcatch-value=n
-Wno-class-conversion  -Wclass-memaccess -Wcomma-subscript
-Wconditionally-supported -Wno-conversion-null
-Wctad-maybe-unsupported -Wctor-dtor-privacy  -Wdangling-reference
-Wno-delete-incomplete -Wdelete-non-virtual-dtor
-Wno-deprecated-array-compare -Wdeprecated-copy
-Wdeprecated-copy-dtor -Wno-deprecated-enum-enum-conversion
-Wno-deprecated-enum-float-conversion -Weffc++  -Wno-exceptions
-Wextra-semi  -Wno-inaccessible-base -Wno-inherited-variadic-ctor
-Wno-init-list-lifetime -Winvalid-constexpr
-Winvalid-imported-macros -Wno-invalid-offsetof  -Wno-literal-suffix
-Wmismatched-new-delete -Wmismatched-tags -Wmultiple-inheritance
-Wnamespaces  -Wnarrowing -Wnoexcept  -Wnoexcept-type
-Wnon-virtual-dtor -Wpessimizing-move  -Wno-placement-new
-Wplacement-new=n -Wrange-loop-construct -Wredundant-move
-Wredundant-tags -Wreorder  -Wregister -Wstrict-null-sentinel
-Wno-subobject-linkage  -Wtemplates -Wno-non-template-friend
-Wold-style-cast -Woverloaded-virtual  -Wno-pmf-conversions
-Wself-move -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|sarif-stderr|sarif-file|json|json-stderr|json-file]
-fno-diagnostics-show-option  -fno-diagnostics-show-caret
-fno-diagnostics-show-labels  -fno-diagnostics-show-line-numbers
-fno-diagnostics-show-cwe -fno-diagnostics-show-rule
-fdiagnostics-minimum-margin-width=width
-fdiagnostics-parseable-fixits  -fdiagnostics-generate-patch
-fdiagnostics-show-template-tree  -fno-elide-type
-fdiagnostics-path-format=[none|separate-events|inline-events]
-fdiagnostics-show-path-depths -fno-show-column
-fdiagnostics-column-unit=[display|byte]
-fdiagnostics-column-origin=origin
-fdiagnostics-escape-format=[unicode|bytes]

And that's just the summary, bestie. The explanations are in the following sections. More options incoming in the next parts โ€” stay tuned. ๐Ÿ’–

โœจ Warning Options โœจ

okay bestie, this is the big one ๐Ÿ’– the warning-flag constellation. it's a lot of flags, they all go straight on the command line, and some of them are -Wno- twins that are just the off-switch version of their sibling. no skimming, we're going through every single one. ๐Ÿ’…

  • -fsyntax-only
  • -fmax-errors=n
  • -Wpedantic
  • -pedantic-errors
  • -w
  • -Wextra
  • -Wall
  • -Wabi=n
  • -Waddress
  • -Wno-address-of-packed-member
  • -Waggregate-return
  • -Walloc-size-larger-than=byte-size
  • -Walloc-zero
  • -Walloca
  • -Walloca-larger-than=byte-size
  • -Wno-aggressive-loop-optimizations
  • -Warith-conversion
  • -Warray-bounds
  • -Warray-bounds=n
  • -Warray-compare
  • -Wno-attributes
  • -Wattribute-alias=n
  • -Wno-attribute-alias
  • -Wno-attribute-warning

not the -Wabi=n sitting right there next to -Wall like it belongs ๐Ÿ˜ญ anyway, moving on, the alphabet is long and she does not care about our feelings.

  • -Wbidi-chars=[none|unpaired|any|ucn]
  • -Wbool-compare
  • -Wbool-operation
  • -Wno-builtin-declaration-mismatch
  • -Wno-builtin-macro-redefined
  • -Wc90-c99-compat
  • -Wc99-c11-compat
  • -Wc11-c2x-compat
  • -Wc++-compat
  • -Wc++11-compat
  • -Wc++14-compat
  • -Wc++17-compat
  • -Wc++20-compat
  • -Wno-c++11-extensions
  • -Wno-c++14-extensions
  • -Wno-c++17-extensions
  • -Wno-c++20-extensions
  • -Wno-c++23-extensions
  • -Wcast-align
  • -Wcast-align=strict
  • -Wcast-function-type
  • -Wcast-qual
  • -Wchar-subscripts
  • -Wclobbered
  • -Wcomment
  • -Wno-complain-wrong-lang
  • -Wconversion
  • -Wno-coverage-mismatch
  • -Wno-cpp
  • -Wdangling-else
  • -Wdangling-pointer
  • -Wdangling-pointer=n

the whole -Wc++11-compat โ†’ -Wc++20-compat lineup is giving boy band, they all show up together every time ๐ŸŽ€ and yes, there's a -Wno- version of the extensions flags too, one per standard, because of course there is.

  • -Wdate-time
  • -Wno-deprecated
  • -Wno-deprecated-declarations
  • -Wno-designated-init
  • -Wdisabled-optimization
  • -Wno-discarded-array-qualifiers
  • -Wno-discarded-qualifiers
  • -Wno-div-by-zero
  • -Wdouble-promotion
  • -Wduplicated-branches
  • -Wduplicated-cond
  • -Wempty-body
  • -Wno-endif-labels
  • -Wenum-compare
  • -Wenum-conversion
  • -Wenum-int-mismatch
  • -Werror
  • -Werror=*
  • -Wexpansion-to-defined
  • -Wfatal-errors
  • -Wfloat-conversion
  • -Wfloat-equal
  • -Wformat
  • -Wformat=2
  • -Wno-format-contains-nul
  • -Wno-format-extra-args
  • -Wformat-nonliteral
  • -Wformat-overflow=n
  • -Wformat-security
  • -Wformat-signedness
  • -Wformat-truncation=n
  • -Wformat-y2k
  • -Wframe-address
  • -Wframe-larger-than=byte-size

-Werror is the main character of this whole section ngl, and -Werror=* is her wildcard twin. the -Wformat-* cluster is a whole investigative journalism subplot, and there's genuinely a -Wformat-y2k in there, iconic, no notes ๐ŸŒธ

  • -Wno-free-nonheap-object
  • -Wno-if-not-aligned
  • -Wno-ignored-attributes
  • -Wignored-qualifiers
  • -Wno-incompatible-pointer-types
  • -Wimplicit
  • -Wimplicit-fallthrough
  • -Wimplicit-fallthrough=n
  • -Wno-implicit-function-declaration
  • -Wno-implicit-int
  • -Winfinite-recursion
  • -Winit-self
  • -Winline
  • -Wno-int-conversion
  • -Wint-in-bool-context
  • -Wno-int-to-pointer-cast
  • -Wno-invalid-memory-model
  • -Winvalid-pch
  • -Winvalid-utf8
  • -Wno-unicode
  • -Wjump-misses-init
  • -Wlarger-than=byte-size
  • -Wlogical-not-parentheses
  • -Wlogical-op
  • -Wlong-long
  • -Wno-lto-type-mismatch
  • -Wmain
  • -Wmaybe-uninitialized
  • -Wmemset-elt-size
  • -Wmemset-transposed-args
  • -Wmisleading-indentation
  • -Wmissing-attributes
  • -Wmissing-braces
  • -Wmissing-field-initializers
  • -Wmissing-format-attribute
  • -Wmissing-include-dirs
  • -Wmissing-noreturn
  • -Wno-missing-profile
  • -Wno-multichar
  • -Wmultistatement-macros
  • -Wnonnull
  • -Wnonnull-compare
  • -Wnormalized=[none|id|nfc|nfkc]
  • -Wnull-dereference
  • -Wno-odr

the -Wmissing-* saga is so long at this point, every time i think it's done there's another one ๐Ÿ˜ญ and yes, -Wno-int-conversion and -Wno-int-to-pointer-cast are two different flags, do not @ me.

  • -Wopenacc-parallelism
  • -Wopenmp-simd
  • -Wno-overflow
  • -Woverlength-strings
  • -Wno-override-init-side-effects
  • -Wpacked
  • -Wno-packed-bitfield-compat
  • -Wpacked-not-aligned
  • -Wpadded
  • -Wparentheses
  • -Wno-pedantic-ms-format
  • -Wpointer-arith
  • -Wno-pointer-compare
  • -Wno-pointer-to-int-cast
  • -Wno-pragmas
  • -Wno-prio-ctor-dtor
  • -Wredundant-decls
  • -Wrestrict
  • -Wno-return-local-addr
  • -Wreturn-type
  • -Wno-scalar-storage-order
  • -Wsequence-point
  • -Wshadow
  • -Wshadow=global
  • -Wshadow=local
  • -Wshadow=compatible-local
  • -Wno-shadow-ivar
  • -Wno-shift-count-negative
  • -Wno-shift-count-overflow
  • -Wshift-negative-value
  • -Wno-shift-overflow
  • -Wshift-overflow=n
  • -Wsign-compare
  • -Wsign-conversion
  • -Wno-sizeof-array-argument
  • -Wsizeof-array-div
  • -Wsizeof-pointer-div
  • -Wsizeof-pointer-memaccess
  • -Wstack-protector
  • -Wstack-usage=byte-size
  • -Wstrict-aliasing
  • -Wstrict-aliasing=n
  • -Wstrict-overflow
  • -Wstrict-overflow=n
  • -Wstring-compare
  • -Wno-stringop-overflow
  • -Wno-stringop-overread
  • -Wno-stringop-truncation
  • -Wstrict-flex-arrays
  • -Wsuggest-attribute=[pure|const|noreturn|format|malloc]
  • -Wswitch
  • -Wno-switch-bool
  • -Wswitch-default
  • -Wswitch-enum
  • -Wno-switch-outside-range
  • -Wno-switch-unreachable
  • -Wsync-nand
  • -Wsystem-headers
  • -Wtautological-compare
  • -Wtrampolines
  • -Wtrigraphs
  • -Wtrivial-auto-var-init
  • -Wtsan
  • -Wtype-limits

-Wshadow really said "i contain multitudes" with her =global, =local and =compatible-local variants ๐Ÿฆ‹ and the -Wsizeof-* squad is quietly doing the most helpful work in the building, love her for that.

  • -Wundef
  • -Wuninitialized
  • -Wunknown-pragmas
  • -Wunsuffixed-float-constants
  • -Wunused
  • -Wunused-but-set-parameter
  • -Wunused-but-set-variable
  • -Wunused-const-variable
  • -Wunused-const-variable=n
  • -Wunused-function
  • -Wunused-label
  • -Wunused-local-typedefs
  • -Wunused-macros
  • -Wunused-parameter
  • -Wno-unused-result
  • -Wunused-value
  • -Wunused-variable
  • -Wno-varargs
  • -Wvariadic-macros
  • -Wvector-operation-performance
  • -Wvla
  • -Wvla-larger-than=byte-size
  • -Wno-vla-larger-than
  • -Wvolatile-register-var
  • -Wwrite-strings
  • -Wxor-used-as-pow
  • -Wzero-length-bounds

the entire -Wunused-* nation, rise up ๐Ÿซถ you are the reason our codebases are clean and our vibes are immaculate, and -Wunused-const-variable=n is right there next to her twin like a matching set. periodt. and with -Wzero-length-bounds the warning list finally, finally runs out of alphabet ๐Ÿ”ฅ


โœจ Static Analyzer Options โœจ

okay so the static analyzer is basically gcc putting on its detective hat ๐Ÿ•ต๏ธโ™€๏ธ and this is her whole control panel. flags first, then the -fdump-* ones she uses to write down everything she found, then a truly enormous pile of -Wno-analyzer-* switches. here we go, all of them, in order:

  • -fanalyzer
  • -fanalyzer-call-summaries
  • -fanalyzer-checker=name
  • -fno-analyzer-feasibility
  • -fanalyzer-fine-grained
  • -fno-analyzer-state-merge
  • -fno-analyzer-state-purge
  • -fno-analyzer-suppress-followups
  • -fanalyzer-transitivity
  • -fno-analyzer-undo-inlining
  • -fanalyzer-verbose-edges
  • -fanalyzer-verbose-state-changes
  • -fanalyzer-verbosity=level
  • -fdump-analyzer
  • -fdump-analyzer-callgraph
  • -fdump-analyzer-exploded-graph
  • -fdump-analyzer-exploded-nodes
  • -fdump-analyzer-exploded-nodes-2
  • -fdump-analyzer-exploded-nodes-3
  • -fdump-analyzer-exploded-paths
  • -fdump-analyzer-feasibility
  • -fdump-analyzer-json
  • -fdump-analyzer-state-purge
  • -fdump-analyzer-stderr
  • -fdump-analyzer-supergraph
  • -fdump-analyzer-untracked

three different exploded-nodes dumps, bestie ๐Ÿ˜ญ -fdump-analyzer-exploded-nodes, -fdump-analyzer-exploded-nodes-2 and -fdump-analyzer-exploded-nodes-3 โ€” she really said one is not enough. and now the big warning wall:

  • -Wno-analyzer-double-fclose
  • -Wno-analyzer-double-free
  • -Wno-analyzer-exposure-through-output-file
  • -Wno-analyzer-exposure-through-uninit-copy
  • -Wno-analyzer-fd-access-mode-mismatch
  • -Wno-analyzer-fd-double-close
  • -Wno-analyzer-fd-leak
  • -Wno-analyzer-fd-phase-mismatch
  • -Wno-analyzer-fd-type-mismatch
  • -Wno-analyzer-fd-use-after-close
  • -Wno-analyzer-fd-use-without-check
  • -Wno-analyzer-file-leak
  • -Wno-analyzer-free-of-non-heap
  • -Wno-analyzer-imprecise-fp-arithmetic
  • -Wno-analyzer-infinite-recursion
  • -Wno-analyzer-jump-through-null
  • -Wno-analyzer-malloc-leak
  • -Wno-analyzer-mismatching-deallocation
  • -Wno-analyzer-null-argument
  • -Wno-analyzer-null-dereference
  • -Wno-analyzer-out-of-bounds
  • -Wno-analyzer-possible-null-argument
  • -Wno-analyzer-possible-null-dereference
  • -Wno-analyzer-putenv-of-auto-var
  • -Wno-analyzer-shift-count-negative
  • -Wno-analyzer-shift-count-overflow
  • -Wno-analyzer-stale-setjmp-buffer
  • -Wno-analyzer-tainted-allocation-size
  • -Wno-analyzer-tainted-assertion
  • -Wno-analyzer-tainted-array-index
  • -Wno-analyzer-tainted-divisor
  • -Wno-analyzer-tainted-offset
  • -Wno-analyzer-tainted-size
  • -Wanalyzer-too-complex
  • -Wno-analyzer-unsafe-call-within-signal-handler
  • -Wno-analyzer-use-after-free
  • -Wno-analyzer-use-of-pointer-in-stale-stack-frame
  • -Wno-analyzer-use-of-uninitialized-value
  • -Wno-analyzer-va-arg-type-mismatch
  • -Wno-analyzer-va-list-exhausted
  • -Wno-analyzer-va-list-leak
  • -Wno-analyzer-va-list-use-after-va-end
  • -Wno-analyzer-write-to-const
  • -Wno-analyzer-write-to-string-literal

the whole -Wno-analyzer-fd-* family is giving file-descriptor true crime documentary ๐Ÿ’€ and -Wanalyzer-too-complex is the one flag in the bunch without a -Wno- twin, she stands alone, main character energy fr fr.


โœจ C and Objective-C-only Warning Options โœจ

these ones are โœจexclusiveโœจ โ€” C and Objective-C only, no C++ girlies allowed at this party ๐Ÿ™ˆ here's every single one:

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

note how -Wold-style-declaration and -Wold-style-definition are two separate flags ๐ŸŽ€ they are not the same, do not merge them, they will know. and -Wtraditional has her own little friend -Wtraditional-conversion tagging along, obsessed with them honestly.


โœจ Debugging Options โœจ

debugging girlies this one's for you ๐Ÿ›โœจ this is the whole -g extended universe โ€” every flavour of debug info, every -gno- counterweight, and a bunch of -f flags that came to live here too. all of them, in order:

  • -g
  • -glevel
  • -gdwarf
  • -gdwarf-version
  • -gbtf
  • -gctf
  • -gctflevel
  • -ggdb
  • -grecord-gcc-switches
  • -gno-record-gcc-switches
  • -gstrict-dwarf
  • -gno-strict-dwarf
  • -gas-loc-support
  • -gno-as-loc-support
  • -gas-locview-support
  • -gno-as-locview-support
  • -gcolumn-info
  • -gno-column-info
  • -gdwarf32
  • -gdwarf64
  • -gstatement-frontiers
  • -gno-statement-frontiers
  • -gvariable-location-views
  • -gno-variable-location-views
  • -ginternal-reset-location-views
  • -gno-internal-reset-location-views
  • -ginline-points
  • -gno-inline-points
  • -gvms
  • -gz[=type]
  • -gsplit-dwarf
  • -gdescribe-dies
  • -gno-describe-dies
  • -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

see how every -g-something has a -gno--something staring back at her? ๐Ÿฆ‹ that's the whole vibe of this section โ€” on, off, on, off, like a little debug-info light switch rave. also -fno-eliminate-unused-debug-types and -fno-eliminate-unused-debug-symbols are different flags, bestie, don't let the near-identical names gaslight you ๐Ÿ˜ญ and there's a [=spec-list] hiding on -femit-struct-debug-detailed, keep that bracket, she bites if you drop it ๐Ÿ’…

โšก Optimization Options โšก

bestie. babes. buckle UP. this is the big one, the optimization menu, the little list of every knob that decides how hard the compiler is gonna try. some of these are iconic, some of these are chaos, and you can absolutely mix and match them, so let's just read through the whole lineup together. no descriptions yet โ€” this is the guest list, the actual โœจloreโœจ per flag shows up later. ๐Ÿ’…

  • -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
  • -fmove-loop-stores
  • -fno-branch-count-reg
  • -fno-defer-pop
  • -fno-fp-int-builtin-inexact
  • -fno-function-cse
  • -fno-guess-branch-probability
  • -fno-inline
  • -fno-math-errno
  • -fno-peephole
  • -fno-peephole2
  • -fno-printf-return-value
  • -fno-sched-interblock
  • -fno-sched-spec
  • -fno-signed-zeros
  • -fno-toplevel-reorder
  • -fno-trapping-math
  • -fno-zero-initialized-in-bss
  • -fomit-frame-pointer
  • -foptimize-sibling-calls
  • -fpartial-inlining
  • -fpeel-loops
  • -fpredictive-commoning
  • -fprefetch-loop-arrays
  • -fprofile-correction
  • -fprofile-use
  • -fprofile-use=path
  • -fprofile-partial-training
  • -fprofile-values
  • -fprofile-reorder-functions
  • -freciprocal-math
  • -free
  • -frename-registers
  • -freorder-blocks
  • -freorder-blocks-algorithm=algorithm
  • -freorder-blocks-and-partition
  • -freorder-functions
  • -frerun-cse-after-loop
  • -freschedule-modulo-scheduled-loops
  • -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
  • -fipa-strict-aliasing
  • -fthread-jumps
  • -ftracer
  • -ftree-bit-ccp
  • -ftree-builtin-call-dce
  • -ftree-ccp
  • -ftree-ch
  • -ftree-coalesce-vars
  • -ftree-copy-prop
  • -ftree-dce
  • -ftree-dominator-opts
  • -ftree-dse
  • -ftree-forwprop
  • -ftree-fre
  • -fcode-hoisting
  • -ftree-loop-if-convert
  • -ftree-loop-im
  • -ftree-phiprop
  • -ftree-loop-distribution
  • -ftree-loop-distribute-patterns
  • -ftree-loop-ivcanon
  • -ftree-loop-linear
  • -ftree-loop-optimize
  • -ftree-loop-vectorize
  • -ftree-parallelize-loops=n
  • -ftree-pre
  • -ftree-partial-pre
  • -ftree-pta
  • -ftree-reassoc
  • -ftree-scev-cprop
  • -ftree-sink
  • -ftree-slsr
  • -ftree-sra
  • -ftree-switch-conversion
  • -ftree-tail-merge
  • -ftree-ter
  • -ftree-vectorize
  • -ftree-vrp
  • -ftrivial-auto-var-init
  • -funconstrained-commons
  • -funit-at-a-time
  • -funroll-all-loops
  • -funroll-loops
  • -funsafe-math-optimizations
  • -funswitch-loops
  • -fipa-ra
  • -fvariable-expansion-in-unroller
  • -fvect-cost-model
  • -fvpt
  • -fweb
  • -fwhole-program
  • -fwpa
  • -fuse-linker-plugin
  • -fzero-call-used-regs
  • --param name=value
  • -O
  • -O0
  • -O1
  • -O2
  • -O3
  • -Os
  • -Ofast
  • -Og
  • -Oz

and yes, that whole list is real, and yes, you can pass more than one, and yes, it's giving compiler goblin energy and we love her for it. ๐Ÿซถ


๐Ÿงช Program Instrumentation Options ๐Ÿงช

these are the "hey bestie, let's watch what this code is actually doing at runtime" flags โ€” profiling, coverage, sanitizers, stack protection, and all the little spy-cams you can bolt onto a binary. ๐Ÿ”

  • -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
  • -fsanitize-trap
  • -fsanitize-trap=style
  • -fasan-shadow-offset=number
  • -fsanitize-sections=s1,s2,...
  • -fsanitize-undefined-trap-on-error
  • -fbounds-check
  • -fcf-protection=[full|branch|return|none|check]
  • -fharden-compares
  • -fharden-conditional-branches
  • -fstack-protector
  • -fstack-protector-all
  • -fstack-protector-strong
  • -fstack-protector-explicit
  • -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-once
  • -finstrument-functions-exclude-function-list=sym,sym,...
  • -finstrument-functions-exclude-file-list=file,file,...
  • -fprofile-prefix-map=old=new

๐ŸŒธ Preprocessor Options ๐ŸŒธ

the before-times. the era of #define and vibes. this whole group is about how the source gets chewed up before it ever becomes real code โ€” macro definitions, include paths, charset stuff, dependency generation, all of it. ๐ŸŽ€

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

just two, bestie, and they're both "hey, pass this straight through to the assembler, k thanks". short and sweet. โœจ

  • -Wa,option
  • -Xassembler option

๐Ÿ”— Linker Options ๐Ÿ”—

the part where all your little object files finally hold hands and become one executable. linking!! the moment of truth!! ๐Ÿ’–

  • object-file-name
  • -fuse-ld=linker
  • -llibrary
  • -nostartfiles
  • -nodefaultlibs
  • -nolibc
  • -nostdlib
  • -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 ๐Ÿ“

where does the compiler go looking for stuff? include dirs, lib dirs, sysroots, prefixes, plugins โ€” this is the map of everywhere she's allowed to rummage. ๐Ÿ—บ๏ธ

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

the juicy ABI-and-layout zone. calling conventions, struct returns, PIC/PIE, visibility, TLS models, all the "how exactly does the generated code behave" choices live right here. ๐Ÿ‘‘

  • -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 ๐Ÿ› ๏ธ

okay this is the backstage pass section. dumps, debug counters, pass disabling/enabling, timing reports, memory reports, and a truly alarming number of ways to peer directly into the compiler's soul. if you're the kind of person who reads compiler IR for fun โ€” hi, you're the main character. ๐Ÿ˜ญ๐Ÿ’œ

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

okay bestie, deep breath ๐Ÿ’– this is the part of the page where GCC opens its entire wardrobe and shows you every single chip family it can dress for. Every target gets its own private stash of flags. None of them are described here, they're just... listed. So here they all are, in order, exactly as GCC names them. No skipping. We're going through the whole closet. โœจ


๐Ÿ’ซ AArch64 Options

the AArch64 girlies are served โ€” look at all these:

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

tiny parallel-computing fairy vibes ๐Ÿงš:

  • -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, to the point, periodt:

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

๐ŸŽ€ ARC Options

an absolute icon of a list, genuinely obsessed:

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

๐Ÿ’… ARM Options

the main character of embedded, no cap:

  • -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 ยท -mfix-cortex-a57-aes-1742098 ยท -mfix-cortex-a72-aes-1655431
  • -munaligned-access ยท -mneon-for-64bits ยท -mslow-flash-data
  • -masm-syntax-unified ยท -mrestrict-it ยท -mverbose-cost-dump
  • -mpure-code ยท -mcmse ยท -mfix-cmse-cve-2021-35465
  • -mstack-protector-guard=guard ยท -mstack-protector-guard-offset=offset
  • -mfdpic
  • -mbranch-protection=none|standard|pac-ret[+leaf] [+bti]|bti[+pac-ret[+leaf]]

๐Ÿ“ AVR Options

microcontroller cutie behavior ๐ŸŽ€:

  • -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 ยท -mskip-bug
  • -nodevicelib ยท -nodevicespecs
  • -Waddr-space-convert ยท -Wmisspelled-isr

๐Ÿซถ Blackfin Options

lowkey a whole novel:

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

small but mighty โœจ:

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

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

a dramatic amount, and yes some of them genuinely appear twice, that's just how it is, we don't edit the queen:

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

โญ DEC Alpha Options

vintage icon energy:

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

kernel-baddie core ๐ŸŒˆ:

  • -mbig-endian ยท -mlittle-endian
  • -mkernel=version ยท -mframe-limit=bytes ยท -mxbpf
  • -mco-re ยท -mno-co-re
  • -mjmpext ยท -mjmp32 ยท -malu32
  • -mcpu=version

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

the libc-picking girlies:

  • -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 ยท -matomic-libcalls
  • -mbig-switch ยท -mcaller-copies
  • -mdisable-fpregs ยท -mdisable-indexing
  • -mordered ยท -mfast-indirect-calls
  • -mgas ยท -mgnu-ld ยท -mhp-ld
  • -mfixed-range=register-range ยท -mcoherent-ldcw
  • -mjump-in-delay ยท -mlinker-opt ยท -mlong-calls ยท -mlong-load-store
  • -mno-atomic-libcalls ยท -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 ยท -msoft-mult
  • -msio ยท -mwsio
  • -munix=unix-std
  • -nolibdld ยท -static ยท -threads

๐ŸŒ™ IA-64 Options

the scheduling menu is huge, iykyk:

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

๐Ÿฆš LoongArch Options

  • -march=cpu-type ยท -mtune=cpu-type
  • -mabi=base-abi-type
  • -mfpu=fpu-type
  • -msoft-float ยท -msingle-float ยท -mdouble-float
  • -mbranch-cost=n
  • -mcheck-zero-division ยท -mno-check-zero-division
  • -mcond-move-int ยท -mno-cond-move-int
  • -mcond-move-float ยท -mno-cond-move-float
  • -memcpy ยท -mno-memcpy
  • -mstrict-align ยท -mno-strict-align
  • -mmax-inline-memcpy-size=n
  • -mexplicit-relocs ยท -mno-explicit-relocs
  • -mdirect-extern-access ยท -mno-direct-extern-access
  • -mcmodel=code-model
  • -mrelax ยท -mpass-mrelax-to-as

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

last but never least ๐Ÿซถ:

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

...and okay so this is the part where the manpage stops pretending to be normal, because from here it's just machine-dependent options. Like, all of them. Hundreds. One per bullet. I'm not even mad, I'm impressed. ๐Ÿ˜ญ

heads up bestie: this whole chunk is literally just flag lists โ€” no descriptions attached. So I'm giving you the flags exactly as they are with max vibes and zero invented lore, because making stuff up about compiler flags is not the move. ๐Ÿ’…

๐Ÿง M680x0 Options ๐Ÿง

The 680x0 block. It's giving vintage Motorola main character energy.

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

๐Ÿ’Ž MicroBlaze Options ๐Ÿ’Ž</col/>

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

๐ŸŒˆ MIPS Options ๐ŸŒˆ

Bestie. Sit down. This one is long. MIPS ate and left no crumbs. ๐Ÿฝ๏ธ

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

PHEW. we survived. ๐Ÿซถ


๐Ÿงš MMIX Options ๐Ÿงš

  • -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, huge aura honestly.

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

๐ŸŽ€ MSP430 Options ๐ŸŽ€

  • -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, we love a low-effort icon.

  • -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
  • -mcmodel=code-model

๐ŸŽž๏ธ PDP-11 Options ๐ŸŽž๏ธ

Retro. Vintage. Nostalgic. The PDP-11 is lowkey the grandmother of us all. โœจ

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

๐ŸŒŸ PowerPC Options ๐ŸŒŸ

okay so this one is literally just a redirect and honestly? respect the delegation.

See RS/6000 and PowerPC Options.


๐Ÿ”ง PRU Options ๐Ÿ”ง

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

๐ŸŒธ RISC-V Options ๐ŸŒธ

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

๐Ÿ€ 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 ๐Ÿ‘‘

and HERE is the beast. the moment we've all been waiting for. PowerPC said "let me cook" and produced an entire grocery list. ๐Ÿ”ฅ

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

iconic behaviour, truly. ๐Ÿ’€โœจ


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

Last one of this batch and it's giving mainframe drama, which is honestly so valid. ๐Ÿ›๏ธ

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

๐ŸŒธ SH Options ๐ŸŒธ

okay so the SH (SuperH) crew got a whole fleet of vibe-selectors: -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. periodt โœจ

๐ŸŒž Solaris 2 Options ๐ŸŒž

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

that little lineup above โœจ

๐Ÿ”ฅ 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 ๐Ÿ’œ

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

๐ŸŒˆ V850 Options ๐ŸŒˆ

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

๐Ÿฆ‹ VAX Options ๐Ÿฆ‹

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

๐Ÿงš Visium Options ๐Ÿงš

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

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

bestie. sit down. this list is long and it's giving encyclopaedia:

  • -mtune=cpu-type
  • -march=cpu-type
  • -mtune-ctrl=feature-list
  • -mdump-tune-features
  • -mno-default
  • -mfpmath=unit
  • -masm=dialect
  • -mno-fancy-math-387
  • -mno-fp-ret-in-387
  • -m80387 / -mhard-float
  • -msoft-float
  • -mno-wide-multiply
  • -mrtd
  • -malign-double
  • -mpreferred-stack-boundary=num
  • -mincoming-stack-boundary=num
  • -mcld
  • -mcx16
  • -msahf
  • -mmovbe
  • -mcrc32
  • -mmwait
  • -mrecip / -mrecip=opt
  • -mvzeroupper
  • -mprefer-avx128
  • -mprefer-vector-width=opt
  • -mmove-max=bits
  • -mstore-max=bits
  • -mmmx
  • -msse
  • -msse2
  • -msse3
  • -mssse3
  • -msse4.1
  • -msse4.2
  • -msse4
  • -mavx
  • -mavx2
  • -mavx512f
  • -mavx512pf
  • -mavx512er
  • -mavx512cd
  • -mavx512vl
  • -mavx512bw
  • -mavx512dq
  • -mavx512ifma
  • -mavx512vbmi
  • -msha
  • -maes
  • -mpclmul
  • -mfsgsbase
  • -mrdrnd
  • -mf16c
  • -mfma
  • -mpconfig
  • -mwbnoinvd
  • -mptwrite
  • -mprefetchwt1
  • -mclflushopt
  • -mclwb
  • -mxsavec
  • -mxsaves
  • -msse4a
  • -m3dnow
  • -m3dnowa
  • -mpopcnt
  • -mabm
  • -mbmi
  • -mtbm
  • -mfma4
  • -mxop
  • -madx
  • -mlzcnt
  • -mbmi2
  • -mfxsr
  • -mxsave
  • -mxsaveopt
  • -mrtm
  • -mhle
  • -mlwp
  • -mmwaitx
  • -mclzero
  • -mpku
  • -mthreads
  • -mgfni
  • -mvaes
  • -mwaitpkg
  • -mshstk
  • -mmanual-endbr
  • -mcet-switch
  • -mforce-indirect-call
  • -mavx512vbmi2
  • -mavx512bf16
  • -menqcmd
  • -mvpclmulqdq
  • -mavx512bitalg
  • -mmovdiri
  • -mmovdir64b
  • -mavx512vpopcntdq
  • -mavx5124fmaps
  • -mavx512vnni
  • -mavx5124vnniw
  • -mprfchw
  • -mrdpid
  • -mrdseed
  • -msgx
  • -mavx512vp2intersect
  • -mserialize
  • -mtsxldtrk
  • -mamx-tile
  • -mamx-int8
  • -mamx-bf16
  • -muintr
  • -mhreset
  • -mavxvnni
  • -mavx512fp16
  • -mavxifma
  • -mavxvnniint8
  • -mavxneconvert
  • -mcmpccxadd
  • -mamx-fp16
  • -mprefetchi
  • -mraoint
  • -mamx-complex
  • -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
  • -mrelax-cmpxchg-loop
  • -mindirect-branch=choice
  • -mfunction-return=choice
  • -mindirect-branch-register
  • -mharden-sls=choice
  • -mindirect-branch-cs-prefix
  • -mneeded
  • -mno-direct-extern-access
  • -munroll-only-small-loops
  • -mlam=choice

ate, truly. no crumbs. ๐Ÿ’…

๐ŸŽ€ 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
  • -mextra-l32r-costs=cycles

๐Ÿ’œ zSeries Options ๐Ÿ’œ

zSeries bestie, your moment is elsewhere โ€” head to S/390 and zSeries Options. that's literally the whole note. ๐Ÿซถ


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

okay so compilation can go through up to four stages: preprocessing, compilation proper, assembly and linking โ€” always in that order, no skipping ahead like it's a groupchat. GCC can preprocess and compile several files either into several assembler input files, or into one assembler input file. then each assembler input file produces an object file, and linking squishes all the object files together (the freshly compiled ones and the ones you passed as input) into an executable file. iconic. ๐Ÿ”ฅ

For any given input file, the file name suffix determines what kind of compilation is done:

  • file.c โ€” C source code that must be preprocessed.
  • file.i โ€” C source code that should not be preprocessed.
  • file.ii โ€” C++ source code that should not be preprocessed.
  • file.m โ€” Objective-C source code. Note that you must link with the libobjc library to make an Objective-C program work.
  • file.mi โ€” Objective-C source code that should not be preprocessed.
  • file.mm, file.M โ€” Objective-C++ source code. Note that you must link with the libobjc library to make an Objective-C++ program work. Note that .M refers to a literal capital M.
  • 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 (default), or C, C++ header file to be turned into an Ada spec (via the -fdump-ada-spec switch).
  • file.cc, file.cp, file.cxx, file.cpp, file.CPP, file.c++, file.C โ€” C++ source code that must be preprocessed. Note that in .cxx, the last two letters must both be literally x. Likewise, .C refers to a literal capital C.
  • 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.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). Such files are also called specs.
  • file.adb โ€” Ada source code file containing a library unit body (a subprogram or package body). Such files are also called bodies.
  • file.s โ€” Assembler code.
  • file.S, file.sx โ€” Assembler code that must be preprocessed.
  • other โ€” An object file to be fed straight into linking. Any file name with no recognized suffix is treated this way.

You can specify the input language explicitly 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  objc-cpp-output
objective-c++  objective-c++-header  objective-c++-cpp-output
objc++-cpp-output
assembler  assembler-with-cpp
ada  adascil  adawhy
d
f77  f77-cpp-input  f95  f95-cpp-input
go
modula-2  modula-2-cpp-output
rust
lto
  • -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 of compilation, you can use -x (or filename suffixes) to tell gcc where to start, and one of the options -c, -S, or -E to say where gcc is to stop.

lowkey important: some combinations (for example, -x cpp-output -E) instruct gcc to do nothing at all. like, zero. nada. it just vibes. ๐Ÿ˜ญ

  • -c โ€” bestie, this one says: compile or assemble the source files, but do not link. The linking stage simply is not done. โœจ The ultimate output is in the form of 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. (They're just there. Vibing. Not our problem. ๐Ÿ’…)

  • -S โ€” stop after the stage of compilation proper; do not assemble. The output is in the form of 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 in the form of preprocessed source code, which is sent to the standard output. ๐ŸŒˆ

Input files that don't require preprocessing are ignored.

  • -o file โ€” place the primary output in file file. Yes it says file twice, no I did not write that, it's literally what it says, and honestly iconic of it. ๐ŸŽ€ This applies to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code.

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

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

Like, watch this:

gcc -c foo.c ...

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

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

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

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

A linker output will instead prefix aux and dump outputs:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

okay bestie we're in the โœจlink-time partโœจ of the dumpdir/dumpbase saga and honestly it EATS ๐Ÿ’… so like, when you're compiling AND then linking from multiple input files, a dumppfx (whether it got there by default or you said it out loud) also goes through that whole dumpbase- transformation from before โ€” think of the compilation of foo.c and bar.c up top, except with no -c in sight. ๐ŸŽ€

And if you gave the compiler neither -dumpdir nor -dumpbase? Then the linker output base name โ€” minus auxdropsuf if you specified one, or the executable suffix otherwise โ€” gets a lil dash tacked on and gets appended to the default dumppfx instead. โญ

BUT โ€” and this is the plot twist โ€” unlike the earlier linking cases:
gcc foo.c bar.c -dumpdir dir/pfx- -o main ...

does not append the output name main to dumppfx, and that's because -dumpdir was explicitly specified, periodt. The goal here is that your explicitly-specified dumppfx is allowed to already contain the specified output name as part of the prefix, if that's the vibe you want. Only an explicitly-specified -dumpbase gets combined with it, so that we don't just straight up discard a meaningful option. ๐Ÿ™ˆ


When you're compiling and then linking from a single input file, the linker output base name only gets appended to the default dumppfx (same as above) if it doesn't share its base name with that one single input file name. The single-input linking cases above already covered this โ€” but not the scenario with an explicit -dumpdir that inhibits the combination, even if -save-temps=* tries to override it:

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

Auxiliary outputs get named foo.*, and dump outputs get named foo.c.*, in the current working directory as ultimately requested by -save-temps=cwd. slay, tidy, consistent ๐Ÿฆ‹


โœจ Summing It All Up โœจ

Here's the intuitive-but-slightly-imprecise data flow, bestie โ€” it's giving flow chart energy:

  • The primary output name gets broken into a directory part and a basename part.
  • dumppfx is set to the former โ€” unless it's overridden by -dumpdir or -save-temps=*.
  • dumpbase is set to the latter โ€” unless it's overriden by -dumpbase.
  • If there are multiple inputs or linking, this dumpbase may be combined with dumppfx and taken from each input file.
  • Auxiliary output names for each input are formed by combining dumppfx, dumpbase minus suffix, and the auxiliary output suffix.
  • Dump output names are only different in that the suffix from dumpbase is retained. ๐Ÿ’–

๐ŸŒ€ Auxiliary and Dump Outputs During LTO Recompilation ๐ŸŒ€

okay this bit is niche but you NEED it: when it comes to auxiliary and dump outputs created during LTO recompilation, a combination of dumppfx and dumpbase โ€” as given, or as derived from the linker output name but not from inputs, even in cases where this combination wouldn't otherwise be used as such โ€” is passed down with a trailing period replacing the compiler-added dash (if there was one), as a -dumpdir option to lto-wrapper. ๐Ÿซถ Being involved in linking, this program doesn't normally get any -dumpbase and -dumpbase-ext, and it ignores them. iconic behaviour honestly

And when lto-wrapper is running sub-compilers? It appends LTO stage names to the dumppfx it received, makes sure that thing contains a directory component so it overrides any -dumpdir, and passes that as -dumpbase to the sub-compilers. ๐Ÿงš


๐Ÿ’– THE REST OF THE OPTIONS ๐Ÿ’–

  • -v โ€” prints (to standard error output, heads up) all the commands that actually got executed to run the stages of compilation. It also prints the version number of the compiler driver program, plus the version of the preprocessor and of the compiler proper. receipts, basically ๐Ÿงพ
  • -### โ€” like -v, except the commands are not executed, and the arguments get quoted unless they contain only alphanumeric characters or "./-_". Super useful for shell scripts that wanna capture the command lines the driver generates. โœจ
  • --help โ€” prints (on standard output) a description of the command-line options that gcc understands. ๐Ÿ‘‘ If you also specified -v, then --help gets passed along to the various processes gcc invokes too, so they can each show off the command-line options they accept. And if -Wextra was also specified (prior to the --help option, note it), then command-line options that have no documentation associated with them get displayed as well. no option left behind
  • --target-help โ€” prints (on standard output) a description of the target-specific command-line options for each tool. For some targets, extra target-specific information may also get printed. ๐ŸŽฏ

--help={class|[^]qualifier}[,...]

prints (on standard output) a description of the command-line options the compiler understands that fit into all the specified classes and qualifiers. Here 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 --target-help though, the target-specific options of the linker and assembler are not displayed, because those tools don't 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, you need to select the common class instead.
  • common โ€” display the options that are common to all languages.

And these are the supported qualifiers:

  • undocumented โ€” display only those options that are undocumented. the secret menu ๐Ÿ™ˆ
  • joined โ€” display options taking an argument that appears after an equal sign in the same continuous piece of text, like: --help=target.
  • separate โ€” display options taking an argument that appears as a separate word following the original option, like: -o output-file.

So 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
Careful bestie: the argument to --help= should not consist solely of inverted qualifiers. ๐Ÿšจ

Combining several classes is possible, although this usually restricts the output so much that there's literally nothing to display. ngl that's kind of the point One case where it does work, though, 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, and 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 it takes precedence over any --help= option. periodt. ๐Ÿ‘‘

If the -Q option appears on the command line before the --help= option, then the descriptive text displayed by --help= changes. Instead of describing the displayed options, you get an indication of whether the option is enabled, disabled, or set to a specific value โ€” assuming the compiler knows this at the point where the --help= option is used. ๐Ÿ’…

Here's 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's 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

the diff-and-grep combo is genuinely so satisfying, look at her go ๐ŸŒˆ

  • --version โ€” display the version number and copyrights of the invoked GCC. ๐ŸŽ€
  • -pass-exit-codes โ€” normally the gcc program exits with code 1 if any phase of the compiler returns a non-success return code. If you specify -pass-exit-codes, then gcc instead returns with the numerically highest error produced by any phase that returned an error indication. Heads up: the C, C++, and Fortran front ends return 4 if an internal compiler error is encountered. ๐Ÿ˜ญ
  • -pipe โ€” use pipes rather than temporary files for communication between the various stages of compilation. This fails to work on some systems where the assembler is unable to read from a pipe; but the GNU assembler has no trouble. ๐Ÿงš we love a cooperative assembler
  • -specs=file โ€” process file after the compiler reads in the standard specs file, so you can override the defaults that the gcc driver program uses when figuring out what switches to pass to cc1, cc1plus, as, ld, etc. More than one -specs=file can be specified on the command line, and they're processed in order, from left to right. โžก๏ธ
  • -wrapper โ€” invoke all subcommands under a wrapper program. The name of the wrapper program and its parameters get passed as a comma-separated list. ๐Ÿซถ
gcc -c t.c -wrapper gdb,--args

This invokes all subprograms of gcc under gdb --args, so the invocation of cc1 becomes gdb --args cc1 .... debugging but make it main character energy ๐Ÿ’€

  • -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. ๐ŸŒธ Directories referenced by directives are not affected by these options, though. See also -fmacro-prefix-map, -fdebug-prefix-map, -fprofile-prefix-map and -fcanon-prefix-map. โญ
  • -fcanon-prefix-map โ€” for the -f*-prefix-map options, normally comparison of the old prefix against the filename that would normally be referenced in the result of the compilation is done using textual comparison of the prefixes โ€” or ignoring character case for case insensitive filesystems, and considering slashes and backslashes as equal on DOS based filesystems. The -fcanon-prefix-map causes such comparisons to be done on canonicalized paths of old and the referenced filename. ๐Ÿฆ‹ canonicalization, but cute
  • -fplugin=name.so โ€” bestie, this loads the plugin code in file name.so, which is assumed to be a shared object that the compiler will dlopen. The base name of the shared object file is what identifies the plugin for argument parsing (peep -fplugin-arg-name-key=value below). Every plugin should define the callback functions specified in the Plugins API. ๐Ÿ’…
  • -fplugin-arg-name-key=value โ€” defines an argument called key with a value of value for the plugin called name. slay.
  • -fdump-ada-spec[-slim] โ€” for C and C++ source and include files, this generates corresponding Ada specs. iconic behavior honestly.
  • -fada-spec-parent=unit โ€” in conjunction with -fdump-ada-spec[-slim] above, this generates Ada specs as child units of parent unit. ๐Ÿซถ
  • -fdump-go-spec=file โ€” for input files in any language, this generates corresponding Go declarations in file. It makes 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. no cap.
  • @file โ€” reads command-line options from file. The options read are inserted in place of the original @file option. If file does not exist, or cannot be read, then the option will be treated literally, and not removed. Options in file are separated by whitespace. A whitespace character may be included in an option by surrounding the entire option in either single or double quotes. Any character (including a backslash) may be included by prefixing the character to be included with a backslash. The file may itself contain additional @file options; any such options will be processed recursively. ๐Ÿ”

โœจ Compiling C++ Programs โœจ

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

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

โœจ Options Controlling C Dialect โœจ

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

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

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

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

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

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

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

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

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

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

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

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

  • -fno-asm โ€” bestie, this one tells GCC to STOP treating asm, inline and typeof like keywords, which means your code is free to use those exact words as identifiers instead ๐Ÿ’…. If you still want the keyword behaviour, just use the underscored versions: __asm__, __inline__ and __typeof__. Also, in C, -ansi implies -fno-asm (surprise!).

In C++, inline is a standard keyword and is not affected by this switch at all โ€” so if that's the vibe you're going for, you probably want -fno-gnu-keywords instead, which disables typeof but leaves asm and inline alone. In C99 mode (-std=c99 or -std=gnu99), this switch only hits the asm and typeof keywords, because inline is a standard keyword in ISO C99. And in C2X mode (-std=c2x or -std=gnu2x), it only touches asm, since typeof is a standard keyword in ISO C2X. the way the keyword list keeps shrinking ๐Ÿ˜ญ

  • -fno-builtin
  • -fno-builtin-function โ€” okay so these two say: don't recognize built-in functions that don't start with the __builtin_ prefix ๐Ÿšซโœจ.

Normally GCC generates special code to handle certain built-in functions way more efficiently โ€” for example, calls to alloca may become single instructions that 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, and you can't change the behaviour of the functions by linking with a different library. that's the tradeoff, no cap ๐Ÿ˜ญ

Plus, once a function is recognized as built-in, GCC may use info about it to warn you about problems with calls to it, 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. iconic behaviour honestly.

With the -fno-builtin-function option, only the built-in function function is disabled. And heads up: function must not begin with __builtin_. If you name a function that isn't built-in in this version of GCC, the option is just ignored (no drama, it moves on ๐Ÿ™ˆ). There is no corresponding -fbuiltin-function option, so if you want to enable built-in functions selectively while 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))
  • -fcond-mismatch โ€” lets you have conditional expressions with mismatched types in the second and third arguments, and the value of such an expression is void. This option is not supported for C++ ๐Ÿ’€.
  • -ffreestanding โ€” asserting that compilation targets a freestanding environment, which implies -fno-builtin. A freestanding environment is one where the standard library may not exist, and program startup may not necessarily be at main โ€” the most obvious example being an OS kernel ๐Ÿ‘‘. This is equivalent to -fno-hosted.
  • -fgimple โ€” enables parsing of function definitions marked with __GIMPLE. This is an experimental feature that allows unit testing of GIMPLE passes. lowkey niche but okay ๐Ÿงš
  • -fgnu-tm โ€” when you specify this, 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, bestie ๐Ÿ™ˆ.

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). โš ๏ธ
  • -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. cute and efficient ๐ŸŽ€

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 behaviour โ€” nothing new, just the usual). But it 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. very handy, iykyk ๐Ÿ’–

  • -fhosted โ€” asserts that compilation targets a hosted environment, which implies -fbuiltin. A hosted environment is one where 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.
  • -flax-vector-conversions โ€” allows implicit conversions between vectors with differing numbers of elements and/or incompatible element types. okay but listen: this option should not be used for new code, fr fr ๐Ÿšซ.
  • -fms-extensions โ€” accepts some non-standard constructs used in Microsoft header files.

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

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

Some cases of unnamed fields in structures and unions are only accepted with this option. Note that this option is off for all targets except for x86 targets using ms-abi.

  • -foffload=disable
  • -foffload=default
  • -foffload=target-list โ€” specify for which OpenMP and OpenACC offload targets code should be generated โœจ. The default behaviour, equivalent to -foffload=default, is to generate code for all supported offload targets. The -foffload=disable form generates code only for the host fallback, while -foffload=target-list generates code only for the specified comma-separated list of offload targets.

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

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

Typical command lines are

-foffload-options=-lgfortran -foffload-options=-lm
-foffload-options="-lgfortran -lm" -foffload-options=nvptx-none=-latomic
-foffload-options=amdgcn-amdhsa=-march=gfx906 -foffload-options=-lm
  • -fopenacc โ€” enables handling of OpenACC directives #pragma acc in C/C++ and !$acc in Fortran ๐Ÿ”ฅ. When -fopenacc is specified, the compiler generates accelerated code according to the OpenACC Application Programming Interface v2.6 <https://www.openacc.org>. This option implies -pthread, and thus is only supported on targets that have support for -pthread.
  • -fopenacc-dim=geom โ€” specifies the default compute dimensions for parallel offload regions that don't explicitly specify them. The geom value is a triple of :-separated sizes, in order gang, worker and, vector. A size can be omitted to use a target-specific default value ๐Ÿ’….
  • -fopenmp โ€” enables handling of OpenMP directives #pragma omp in C/C++, [[omp::directive(...)]] and [[omp::sequence(...)]] in C++ and !$omp in Fortran ๐Ÿ‘‘. When -fopenmp is specified, the compiler generates parallel code according to the OpenMP Application Program Interface v4.5 <https://www.openmp.org>. This option implies -pthread, and thus is only supported on targets that have support for -pthread. Also, -fopenmp implies -fopenmp-simd.
  • -fopenmp-simd โ€” enables handling of OpenMP's simd, declare simd, declare reduction, assume, ordered, scan, loop directives and combined or composite directives with simd as a constituent, using #pragma omp in C/C++, [[omp::directive(...)]] and [[omp::sequence(...)]] in C++ and !$omp in Fortran ๐ŸŒธ. Other OpenMP directives are just ignored, bestie, we don't see them ๐Ÿ™ˆ.
  • -fopenmp-target-simd-clone
  • -fopenmp-target-simd-clone=device-type โ€” in addition to generating SIMD clones for functions marked with the declare simd directive, GCC also generates clones for functions marked with the OpenMP declare target directive that are suitable for vectorization when this option is in effect โšก. The device-type may be one of none, host, nohost, and any, which correspond to keywords for the device_type clause of the declare target directive; clones are generated for the intersection of devices specified. -fopenmp-target-simd-clone is equivalent to -fopenmp-target-simd-clone=any and -fno-openmp-target-simd-clone is equivalent to -fopenmp-target-simd-clone=none.

At -O2 and higher (but not -Os or -Og) this optimization defaults to -fopenmp-target-simd-clone=nohost; otherwise it is disabled by default.

  • -fpermitted-flt-eval-methods=style โ€” okay this one's a bit of a deep cut but stay with me ๐Ÿงš. 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. periodt ๐Ÿ’…

  • -fplan9-extensions โ€” accepts some non-standard constructs used in Plan 9 code ๐ŸŒˆ.

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

  • -fsigned-bitfields, -funsigned-bitfields, -fno-signed-bitfields, -fno-unsigned-bitfields โ€” these four decide whether a bit-field is signed or unsigned when the declaration just... doesn't say "signed" or "unsigned" anywhere ๐Ÿ‘€. Default vibes? signed, because it's consistent โ€” the basic integer types like "int" are signed types, so bit-fields match the family. ๐Ÿซถ
  • -fsigned-char โ€” let the type "char" be signed, exactly like "signed char".

Heads up bestie: this is literally equivalent to -fno-unsigned-char, which is the negative form of -funsigned-char. And the other way round too โ€” -fno-signed-char is equivalent to -funsigned-char. Flip, flip, flip. ๐Ÿฆ‹

  • -funsigned-char โ€” let the type "char" be unsigned, like "unsigned char".

Every kind of machine has its own default for what "char" should be. It's either like "unsigned char" by default or like "signed char" by default. No universal answer, it's giving platform-dependent ๐Ÿ’….

Ideally, a portable program should always use "signed char" or "unsigned char" whenever it actually cares about the signedness of an object. But like... tons of programs out there just use plain "char" and expect it to be signed, or expect it to be unsigned, depending on whatever machines they were originally written for. This option (and its inverse) is your rescue mission: it lets you make such a program work with the opposite default. ๐Ÿ”ฅ

And a lil detail that matters: 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. Distinct. Not the same. Periodt. โœจ

  • -fstrict-flex-arrays โ€” controls when a trailing array of a structure gets treated as a flexible array member, for the purpose of accessing the elements of such an array. ๐Ÿ‘‘

The positive form is equivalent to -fstrict-flex-arrays=3, the strictest โ€” a trailing array is treated as a flexible array member only when it's declared as a flexible array member per C99 standard onwards. The negative form is equivalent to -fstrict-flex-arrays=0, the least strict โ€” all trailing arrays of structures get treated as flexible array members. Choose your chaos level lol ๐Ÿ’€

  • -fstrict-flex-arrays=level โ€” same deal, but now you're driving ๐Ÿš—. Controls when a trailing array of a structure is treated as a flexible array member for the purpose of accessing the elements of such an array. The value of level controls the level of strictness.

The possible values of level are the same as for the "strict_flex_array" attribute.

And you can control this behavior for one specific trailing array field of a structure by using the variable attribute "strict_flex_array" attribute. Targeted. Surgical. Iconic. ๐ŸŽ€

  • -fsso-struct=endianness โ€” sets the default scalar storage order of structures and unions to the specified endianness. The accepted values are big-endian, little-endian and native for the native endianness of the target (which is the default). This option is not supported for C++. ๐Ÿ™ˆ
โš ๏ธ Warning, bestie, for real: 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. Binary incompatible. That means it will not talk to the other code. Do not do this casually. ๐Ÿ˜ญ

๐ŸŒˆ Options Controlling C++ Dialect ๐ŸŒˆ

This section is all about the command-line options that are only meaningful for C++ programs ๐Ÿ’–. But plot twist โ€” you can also use most of the GNU compiler options no matter 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. Multi-talented. ๐Ÿ’…

Also, some options for compiling C programs, such as -std, are also relevant for C++ programs. Sharing is caring. ๐Ÿซถ

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. Yes, the default is the moving target. That's just how it is. ๐Ÿ˜ญ

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, treats nullptr_t as a builtin type and corrects the mangling of lambdas in default argument scope.

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

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

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

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

Version 12, which first appeared in G++ 8, corrects the calling conventions for empty classes on the x86_64 target and for classes with only deleted copy/move constructors. It accidentally changes the calling convention for classes with a deleted copy constructor and a trivial move constructor. Oopsie. ๐Ÿ’€

Version 13, which first appeared in G++ 8.2, fixes the accidental change in version 12. Cleanup era. โœจ

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

Version 15, which first appeared in G++ 10.3, corrects G++ 10 ABI tag regression.

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

Version 17, which first appeared in G++ 12, fixes layout of classes that inherit from aggregate classes with default member initializers in C++14 and up.

Version 18, which first appeared in G++ 13, fixes manglings of lambdas that have additional context.

See also -Wabi. ๐Ÿ‘€

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

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

And the crossover rules: if this option is not provided but -Wabi=n is, then that version is used for compatibility aliases. If this option is provided along with -Wabi (without the version), then the version from this option is used for the warning. Teamwork, but make it specific. ๐Ÿ’…

  • -fno-access-control โ€” turn off all access checking. ๐Ÿ”“ This switch is mainly useful for working around bugs in the access control code. It's the "we don't do rules here" flag.
  • -faligned-new โ€” enable support for C++17 "new" of types that require more alignment than "void* ::operator new(std::size_t)" provides. A numeric argument such as -faligned-new=32 can be used to specify how much alignment (in bytes) is provided by that function, but few users will need to override the default of alignof(std::max_align_t). Key word: few. ๐Ÿซถ

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

  • -fchar8_t, -fno-char8_t โ€” enable support for "char8_t" as adopted for C++20. This includes the addition of a new "char8_t" fundamental type, changes to the types of UTF-8 string and character literals, new signatures for user-defined literals, associated standard library updates, and new "__cpp_char8_t" and "__cpp_lib_char8_t" feature test macros. It's a whole glow-up. ๐ŸŒธ

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

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

and introduces new signatures for user-defined literals:

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

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

const char *cp = u8"xx";// error: invalid conversion from
                        //        `const char8_t*' to `const char*'
int f(const char*);
auto v = f(u8"xx");     // error: invalid conversion from
                        //        `const char8_t*' to `const char*'
std::string s{u8"xx"};  // error: no matching function for call to
                        //        `std::basic_string<char>::basic_string()'
using namespace std::literals;
s = u8"xx"s;            // error: conversion from
                        //        `basic_string<char8_t>' to non-scalar
                        //        type `basic_string<char>' requested
  • -fcheck-new โ€” check that the pointer returned by "operator new" is non-null before attempting to modify the storage allocated. ๐Ÿ•ต๏ธ

This check is normally unnecessary because the C++ standard specifies that "operator new" only returns 0 if it is declared throw(), in which case the compiler always checks the return value even without this option. In all other cases, when "operator new" has a non-empty exception specification, memory exhaustion is signalled by throwing "std::bad_alloc". See also new (nothrow).


  • -fconcepts โ€” concepts time bestie!! โœจ turns on support for the C++ Concepts feature so you can constrain template arguments and stop your templates from accepting literally anything with a pulse. With -std=c++20 and above, Concepts are part of the language standard, so -fconcepts defaults to on. ๐Ÿ’…
  • -fconcepts-ts โ€” some constructs that were allowed by the earlier C++ Extensions for Concepts Technical Specification, ISO 19217 (2015), but didn't make it into the standard, can additionally be enabled by this. So it's the throwback-vibes option. ๐ŸŽ€
  • *-fconstexpr-depth=n* โ€” sets the maximum nested evaluation depth for C++11 constexpr functions to n. A limit is needed to detect endless recursion during constant expression evaluation (otherwise your compiler just spirals forever, not the cute kind of spiral ๐Ÿ’€). The minimum specified by the standard is 512.
  • *-fconstexpr-cache-depth=n* โ€” sets 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 very large from highly recursive evaluations ๐Ÿ˜ญ). The default is 8. Very few users are likely to want to adjust it, but if your code does heavy constexpr calculations you might want to experiment to find which value works best for you. science experiment arc, go off.
  • -fconstexpr-fp-except โ€” okay so Annex F of the C standard says that IEC559 floating point exceptions encountered at compile time should not stop compilation. C++ compilers have historically not followed this guidance, instead treating floating point division by zero as non-constant even though it has a well defined value. ๐Ÿซ  This flag tells the compiler to give Annex F priority over other rules saying that a particular operation is undefined.
constexpr float inf = 1./0.; // OK with -fconstexpr-fp-except
  • *-fconstexpr-loop-limit=n* โ€” sets the maximum number of iterations for a loop in C++14 constexpr functions to n. Again, a limit is needed to detect infinite loops during constant expression evaluation. The default is 262144 (that's 1<<18 for the hex girlies ๐Ÿงš).
  • *-fconstexpr-ops-limit=n* โ€” sets the maximum number of operations during a single constexpr evaluation. Here's the tea ๐Ÿ“: 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 a body of some loop or even outside of a loop too many expressions need to be evaluated, the resulting constexpr evaluation might take too long. The default is 33554432 (1<<25).
  • -fcontracts โ€” enables experimental support for the C++ Contracts feature, as briefly added to and then removed from the C++20 working paper (N4820). The implementation also includes proposed enhancements from papers P1290, P1332, and P1429. This functionality is intended mostly for those interested in experimentation towards refining the feature to get it into shape for a future C++ standard. lab-coat energy ๐Ÿฅผโœจ

On violation of a checked contract, the violation handler is called. Users can replace the violation handler by defining:

void
handle_contract_violation (const std::experimental::contract_violation&);

There are different sets of additional flags that can be used together to specify which contracts will be checked and how, for N4820 contracts, P1332 contracts, or P1429 contracts; these sets cannot be used together. (pick a lane bestie ๐Ÿšซ)

  • -fcontract-mode=[on|off] โ€” control whether any contracts have any semantics at all. Defaults to on.
  • -fcontract-assumption-mode=[on|off] โ€” [N4820] control whether contracts with level axiom should have the assume semantic. Defaults to on.
  • -fcontract-build-level=[off|default|audit] โ€” [N4820] specify which level of contracts to generate checks for. Defaults to default.
  • -fcontract-continuation-mode=[on|off] โ€” [N4820] control whether to allow the program to continue executing after a contract violation. That is, do checked contracts have the maybe semantic described below rather than the never semantic. Defaults to off.
  • *-fcontract-role=<name>:<default>,<audit>,<axiom>* โ€” [P1332] specify the concrete semantics for each contract level of a particular contract role.
  • *-fcontract-semantic=[default|audit|axiom]:<semantic>* โ€” [P1429] specify the concrete semantic for a particular contract level.
  • -fcontract-strict-declarations=[on|off] โ€” control whether to reject adding contracts to a function after its first declaration. Defaults to off.

The possible concrete semantics that can be specified with -fcontract-role or -fcontract-semantic are:

  • "ignore" โ€” this contract has no effect. it's giving nothing, and that's the point.
  • "assume" โ€” this contract is treated like C++23 "[[assume]]".
  • "check_never_continue", "never", "abort" โ€” this contract is checked. If it fails, the violation handler is called. If the handler returns, "std::terminate" is called. ๐Ÿ’€
  • "check_maybe_continue", "maybe" โ€” this contract is checked. If it fails, the violation handler is called. If the handler returns, execution continues normally. ๐Ÿซถ
  • -fcoroutines โ€” enable support for the C++ coroutines extension (experimental). she's experimental and she knows it โœจ
  • -fno-elide-constructors โ€” the C++ standard allows an implementation to omit creating a temporary that is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases. This option also causes G++ to call trivial member functions which otherwise would be expanded inline. In C++17, the compiler is required to omit these temporaries, but this option still affects trivial member functions.
  • -fno-enforce-eh-specs โ€” don't generate code to check for violation of exception specifications at run time. This option violates the C++ standard ๐Ÿ˜ณ, but may be useful for reducing code size in production builds, much like defining "NDEBUG". This does not give user code permission to throw exceptions in violation of the exception specifications; the compiler still optimizes based on the specifications, so throwing an unexpected exception results in undefined behavior at run time. So like... be normal about it.
  • -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 this, any use of such a variable goes through a wrapper function that performs any necessary initialization. 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 is 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.

  • -ffold-simple-inlines, -fno-fold-simple-inlines โ€” permit the C++ frontend to fold calls to "std::move", "std::forward", "std::addressof" and "std::as_const". In contrast to inlining, this means no debug information will be generated for such calls. Since these functions are rarely interesting to debug, this flag is enabled by default unless -fno-inline is active. ๐Ÿ›
  • -fno-gnu-keywords โ€” do not 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.
  • -fimplicit-constexpr โ€” make inline functions implicitly constexpr, if they satisfy the requirements for a constexpr function. This option can be used in C++14 mode or later. This can result in initialization changing from dynamic to static and other optimizations. glow-up for your inline functions fr fr โœจ
  • -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 to avoid getting 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, do not emit out-of-line copies of inline functions controlled by "#pragma implementation". This causes linker errors if these functions are not inlined everywhere they are called. ๐Ÿ’€ space-saving but at what cost
  • -fmodules-ts, -fno-modules-ts โ€” enable support for C++20 modules. The -fno-modules-ts is usually not needed, as that is the default. Even though this is a C++20 feature, it is not currently implicitly enabled by selecting that standard version. the way that C++20 modules just Do That ๐Ÿ™ˆ
  • -fmodule-header, -fmodule-header=user, -fmodule-header=system โ€” compile a header file to create an importable header unit.
  • -fmodule-implicit-inline โ€” member functions defined in their class definitions are not implicitly inline for modular code. This is different to traditional C++ behavior, for good reasons. However, it may result in a difficulty during code porting. This option makes such function definitions implicitly inline. It does however generate an ABI incompatibility, so you must use it everywhere or nowhere ๐Ÿšจ (Such definitions outside of a named module remain implicitly inline, regardless.)
  • -fno-module-lazy โ€” disable lazy module importing and module mapper creation. she said no thanks to lazy, we're doing it live
  • -fmodule-mapper=[hostname]:port[?ident]
  • -fmodule-mapper=|program[?ident] args...
  • -fmodule-mapper==socket[?ident]
  • -fmodule-mapper=<>[inout][?ident]
  • -fmodule-mapper=<in>out[?ident]
  • -fmodule-mapper=file[?ident]

an oracle to query for module name to filename mappings ๐Ÿ”ฎ If unspecified the CXX_MODULE_MAPPER environment variable is used, and if that is unset, an in-process default is provided. bestie the oracle does not take walk-ins


  • -fmodule-only โ€” bestie, this one ONLY spits out the Compiled Module Interface and โœจnothing elseโœจ. No object file, no crumbs. Just the CMI, that's the whole fit.
  • -fms-extensions โ€” turns OFF the Wpedantic warnings about stuff people use in MFC, like implicit int and pulling a pointer to a member function through non-standard syntax. Basically: "yeah we know it's not kosher, we're not gonna yell about it ๐Ÿ’…".
  • -fnew-inheriting-ctors โ€” switches on the P0136 glow-up to how C++11 constructor inheritance actually behaves. It's part of C++17 but it's also considered a Defect Report against C++11 and C++14, so it's retroactively iconic. It's on by default unless you go -fabi-version=10 or lower (rude).
  • -fnew-ttp-matching โ€” enables the P0522 fix for Core issue 150, i.e. template template parameters and default arguments. Translation: a template with default template arguments can now be passed as an argument for a template template parameter that has fewer template parameters. Enabled by default for -std=c++17 ๐Ÿซถ.
  • -fno-nonansi-builtins โ€” disables the built-in declarations of functions that ANSI/ISO C never mandated. The whole squad getting yeeted: ffs, alloca, _exit, index, bzero, conjf, and friends. No cap.
  • -fnothrow-opt โ€” treats a throw() exception specification like it were a noexcept spec, so the compiler can shrink or fully delete the text-size overhead compared to a function with no exception spec at all. Plot twist though: 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 locals can be optimized away. The semantic tea โ˜•: an exception thrown out of a function with such a spec ends in a call to terminate instead of unexpected.
  • -fno-operator-names โ€” do NOT treat those operator-name keywords and, bitand, bitor, compl, not, or and xor as synonyms-as-keywords. They're just... words now. lowercase behavior fr.
  • -fno-optional-diags โ€” kills the diagnostics that the standard literally says a compiler does not need to issue. rn the only such diagnostic G++ actually issues is the one for a name having multiple meanings within a class. that's the whole list bestie.
  • -fpermissive โ€” demotes some diagnostics about nonconformant code from errors down to warnings. So yeah, using -fpermissive lets some nonconforming code actually compile. ๐Ÿ˜ญ live your truth.
  • -fno-pretty-templates โ€” ok so normally, when an error message points at a specialization of a function template, the compiler prints the template's signature followed by the template arguments and any typedefs or typenames in that signature (like void f(T) [with T = int] instead of void f(int)) so it's obvious which template is being dramatic. And when an error 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 behaviors makes the error HARDER to read instead of easier, -fno-pretty-templates disables them both. you're welcome.
  • -fno-rtti โ€” disables generating info about every class with virtual functions that the C++ run-time type identification features (dynamic_cast and typeid) need. If you don't use those parts of the language, this flag saves you some space, slay. Heads up though: exception handling uses the same info, but G++ generates it as needed. And dynamic_cast 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. For example, programs may fail to link if a class compiled with -fno-rtti is used as a base for a class compiled with -frtti. ๐Ÿ’€ do not do this to yourself.
  • -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. Super 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 -Wsized-deallocation will warn you about places that might wanna add a definition ๐Ÿ‘€.

  • -fstrict-enums โ€” lets the compiler optimize using the assumption that a value of enumerated type can only be one of the values of the enumeration (as defined in the C++ standard; basically, a value that fits in the minimum number of bits needed to represent all the enumerators). This assumption may not be valid if the program uses a cast to convert an arbitrary integer value into the enumerated type. so like... only if you're being feral.
  • -fstrong-eval-order โ€” evaluates member access, array subscripting, and shift expressions left-to-right, and evaluates assignment right-to-left, as adopted for C++17. Enabled by default with -std=c++17. There's also -fstrong-eval-order=some, which enables just the ordering of member access and shift expressions, and that's the default without -std=c++17.
  • -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. yes we're capping the backtrace, it's giving self-care โœจ.
  • -ftemplate-depth=n โ€” sets the maximum instantiation depth for template classes to n. You need some limit on template instantiation depth to catch 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 even hitting 1024 in some situations ๐Ÿ˜ญ. don't ask.
  • -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 code size slightly in code that genuinely doesn't need to be thread-safe. only if you're sure bestie ๐Ÿซถ.
  • -fuse-cxa-atexit โ€” registers destructors for objects with static storage duration with the __cxa_atexit function instead of 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. check first, no cap.
  • -fno-use-cxa-get-exception-ptr โ€” don't use the __cxa_get_exception_ptr runtime routine. Doing this causes std::uncaught_exception to be incorrect, but it's necessary if that runtime routine isn't available. trade-offs, babes.
  • -fvisibility-inlines-hidden โ€” this switch declares that you (the user) are not attempting to compare pointers to inline functions or methods where the addresses of the two functions are taken in different shared objects.

The effect: GCC may effectively mark inline methods with __attribute__ ((visibility ("hidden"))), so they don't show up in the export table of a DSO and don't need a PLT indirection when used inside that DSO. Turning this on can have a dramatic effect on load and link times of a DSO, because it massively shrinks the dynamic export table when the library makes heavy use of templates ๐Ÿ”ฅ.

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

You can mark a method as having a visibility explicitly to negate the effect of the switch for that method. For example, if you do wanna 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, btw.

Explicitly instantiated inline methods are unaffected by this option, since their linkage might otherwise cross a shared library boundary. special case, iconic.

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

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

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

In new code it's better to use -fvisibility=hidden and export the classes that are meant to be externally visible. Unfortunately, it's possible for code to rely โ€” perhaps accidentally โ€” on the Visual Studio behavior. ๐Ÿ™ˆ

Among the consequences of these changes: 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. When this flag is given, it's a violation of the ODR to define types with the same name differently. so like, be careful.

  • -fno-weak โ€” don't use weak symbol support, even if the linker provides it. By default G++ uses weak symbols if they're available. This option exists only for testing, and should not be used by end-users; it results in inferior code and has no benefits. It may be removed in a future release of G++. ๐Ÿšจ do not touch, seriously.
  • -fext-numeric-literals (C++ and Objective-C++ only) โ€” accepts imaginary, fixed-point, or machine-defined literal number suffixes as GNU extensions. When this option is turned off, those suffixes are treated as C++11 user-defined literal numeric suffixes. This is on by default for all pre-C++11 dialects and all GNU dialects: -std=c++98, -std=gnu++98, -std=gnu++11, -std=gnu++14. This option is off by default for ISO C++11 onwards (-std=c++11, ...).
  • -nostdinc++ โ€” don't 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.) so it's not a full blackout, just a C++-flavored one ๐Ÿ’….
  • -flang-info-include-translate, -flang-info-include-translate-not, -flang-info-include-translate=header โ€” informs you about include translation events ๐Ÿ“ฃ. The first one notes accepted include translations, the second notes declined include translations. The header form informs you about include translations relating to that specific header. And if header is of the form "user" or <system>, it gets resolved to a specific user or system header using the include path. iykyk.
  • -flang-info-module-cmi, -flang-info-module-cmi=module โ€” bestie, this one's all about peeking at Compiled Module Interface pathnames ๐Ÿ’…. The plain form notes every CMI pathname that gets read. The =module form won't note the reading of one specific module's CMI. And heads up: module can be a named module **or a header-unit (you signal "header-unit" by either giving a pathname that has directory separators in it, or by wrapping the thing in "<>" or ""). iykyk ๐ŸŽ€
  • -stdlib=libstdc++,libc++ โ€” when G++ was configured to support this option, it lets you pick an alternate C++ runtime library โœจ. Two options on the menu:
    • libstdc++ โ€” the default, the native C++ runtime for G++ ๐Ÿซถ
    • libc++ โ€” the C++ runtime that's installed on some operating systems (like Darwin versions from Darwin11 onwards) ๐Ÿฆ‹

Picking one switches G++ to use the headers from that library, and makes it emit -lstdc++ or -lc++ (respectively, obviously ๐Ÿ’…) whenever a C++ runtime is needed for linking.


Also, these warning options only have meaning for C++ programs ๐Ÿ‘‘:

  • -Wabi-tag (C++ and Objective-C++ only) โ€” warns when a type that has an ABI tag gets used in a context that doesn't have that ABI tag. Wanna know more about ABI tags? Go see C++ Attributes ๐Ÿ“š.
  • -Wcomma-subscript (C++ and Objective-C++ only) โ€” warns about comma expressions showing up inside a subscripting expression ๐Ÿ˜ญ. This usage got deprecated in C++20 and is gonna be removed in C++23. But plot twist: a comma expression wrapped in "( )" is not deprecated. Example:
void f(int *a, int b, int c) {
    a[b,c];     // deprecated in C++20, invalid in C++23
    a[(b,c)];   // OK
}

In C++23 it's actually valid to have comma-separated expressions in a subscript when an overloaded subscript operator is found and it supports the right number and types of arguments โœจ. G++ will accept the formerly valid syntax for code that isn't valid in C++23 but used to be valid (though deprecated) in C++20, with a pedantic warning that you can turn off using -Wno-comma-subscript.

Enabled by default with -std=c++20 unless -Wno-deprecated, and with -std=c++23 regardless of -Wno-deprecated. ๐Ÿ’…

  • -Wctad-maybe-unsupported (C++ and Objective-C++ only) โ€” warns when you do class template argument deduction (CTAD) on a type that has no explicitly written deduction guides ๐Ÿ‘€. It points out the cases where CTAD only succeeded because the compiler synthesized the implicit deduction guides โ€” which might not be what the programmer actually wanted, ngl. Some style guides only allow CTAD on types that specifically "opt-in", i.e. types designed to support CTAD. You can suppress this warning with the following pattern:
struct allow_ctad_t; // any name works
template <typename T> struct S {
  S(T) { }
};
// Guide with incomplete parameter type will never be considered.
S(allow_ctad_t) -> S<void>;
  • -Wctor-dtor-privacy (C++ and Objective-C++ only) โ€” warns when a class looks straight-up unusable because every constructor or destructor in it is private, and it has neither friends nor public static member functions ๐Ÿ’€. Also warns if there are no non-private methods, and there's at least one private member function that isn't a constructor or a destructor.
  • -Wdangling-reference (C++ and Objective-C++ only) โ€” warns when a reference gets bound to a temporary whose lifetime has already ended ๐Ÿ˜ญ. Like:
int n = 1;
const int& r = std::max(n - 1, n + 1); // r is dangling

In that example up there, two temporaries get created โ€” one for each argument โ€” and a reference to one of them gets returned. But bestie, both temporaries are destroyed at the end of the full expression, so the reference r is dangling. This warning also catches dangling references in member initializer lists:

const int& f(const int& i) { return i; }
struct S {
  const int &r; // r is dangling
  S() : r(f(10)) { }
};

Member functions get checked too, but only their object argument:

struct S {
   const S& self () { return *this; }
};
const S& s = S().self(); // s is dangling

Some functions are safe in this respect, like "std::use_facet": they take and return a reference, but they don't return one of their arguments โ€” which can fool the warning ๐Ÿ˜ตโ€๐Ÿ’ซ. You can exclude such functions from the warning by wrapping them in a "#pragma":

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-reference"
const T& foo (const T&) { ... }
#pragma GCC diagnostic pop

-Wdangling-reference also warns about code like

auto p = std::minmax(1, 2);

where "std::minmax" returns "std::pair<const int&, const int&>", and both references dangle after the end of the full expression containing the "std::minmax" call ๐Ÿซ .

This warning is enabled by -Wextra.

  • -Wdelete-non-virtual-dtor (C++ and Objective-C++ only) โ€” warns when "delete" is used to destroy an instance of a class that has virtual functions and a 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 doesn't have a virtual destructor. This warning is enabled by -Wall.
  • -Wdeprecated-copy (C++ and Objective-C++ only) โ€” warns 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. And with -Wdeprecated-copy-dtor, it also deprecates if the class has a user-provided destructor.
  • -Wno-deprecated-enum-enum-conversion (C++ and Objective-C++ only) โ€” disables the warning about the case where the usual arithmetic conversions get 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) โ€” disables the warning about the case where the usual arithmetic conversions get 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. Example time:
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) โ€” don't warn about uses of "std::initializer_list" that are likely to result in dangling pointers ๐Ÿ˜ญ. Because the underlying array for an "initializer_list" is handled like a normal C++ temporary object, it's genuinely easy to accidentally 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-constexpr โ€” warns when a function never produces a constant expression ๐Ÿ‘‘. In C++20 and earlier, for every "constexpr" function and function template, there must be at least one set of function arguments in at least one instantiation such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression. C++23 removed that restriction, so it's possible to have a function or function template marked "constexpr" where no invocation satisfies the requirements of a core constant expression. Wild, right?

This warning is enabled as a pedantic warning by default in C++20 and earlier. In C++23, -Winvalid-constexpr can be turned on, and in that case it'll be an ordinary warning. Example:

void f (int& i);
constexpr void
g (int& i)
{
  // Warns by default in C++20, in C++23 only with -Winvalid-constexpr.
  f(i);
}
  • -Winvalid-imported-macros โ€” verifies that all imported macro definitions are valid at the end of compilation โœจ. This is not enabled by default, since it requires extra processing to figure out. It may be useful when you're preparing sets of header-units, to make sure the macros are consistent ๐ŸŽ€.
  • -Wno-literal-suffix (C++ and Objective-C++ only) โ€” don't warn when a string or character literal is followed by a ud-suffix that does not begin with an underscore ๐Ÿ™ˆ. As a conforming extension, GCC treats such suffixes as separate preprocessing tokens, so that it stays backwards compatible 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);
                   }

so like, in this exact 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. bestie, that's the rule ๐Ÿซถ

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. the compiler is like โ€œI know you won't throw, but the signature says otherwiseโ€ ๐Ÿ˜ญ
  • -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. fr fr, ABI be like that sometimes.

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 (C++ and Objective-C++ only) โ€” Warn when the destination of a call to a raw memory function such as "memset" or "memcpy" is an object of class type, and when writing into such an object might bypass the class 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. 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. do NOT be out here memset-ing your std::string, bestie ๐Ÿ’€
                   std::string str = "abc";
                   memset (&str, 0, sizeof str);

The -Wclass-memaccess option is enabled by -Wall. 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 (C++ and Objective-C++ only) โ€” Warn when a class has virtual functions and an accessible non-virtual destructor itself or in an accessible polymorphic base class, in which case it is possible but unsafe to delete an instance of a derived class through a pointer to the class itself or base class. This warning is automatically enabled if -Weffc++ is specified. The -Wdelete-non-virtual-dtor option (enabled by -Wall) should be preferred because it warns about the unsafe cases without false positives. virtual destructors are the moment, periodt.
  • -Wregister (C++ and Objective-C++ only) โ€” Warn on uses of the "register" storage class specifier, except when it is part of the GNU Explicit Register Variables extension. The use of the "register" keyword as storage class specifier has been deprecated in C++11 and removed in C++17. Enabled by default with -std=c++17. rip register, you were iconic in C but C++ said bye ๐Ÿ™ˆ
  • -Wreorder (C++ and Objective-C++ only) โ€” Warn 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. the compiler said โ€œI got you, but I'm telling youโ€ ๐Ÿ’…

  • -Wno-pessimizing-move (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. so like, the move is giving anti-optimization energy ๐Ÿ˜ญ
                   struct T {
                   ...
                   };
                   T fn()
                   {
                     T t;
                     ...
                     return std::move (t);
                   }

But in this example, the "std::move" call prevents copy elision.

This warning is enabled by -Wall.

  • -Wno-redundant-move (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 (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.

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.

This warning is enabled by -Wall.

  • -Wredundant-tags (C++ and Objective-C++ only) โ€” Warn 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
  • -Wno-subobject-linkage (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. anonymous namespace said โ€œlet me fix that for youโ€ โœจ
  • -Weffc++ (C++ and Objective-C++ only) โ€” Warn 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. ngl, Effective C++ is lowkey the blueprint ๐Ÿ’…

  • -Wno-exceptions (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 out here playing hide and seek ๐Ÿ˜ญ
  • -Wstrict-null-sentinel (C++ and Objective-C++ only) โ€” Warn 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. portability said โ€œnot on my watchโ€ ๐Ÿซถ
  • -Wno-non-template-friend (C++ and Objective-C++ only) โ€” Okay bestie, this one turns off warnings when you declare non-template friend functions inside a template. Back in the dinosaur age of GCC (before the ISO standard was a thing), something like friend int foo(int) โ€” where the friend name is an unqualified-id โ€” could be seen as a specific specialization of a template function. The warning exists to catch compatibility drama, and it's enabled by default. So if you're not about that warning life, use this flag. ๐Ÿ’…
  • -Wold-style-cast (C++ and Objective-C++ only) โ€” This one yells at you if you use an old-style C cast to a non-void type in C++. Like, no bestie, the new-style casts โ€” dynamic_cast, static_cast, reinterpret_cast, and const_cast โ€” are way less vulnerable to unintended effects and are so much easier to search for. It's giving safety. โœจ
  • -Woverloaded-virtual, -Woverloaded-virtual=n (C++ and Objective-C++ only) โ€” Warns when a function declaration hides virtual functions from a base class. Example time:
struct A {
  virtual void f();
};

struct B: public A {
  void f(int); // does not override
};

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

B* b;
b->f();

just fails to compile. Oops. If the different signatures aren't an accident, the simplest fix is to add a using-declaration to the derived class to un-hide the base function, like adding using A::f; to B.

Now the optional level suffix controls what happens when all the declarations in the derived class override virtual functions in the base class, even if not all base functions are overridden:

struct C {
  virtual void f();
  virtual void f(int);
};

struct D: public C {
  void f(int); // does override
};

This pattern is less likely to be a mistake; if D is only used virtually, the user might have decided the base class semantics for some overloads are fine. At level 1, this case doesn't warn; at level 2, it does. -Woverloaded-virtual by itself selects level 2. Level 1 is included in -Wall. So yeah, pick your level. ๐ŸŽ€

  • -Wno-pmf-conversions (C++ and Objective-C++ only) โ€” Disables the diagnostic for converting a bound pointer to member function to a plain pointer. So if you're doing that, this flag says "I got it, chill." ๐Ÿ’…
  • -Wsign-promo (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. So respect the standard, bestie. โญ
  • -Wtemplates (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 you can still use the STL. You may also instantiate or specialize templates. So it's not a total lockdown. ๐Ÿฆ‹
  • -Wmismatched-new-delete (C++ and Objective-C++ only) โ€” Warns for mismatches between calls to operator new or operator delete and the corresponding call to the allocation or deallocation function. This includes invocations of C++ operator delete with pointers returned from either mismatched forms of operator new, or from other functions that allocate objects for which the operator delete isn't a suitable deallocator, as well as calls to other deallocation functions with pointers returned from operator new for which the deallocation function isn't suitable.

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

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

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

The related option -Wmismatched-dealloc diagnoses mismatches involving allocation and deallocation functions other than operator new and operator delete. -Wmismatched-new-delete is included in -Wall. ๐Ÿ”ฅ

  • -Wmismatched-tags (C++ and Objective-C++ only) โ€” Warns for declarations of structs, classes, and class templates and their specializations with a class-key that does not match either the definition or the first declaration if no definition is provided. For example, the declaration of struct Object in the argument list of draw triggers the warning. To avoid it, either remove the redundant class-key struct or replace it with class to match its definition.
class Object {
public:
  virtual ~Object () = 0;
};
void draw (struct Object*);

It is not wrong to declare a class with the class-key struct as the example above shows. The -Wmismatched-tags option is intended to help achieve a consistent style of class declarations. In code that is intended to be portable to Windows-based compilers the warning helps prevent unresolved references due to the difference in the mangling of symbols declared with different class-keys. The option can be used either on its own or in conjunction with -Wredundant-tags. Consistency is key โœจ

  • -Wmultiple-inheritance (C++ and Objective-C++ only) โ€” Warns when a class is defined with multiple direct base classes. Some coding rules disallow multiple inheritance, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also define classes that indirectly use multiple inheritance. So it's a vibe check, not a ban. ๐ŸŒธ
  • -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 one can still use the STL. One may also define classes that indirectly use virtual inheritance. Same energy as the last one. ๐Ÿ’œ
  • -Wno-virtual-move-assign โ€” Suppresses warnings about inheriting from a virtual base with a non-trivial C++11 move assignment operator. This is dangerous because if the virtual base is reachable along more than one path, it is 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, this warning can be disabled. So only turn it off if you really know what you're doing. ๐Ÿ˜ญ
  • -Wnamespaces โ€” Warns when a namespace definition is opened. Some coding rules disallow namespaces, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also use using directives and qualified names. So you can still have your namespaces, just not new ones. ๐Ÿซถ
  • -Wno-terminate (C++ and Objective-C++ only) โ€” Disables the warning about a throw-expression that will immediately result in a call to terminate. So if you're throwing and you know it's gonna terminate, this shuts up the warning. Periodt. ๐Ÿ’…
  • -Wno-vexing-parse (C++ and Objective-C++ only) โ€” Warns about the most vexing parse syntactic ambiguity. This warns about the cases when 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 how to deal with such an ambiguity; e.g., it can suggest removing the parentheses or using braces instead. This warning is enabled by default. So it's always watching. ๐Ÿ‘€

  • -Wno-class-conversion (C++ and Objective-C++ only) โ€” Do not warn when a conversion function converts an object to the same type, to a base class of that type, or to void; such a conversion function will never be called. So if you have a useless conversion function, this flag lets you keep it without the warning. No judgement. ๐Ÿ˜Œ
  • -Wvolatile (C++ and Objective-C++ only) โ€” Warns about deprecated uses of the volatile qualifier. This includes postfix and prefix ++ and -- expressions of volatile-qualified types, using simple assignments where the left operand is a volatile-qualified non-class type for their value, compound assignments where the left operand is a volatile-qualified non-class type, volatile-qualified function return type, volatile-qualified parameter type, and structured bindings of a volatile-qualified type. This usage was deprecated in C++20. Enabled by default with -std=c++20. So yeah, volatile is a little problematic now. โšก
  • -Wzero-as-null-pointer-constant (C++ and Objective-C++ only) โ€” Warns when a literal 0 is used as null pointer constant. This can be useful to facilitate the conversion to nullptr in C++11. So you can be modern and cute. Slay ๐Ÿ‘‘
  • -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. So alignment matters, bestie. ๐Ÿ“
  • -Wno-placement-new, -Wplacement-new=n โ€” Warns about placement new expressions with undefined behavior, such as constructing an object in a buffer that is 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];

This warning is enabled by default.

  • -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 โ€” okay so at this level, bestie, you get everything level 1 catches, plus a lil extra: it throws a diagnostic at placement new expressions that build an object inside the last member of a struct when that member's type is an array of exactly one element, and its size is smaller than the size of the object you're constructing. So yeah, the example right above would totally get flagged. But check this out โ€” the construct below leans on the flexible member array extension to dodge the warning at level 2:
        struct S { int n, a[]; };
        S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]);
        new (s->a)int [32]();
  • -Wcatch-value
  • -Wcatch-value=n (C++ and Objective-C++ only) โ€” this one yells at catch handlers that don't catch by reference. With -Wcatch-value=1 (that's -Wcatch-value for short, slay) it warns about polymorphic class types getting caught by value. With -Wcatch-value=2 it's all class types caught by value. With -Wcatch-value=3 it's literally every type that isn't caught by reference. And -Wcatch-value comes enabled by -Wall ๐Ÿ’….
  • -Wconditionally-supported (C++ and Objective-C++ only) โ€” warns for conditionally-supported constructs (C++11 [intro.defs]).
  • -Wno-delete-incomplete (C++ and Objective-C++ only) โ€” do not warn when you delete a pointer to an incomplete type, which, oof, may cause undefined behavior at runtime. This warning is enabled by default, so this flag is the "stop telling me" button.
  • -Wextra-semi (C++, Objective-C++ only) โ€” warns about redundant semicolons after in-class function definitions. Yes queen, extra semis get called out.
  • -Wno-inaccessible-base (C++, Objective-C++ only) โ€” controls warnings when a base class is inaccessible inside a class derived from it, because of ambiguity. The warning is enabled by default. But heads up bestie: the warning for ambiguous virtual bases is enabled by the -Wextra option instead.
                struct A { int a; };

                struct B : A { };

                struct C : B, A { };
  • -Wno-inherited-variadic-ctor โ€” suppresses warnings about using C++11 inheriting constructors when the base class being inherited from has a C variadic constructor. This warning is on by default because โ€” plot twist โ€” the ellipsis is not inherited.
  • -Wno-invalid-offsetof (C++ and Objective-C++ only) โ€” suppresses warnings from applying the offsetof macro to a non-POD type. Per the 2014 ISO C++ standard, applying offsetof to a non-standard-layout type is undefined. But in existing C++ implementations, offsetof usually gives you something meaningful anyway. So this flag is for the girlies who know they're writing nonportable code and have deliberately chosen to ignore the warning about it. The restrictions on offsetof may get relaxed in a future version of the C++ standard, so stay tuned ig.
  • -Wsized-deallocation (C++ and Objective-C++ only) โ€” warns about a definition of an unsized deallocation function
        void operator delete (void *) noexcept;
        void operator delete[] (void *) noexcept;

without a definition of the corresponding sized deallocation function

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

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

  • -Wsuggest-final-types โ€” warns about types with virtual methods where your code quality would be better if the type were declared with the C++11 final specifier, or, if possible, declared in an anonymous namespace. Why do we care? Because it lets GCC more aggressively devirtualize the polymorphic calls, and that's the dream ๐Ÿ’–. This warning hits harder with link-time optimization, where the info about the class hierarchy graph is more complete.
  • -Wsuggest-final-methods โ€” warns about virtual methods where code quality would improve if the method were declared with the C++11 final specifier, or, if possible, its type were declared in an anonymous namespace or with the final specifier. Same deal: more effective with link-time optimization, where the class-hierarchy-graph tea is more complete. And the rec is to first consider the suggestions from -Wsuggest-final-types and then rebuild with the new annotations. Order matters, bestie.
  • -Wsuggest-override โ€” warns about overriding virtual functions that aren't marked with the override keyword. Just say override, it's free.
  • -Wuse-after-free
  • -Wuse-after-free=n โ€” warns about uses of pointers to dynamically allocated objects that have been rendered indeterminate by a call to a deallocation function. This warning is enabled at all optimization levels, but ngl it may give you different results with optimization than without.
    • -Wuse-after-free=1 โ€” at level 1 the warning tries to diagnose only unconditional uses of pointers made indeterminate by a deallocation call or a successful call to realloc, regardless of whether the call actually reallocated the memory or not. This includes double-free calls plus uses in arithmetic and relational expressions. And even though it's undefined, uses of indeterminate pointers in equality (or inequality) expressions are not diagnosed at this level.
    • -Wuse-after-free=2 โ€” at level 2, on top of the unconditional uses, the warning also diagnoses conditional uses of pointers made indeterminate by a deallocation call. As at level 2, uses in equality (or inequality) expressions are not diagnosed. For example, that second free call in the function below gets diagnosed at this level:
        struct A { int refcount; void *data; };

        void release (struct A *p)
        {
          int refcount = --p->refcount;
          free (p);
          if (refcount == 0)
            free (p->data);   // warning: p may be used after free
        }
  • -Wuse-after-free=3 โ€” at level 3, the warning also diagnoses uses of indeterminate pointers in equality expressions. Like, all uses of indeterminate pointers are undefined, full stop, but equality tests sometimes show up after calls to realloc as an attempt to figure out whether the call relocated the object to a different address. They get diagnosed at a separate level so legacy code can gradually transition to safe alternatives. For example, the equality test in this function below is diagnosed at level 3:
        void adjust_pointers (int**, int);

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

To dodge the warning at this level, store offsets into allocated memory instead of pointers. That way you don't need to adjust the stored pointers after reallocation at all. Iconic workaround, honestly.

-Wuse-after-free=2 is included in -Wall.

  • -Wuseless-cast (C++ and Objective-C++ only) โ€” warns when an expression is cast to its own type. But it does not fire when a class object is converted to a non-reference type, because that's a legit way to create a temporary:
        struct S { };
        void g (S&&);
        void f (S&& arg)
        {
          g (S(arg)); // make arg prvalue so that it can bind to S&&
        }
  • -Wno-conversion-null (C++ and Objective-C++ only) โ€” do not warn for conversions between NULL and non-pointer types. -Wconversion-null is enabled by default, so this is your off switch.

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

(NOTE: This manual does not describe the Objective-C and Objective-C++ languages themselves. Just so we're clear bestie, that's not what this is.)

This section is all about the command-line options that are only meaningful for Objective-C and Objective-C++ programs. You can also use most of the language-independent GNU compiler options, so you're not stuck with just these. For example, you might compile a file some_class.m like this:

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

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

Also note: since Objective-C is an extension of the C language, Objective-C compilations may also use options specific to the C front-end (e.g., -Wtraditional). Same energy โ€” Objective-C++ compilations may use C++-specific options (e.g., -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 โ€” uses class-name as the name of the class to instantiate for each literal string specified with the syntax @"...". The default class name is NXConstantString if the GNU runtime is being used, and NSConstantString if the NeXT runtime is being used (see below, iykyk). On Darwin (macOS, MacOS X) platforms, the -fconstant-cfstrings option, if it's also present, overrides the -fconstant-string-class setting and causes @"..." literals to be laid out as constant CoreFoundation strings. And note that -fconstant-cfstrings is an alias for the target-specific -mconstant-cfstrings equivalent.
  • -fgnu-runtime โ€” generates object code 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, including Darwin and Mac OS X. The macro __NEXT_RUNTIME__ is predefined if (and only if) this option is used. No cap.
  • -fno-nil-receivers โ€” assumes that all Objective-C message dispatches ([receiver message:arg]) in this translation unit make sure the receiver is not nil. That assumption lets the runtime use more efficient entry points. Heads up though: this option is only available in conjunction with the NeXT runtime and ABI version 0 or 1.
  • -fobjc-abi-version=n โ€” bestie, this one picks version n of the Objective-C ABI for whichever runtime you're on. Lowkey only the NeXT runtime supports it rn. So for NeXT: Version 0 = the traditional (32-bit) ABI, no properties, no other Objective-C 2.0 extras. Version 1 = traditional (32-bit) ABI, but with properties and the other Objective-C 2.0 additions. Version 2 = the modern (64-bit) ABI. And if you just don't say anything? Default is Version 0 on 32-bit target machines, Version 2 on 64-bit target machines. โœจ
  • -fobjc-call-cxx-cdtors โ€” okay so for every Objective-C class, it checks whether any of its instance variables is a C++ object with a non-trivial default constructor. If yeah, it synthesizes a special - (id) .cxx_construct instance method that runs those non-trivial default constructors on those instance variables, in order, and then returns self. Same vibe check for destructors: if any instance variable is a C++ object with a non-trivial destructor, it synthesizes a special - (void) .cxx_destruct method that runs all those 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 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 immediately after a new object instance is allocated; the - (void) .cxx_destruct methods get invoked immediately before the runtime deallocates an object instance. ๐Ÿซถ

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

  • -fobjc-direct-dispatch โ€” allows fast jumps to the message dispatcher. On Darwin this is accomplished via the comm page. ๐Ÿฆ‹
  • -fobjc-exceptions โ€” turns on syntactic support for structured exception handling in Objective-C, kinda like what C++ offers. 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 together 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. This option is 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, it checks for a nil receiver in method invocations before doing the actual 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 this flag is set to. Currently this flag does nothing when the GNU runtime, or an older version of the NeXT runtime ABI, is used.
  • -fobjc-std=objc1 โ€” conform to the language syntax of Objective-C 1.0, the language recognized by GCC 4.0. This only affects the Objective-C additions to the C/C++ language; it does not affect conformance to C/C++ standards, which is controlled by the separate C/C++ dialect option flags. When you use this with the Objective-C or Objective-C++ compiler, any Objective-C syntax not recognized by GCC 4.0 gets rejected. Super useful if you need to make sure your Objective-C code can be compiled with older versions of GCC. ๐Ÿ’–
  • -freplace-objc-classes โ€” emits a special marker instructing ld(1) not to statically link in the resulting object file, and lets 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 may be recompiled and dynamically reloaded while the program is executing, without needing to restart the program itself. Currently, Fix-and-Continue functionality is only available in conjunction with the NeXT runtime on Mac OS X 10.3 and later. ๐Ÿ”ฅ
  • -fzero-link โ€” when compiling for the NeXT runtime, the compiler ordinarily replaces calls to objc_getClass("...") (when the 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 this behavior and causes calls to objc_getClass("...") to be retained. This is 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 within the methods of the class they're declared in. That can lead to shadowing between instance variables and other variables declared either locally inside a class method or globally with the same name. Specifying the -fno-local-ivars flag disables this behavior, thus avoiding variable shadowing issues. ๐Ÿ™ˆ
  • -fivar-visibility=[public|protected|private|package] โ€” sets the default instance variable visibility to the option you pick, so that instance variables declared outside the scope of any access modifier directives default to that specified 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) โ€” don't warn if a property for an Objective-C object has no assign semantics specified.
  • -Wno-protocol (Objective-C and Objective-C++ only) โ€” if a class is declared to implement a protocol, a warning is issued for every method in the protocol that isn't implemented by the class. The default behavior is to issue a warning for every method not explicitly implemented in the class, even if a method implementation is inherited from the superclass. If you use the -Wno-protocol option, then methods inherited from the superclass are considered to be implemented, and no warning is issued for them.
  • -Wobjc-root-class (Objective-C and Objective-C++ only) โ€” warns if a class interface lacks a superclass. Most classes will inherit from NSObject (or Object) for example. When declaring classes intended to be root classes, the warning can be suppressed by marking their interfaces with __attribute__((objc_root_class)).
  • -Wselector (Objective-C and Objective-C++ only) โ€” warns if multiple methods of different types for the same selector are found during compilation. The check happens on the list of methods in the final stage of compilation. Also, a check is performed for each selector appearing in a @selector(...) expression, and a corresponding method for that selector has been found during compilation. Because these checks scan the method table only at the end of compilation, these warnings are not produced if the final stage of compilation isn't reached โ€” for example because an error is found during compilation, or because the -fsyntax-only option is being used.
  • -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 attempting to send a message using this selector to a receiver of type id or Class. When this flag is off (which is the default behavior), the compiler omits such warnings if any differences found are confined to types that share the same size and alignment.
  • -Wundeclared-selector (Objective-C and Objective-C++ only) โ€” warns if a @selector(...) expression referring to an undeclared selector is found. A selector is considered undeclared if no method with that name has been declared before the @selector(...) expression, either explicitly in an @interface or @protocol declaration, or implicitly in an @implementation section. This option always performs its checks as soon as a @selector(...) expression is found, while -Wselector only performs its checks in the final stage of compilation. This also enforces the coding style convention that methods and selectors must be declared before being used. ๐Ÿ‘‘
  • -print-objc-runtime-info โ€” generates a C header describing the largest structure that is passed by value, if any.

๐ŸŽ€ Options to Control Diagnostic Messages Formatting ๐ŸŽ€

Okay so traditionally, diagnostic messages have been formatted irrespective of the output device's aspect (like its width, and so on). You can use the options below to control the formatting algorithm for diagnostic messages โ€” like how many characters per line, how often source location info should be reported. Ngl, some language front ends may not honor these options. ๐Ÿ˜ญ

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

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

  • -fdiagnostics-plain-output โ€” this option requests that diagnostic output look as plain as possible, which may be useful when running dejagnu or other utilities that need to parse diagnostics output and prefer that it remain more stable over time. -fdiagnostics-plain-output is currently equivalent to the following options:
-fno-diagnostics-show-caret -fno-diagnostics-show-line-numbers
-fdiagnostics-color=never -fdiagnostics-urls=never
-fdiagnostics-path-format=separate-events

In the future, if GCC changes the default appearance of its diagnostics, the corresponding option to disable the new behavior will be added to this list. ๐ŸŒธ

  • -fdiagnostics-show-location=once โ€” only meaningful when you're in line-wrapping mode, bestie. It tells the diagnostic messages reporter to emit source location info once: when a message is too long to fit on a single physical line and has to get wrapped, the source location won't get emitted (as prefix) again and again on the subsequent continuation lines. This is the default behavior. ๐Ÿ’…
  • -fdiagnostics-show-location=every-line โ€” also only meaningful in line-wrapping mode. It tells the diagnostic messages reporter to emit the same source location info (as prefix) for the physical lines that result from the process of breaking a message that was too long to fit on a single line. every line gets the full vibe check.
  • -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 those 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. (See 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:fnname=01;32:targs=35

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.
  • fnname= โ€” SGR substring for names of C++ functions.
  • targs= โ€” SGR substring for C++ function template parameter bindings.
  • 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 still 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 tries to detect also a few terminals that are known to not implement the URL feature, and have bugs or at least had bugs in some versions that are still in use, where the URL escapes are likely to misbehave, i.e. print garbage on the screen. ๐Ÿ’€ That list is currently xfce4-terminal, certain known to be buggy gnome-terminal versions, the linux console, and mingw. This check can be skipped with -fdiagnostics-urls=always.

  • -fno-diagnostics-show-option โ€” by default, each diagnostic emitted includes text indicating the command-line option that directly controls the diagnostic (if such an option is known to the diagnostic machinery). Specifying the -fno-diagnostics-show-option flag suppresses that behavior. ๐Ÿ™ˆ
  • -fno-diagnostics-show-caret โ€” by default, each diagnostic emitted includes the original source line and a caret ^ indicating the column. This option suppresses this information. The source line is truncated to n characters, if the -fmessage-length=n option is given. When the output is done to the terminal, the width is limited to the width given by the COLUMNS environment variable or, if not set, to the terminal width.
  • -fno-diagnostics-show-labels โ€” by default, when printing source code (via -fdiagnostics-show-caret), diagnostics can label ranges of source code with pertinent information, such as the types of expressions:
printf ("foo %s bar", long_i + long_j);
             ~^       ~~~~~~~~~~~~~~~
              |              |
              char *         long int

This option suppresses the printing of these labels (in the example above, the vertical bars and the char * and long int text). ๐Ÿ’…

  • -fno-diagnostics-show-cwe โ€” diagnostic messages can optionally have an associated CWE (https://cwe.mitre.org/index.html) identifier. GCC itself only provides such metadata for some of the -fanalyzer diagnostics. GCC plugins may also provide diagnostics with such metadata. By default, if this information is present, it will be printed with the diagnostic. This option suppresses the printing of this metadata. ๐ŸŽ€
  • -fno-diagnostics-show-rules โ€” diagnostic messages can optionally have rules associated with them, such as from a coding standard, or a specification. GCC itself does not do this for any of its diagnostics, but plugins may do so. By default, if this information is present, it will be printed with the diagnostic. This option suppresses the printing of this 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 this left margin. ๐Ÿ“
  • -fdiagnostics-minimum-margin-width=width โ€” this option 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 will be 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 above example, bytes 3 through 20 of line 45 of "test.c" are to be replaced with the given string:

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

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

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 โ€” bestie, when the C++ frontend is out here printing diagnostics about mismatching template types, like this mess:
could not convert 'std::map<int, std::vector<double> >()'
  from 'map<[...],vector<double>>' to 'map<[...],vector<float>>

this flag turns on a tree-like structure showing which bits of the types are common and which bits are lowkey fighting each other, like:

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

and the parts that differ get highlighted with color โ€” "double" and "float" in this case. slay.

  • -fno-elide-type โ€” so by default, when the C++ frontend prints diagnostics about mismatching template types, it prints the common parts as [...] to keep the error message cute and short. example:
could not convert 'std::map<int, std::vector<double> >()'
  from 'map<[...],vector<double>>' to 'map<[...],vector<float>>

but if you specify -fno-elide-type, that behavior gets suppressed, no cap. this flag also affects the output of the -fdiagnostics-show-template-tree flag, so keep that in mind bestie.

  • -fdiagnostics-path-format=KIND โ€” picks how paths of control-flow events get printed for diagnostics that have such a path attached. KIND is none, separate-events, or inline-events, and inline-events is the default.

none means, literally, don't print diagnostic paths at all. nothing. silence. ๐Ÿ’œ

separate-events means 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 print the events "inline" within the source code. this view tries to consolidate the events into runs of sufficiently-close events, printing them as labelled ranges inside the source.

for example, those same events as above might come out like:

  '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 gets shown by grouping the events by stack frame and using indentation to show how the stack frames are nested, pushed, and popped. iconique honestly.

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 one hands you extra info when printing control-flow paths tied to a diagnostic. โœจ

if this option is provided, then the stack depth gets printed for each run of events within -fdiagnostics-path-format=inline-events. and if you provide it with -fdiagnostics-path-format=separate-events, then the stack depth and the function declaration get appended when printing each event.

heads up: this is intended for use by GCC developers and plugin developers when debugging diagnostics that report interprocedural control flow. so it's giving maintainer energy, not everyday-user energy, iykyk.

  • -fno-show-column โ€” don't print column numbers in diagnostics. periodt. this might be necessary if your diagnostics are getting scanned by a program that doesn't understand the column numbers, like dejagnu. ๐Ÿฆ‹
  • -fdiagnostics-column-unit=UNIT โ€” picks the units for the column number. this affects traditional diagnostics (when there's no -fno-show-column), and also JSON format diagnostics if you requested those.

the default UNIT, display, counts the number of display columns each character takes up. this can be bigger than the number of bytes needed to encode the character, in the case of tab characters, or it can be smaller, in the case of multibyte characters. for example, the character "GREEK SMALL LETTER PI (U+03C0)" occupies one display column, and its UTF-8 encoding needs two bytes; the character "SLIGHTLY SMILING FACE (U+1F642)" occupies two display columns, and its UTF-8 encoding needs four bytes. the math is mathing. ๐Ÿ™ˆ

setting UNIT to byte changes the column number to the raw byte count in all cases, exactly as was traditionally output by GCC prior to version 11.1.0.

  • -fdiagnostics-column-origin=ORIGIN โ€” picks the origin for column numbers, aka the column number assigned to the first column. the default value of 1 matches traditional GCC behavior and the GNU style guide. some utilities might perform better with an origin of 0, and honestly any non-negative value may be specified. you do you bestie. ๐Ÿ’…
  • -fdiagnostics-escape-format=FORMAT โ€” when GCC prints the pertinent source lines for a diagnostic, it normally tries to print the source bytes directly. but some diagnostics are about encoding issues in the source file โ€” malformed UTF-8, Unicode normalization drama, that whole vibe โ€” and those diagnostics are flagged so GCC escapes bytes that aren't printable ASCII when printing their pertinent source lines.

this option controls how those bytes get escaped.

the default FORMAT, unicode, displays Unicode characters that aren't printable ASCII in the form <U+XXXX>, and bytes that don't correspond to a Unicode character validly-encoded in UTF-8-encoded get displayed as hexadecimal in the form <XX>.

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

before<U+03C0><BF>after

setting FORMAT to bytes displays all non-printable-ASCII bytes in the form <XX>, which shows off the underlying encoding of non-ASCII Unicode characters. for that same example above, you'd get:

before<CF><80><BF>after
  • -fdiagnostics-format=FORMAT โ€” pick a different format for printing diagnostics. FORMAT is text, sarif-stderr, sarif-file, json, json-stderr, or json-file.

the default is text.

the sarif-stderr and sarif-file formats both emit diagnostics in SARIF Version 2.1.0 format โ€” either to stderr, or to a file named source.sarif, respectively.

the json format is a synonym for json-stderr. the json-stderr and json-file formats are identical apart from where the JSON is emitted to โ€” with the former, the JSON goes to stderr, whereas with json-file it gets written to source.gcc.json. ๐Ÿ“

the emitted JSON consists of a top-level JSON array containing JSON objects representing the diagnostics. the JSON is emitted as one line, with no formatting; the examples below have been formatted for clarity, so don't come for them.

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

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

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

where the "note" is a child of the "warning" ๐Ÿ’– like, literally a nested child, the diagnostics have a whole family-tree thing going on and we respect it.

A diagnostic has a "kind". If this is "warning", then there is an "option" key describing the command-line option controlling the warning. slay, it tells you which flag to blame โœจ

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

  • "display-column" counts display columns, accounting for tabs and multibyte characters. ๐Ÿฆ‹
  • "byte-column" counts raw bytes. ๐Ÿ”ข
  • "column" is equal to one of the previous two, as dictated by the -fdiagnostics-column-unit option.

All three columns are relative to the origin specified by -fdiagnostics-column-origin, which is typically equal to 1 but may be set, for instance, to 0 for compatibility with other utilities that number columns from 0 ๐Ÿ’…. The column origin is recorded in the JSON output in the "column-origin" tag. In the remaining examples below, the extra column number outputs have been omitted for brevity, bestie โ€” we're keeping it cute and short.


For example, this error:

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

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

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

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

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

might be printed in JSON form as:

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

where the fix-it hint suggests replacing the text from "start" up to but not including "next" with "string"'s value ๐Ÿ’ซ. Deletions are expressed via an empty value for "string", insertions by having "start" equal "next". so simple, so elegant, we love to see it โœจ

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

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

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

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


โœจ Options to Request or Suppress Warnings โœจ

Warnings are diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error ๐Ÿ‘€. Like, the code works, but bestieโ€ฆ are we sure?

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

  • -fsyntax-only โ€” Check the code for syntax errors, but don't do anything beyond that. Just the vibe check, no compiling ๐ŸŒธ.
  • -fmax-errors=n โ€” Limits the maximum number of error messages to n, at which point GCC bails out rather than attempting to continue processing the source code. If n is 0 (the default), there is no limit on the number of error messages produced. If -Wfatal-errors is also specified, then -Wfatal-errors takes precedence over this option ๐Ÿ‘‘.
  • -w โ€” Inhibit all warning messages. all of them. gone. silenced. ๐Ÿ™ˆ
  • -Werror โ€” Make all warnings into errors ๐Ÿ”ฅ. Every little warning gets main character energy and becomes a full-on error.
  • -Werror= โ€” bestie, this turns a specific warning into a full-on error. You append the specifier for the warning you're mad at; like -Werror=switch makes the warnings controlled by -Wswitch into errors. And there's a negative form too, for when you want to un--Werror just ONE little warning: -Wno-error=switch makes -Wswitch warnings not be errors, even when -Werror is fully in effect. ๐Ÿ’…

Every controllable warning's message includes the option that controls it. So you can take that exact option and pair it with -Werror= or -Wno-error=. (If you want that option text to stop showing up in the message, hit it with the -fno-diagnostics-show-option flag.)

Note that specifying -Werror=foo automatically implies -Wfoo. However, -Wno-error=foo does not imply anything. Not a thing. Nothing. ๐Ÿซถ
  • -Wfatal-errors โ€” this one makes the compiler just abort compilation on the first error instead of trying to keep going and printing further error messages. It's giving "I've seen enough." ๐Ÿ˜ญ

okay so you can request a whole bunch of specific warnings with options that start with -W, for example -Wimplicit to request warnings on implicit declarations. Every one of these specific warning options also has a negative form starting with -Wno- that turns 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, go look at C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. Additional 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. And the combined effect of positive and negative forms? More specific options have priority over less specific ones, independently of their position in the command-line. For options of the same specificity, the last one takes effect. Options enabled or disabled via pragmas take effect as if they appeared at the end of the command-line. โœจ

When an unrecognized warning option is requested (e.g., -Wunknown-warning), GCC emits a diagnostic stating that the option is not recognized. But if the -Wno- form is used, 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 that an unrecognized option is present. ๐Ÿ™ˆ

The effectiveness of some warnings depends on optimizations also being enabled, ngl. For example -Wsuggest-final-types is more effective with link-time optimization, and some instances of other warnings may not be issued at all unless optimization is enabled. While optimization in general improves the efficacy of control and data flow sensitive warnings, in some cases it may also cause false positives. ๐Ÿ’€

  • -Wpedantic -pedantic โ€” this issues all the warnings demanded by strict ISO C and ISO C++; it rejects all programs that use forbidden extensions, plus 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 any -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 are rejected. periodt.

-Wpedantic does not cause warning messages for use of the alternate keywords whose names begin and end with __. This alternate format can also be used to disable warnings for non-ISO __intN types, i.e. __intN__. Pedantic warnings are also disabled in the expression that follows "__extension__". But like โ€” only system header files should use these escape routes; application programs should avoid them. ๐Ÿšซ

Some users try to use -Wpedantic to check programs for strict ISO C conformance. They soon find that it does not do quite what they want: it finds some non-ISO practices, but not all---only those for which ISO C requires a diagnostic, and some others for which diagnostics have been added. ๐Ÿ˜ญ

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

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

  • -pedantic-errors โ€” gives an error whenever the base standard (see -Wpedantic) requires a diagnostic, in some cases where there is undefined behavior at compile-time, and in some other cases that do not prevent compilation of programs that are valid according to the standard. This is not equivalent to -Werror=pedantic, since there are errors enabled by this option and not enabled by the latter, and vice versa. no cap.
  • -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-compare
-Warray-parameter=2 (C and Objective-C only) -Wbool-compare
-Wbool-operation -Wc++11-compat  -Wc++14-compat -Wcatch-value (C++
and Objective-C++ only) -Wchar-subscripts -Wcomment
-Wdangling-pointer=2 -Wduplicate-decl-specifier (C and Objective-C
only) -Wenum-compare (in C/ObjC; this is on by default in C++)
-Wenum-int-mismatch (C and Objective-C only) -Wformat
-Wformat-overflow -Wformat-truncation -Wint-in-bool-context
-Wimplicit (C and Objective-C only) -Wimplicit-int (C and
Objective-C only) -Wimplicit-function-declaration (C and Objective-C
only) -Winit-self (only for C++) -Wlogical-not-parentheses -Wmain
(only for C/ObjC and unless -ffreestanding) -Wmaybe-uninitialized
-Wmemset-elt-size -Wmemset-transposed-args -Wmisleading-indentation
(only for C/C++) -Wmismatched-dealloc -Wmismatched-new-delete (only
for C/C++) -Wmissing-attributes -Wmissing-braces (only for C/ObjC)
-Wmultistatement-macros -Wnarrowing (only for C++) -Wnonnull
-Wnonnull-compare -Wopenmp-simd -Wparentheses -Wpessimizing-move
(only for C++) -Wpointer-sign -Wrange-loop-construct (only for C++)
-Wreorder -Wrestrict -Wreturn-type -Wself-move (only for C++)
-Wsequence-point -Wsign-compare (only in C++) -Wsizeof-array-div
-Wsizeof-pointer-div -Wsizeof-pointer-memaccess -Wstrict-aliasing
-Wstrict-overflow=1 -Wswitch -Wtautological-compare -Wtrigraphs
-Wuninitialized -Wunknown-pragmas -Wunused-function -Wunused-label
-Wunused-value -Wunused-variable -Wuse-after-free=2 -Wvla-parameter
(C and Objective-C only) -Wvolatile-register-var
-Wzero-length-bounds

Note that some warning flags are not implied by -Wall. Some of them warn about constructions that users generally do not consider questionable, but which occasionally you might wish to check for; others warn about constructions that are necessary or hard to avoid in some cases, and there is 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. ๐Ÿ™ƒ

  • -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.) ๐Ÿ’–
-Wclobbered -Wcast-function-type -Wdangling-reference (C++ only)
-Wdeprecated-copy (C++ only) -Wempty-body -Wenum-conversion (C only)
-Wignored-qualifiers -Wimplicit-fallthrough=3
-Wmissing-field-initializers -Wmissing-parameter-type (C only)
-Wold-style-declaration (C only) -Woverride-init -Wsign-compare (C
only) -Wstring-compare -Wredundant-move (only for C++) -Wtype-limits
-Wuninitialized -Wshift-negative-value (in C++11 to C++17 and in C99
and newer) -Wunused-parameter (only with -Wunused or -Wall)
-Wunused-but-set-parameter (only with -Wunused or -Wall)

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

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

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

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

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

okay so โ€” they genuinely tried to warn you about every single one of these cases, but bestie, realistically? there are probably some cases nobody warns you about, even while G++ is out here generating code that's just... not compatible. ๐Ÿ™ˆ And also sometimes you get a warning even though the code is totally compatible. it's giving chaos.

If the whole "G++ code might not be binary compatible with code from other compilers" thing is keeping you up at night, you should rewrite your code to dodge these warnings. periodt.

Here's the tea on known incompatibilities in -fabi-version=2 (which was the default from GCC 3.4 to 4.9):

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


  • -Wno-changes-meaning (C++ and Objective-C++ only) โ€” so C++ has โœจrulesโœจ: unqualified uses of a name inside a class have to mean the same thing across the entire scope of the class, which means declaring the name after you use it is ill-formed:
struct A;
struct B1 { A a; typedef A A; }; // warning, 'A' changes meaning
struct B2 { A a; struct A { }; }; // error, 'A' changes meaning

By default, the B1 case is only a warning because the two declarations have the same type, while the B2 case is an error. Both diagnostics can be disabled with -Wno-changes-meaning. Alternately, the error case can be reduced to a warning with -Wno-error=changes-meaning or -fpermissive.

Both diagnostics are also suppressed by -fms-extensions. ๐Ÿซถ

  • -Wchar-subscripts โ€” warns 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 if feedback profiles do not match when using the -fprofile-use option. If a source file is changed between compiling with -fprofile-generate and with -fprofile-use, the files with the profile feedback can fail to match the source file and GCC cannot use the profile feedback information. By default, this warning is enabled and is treated as an error. -Wno-coverage-mismatch can be used to disable the warning or -Wno-error=coverage-mismatch can be used to disable the error. Disabling the error for this warning can result in poorly optimized code and is useful only in the case of very minor changes such as bug fixes to an existing code-base. Completely disabling the warning is not recommended. ๐Ÿ˜ญ
  • -Wno-coverage-invalid-line-number โ€” warns in case a function ends earlier than it begins due to an invalid linenum macros. The warning is emitted only with --coverage enabled.

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

  • -Wno-cpp (C, Objective-C, C++, Objective-C++ and Fortran only) โ€” suppresses warning messages emitted by #warning directives. shhh ๐Ÿคซ
  • -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. CPUs with a 32-bit "single-precision" floating-point unit implement float in hardware, but emulate double in software. On such a machine, doing computations using double values is much more expensive because of the overhead required for software emulation. ๐Ÿ’€

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

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

the compiler performs the entire computation with double because the floating-point literal is a double. caught in 4k ๐Ÿซฃ

  • -Wduplicate-decl-specifier (C and Objective-C only) โ€” warns 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 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 ๐ŸŒธ

okay bestie, picture this: GCC reads your little sprintf call and just knows that buffer is not gonna fit the vibe. ๐Ÿ’€ Level 1 is what you get from -Wformat-overflow=1, and it's also what -Wformat switches on for you. It's the conservative, low-drama setting โ€” it only comes for the calls that are most likely to overflow the buffer. No false accusations, we're respectful here.

The assumptions at this level, bestie, write them down:

  • numeric arguments to format directives whose values are unknown? assumed to have the value of 1 โœจ
  • strings of unknown length? assumed to be empty ๐Ÿซถ
  • numeric arguments that are known to be bounded to a subrange of their type, or string arguments whose output is bounded either by their directive's precision or by a finite set of string literals? they take on the value within that range that gives the most bytes on output. worst case, always. icon behavior.

So like, the sprintf call below gets diagnosed because even with both a and b equal to zero, the terminating NUL character ('\0') that the function appends to the destination buffer is gonna be written past its end. ๐Ÿ˜ญ Bumping the buffer size by a single byte is enough to make the warning go away โ€” though ngl it may not be enough to actually stop the 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 level 1 but with main character energy โ€” it also drags calls that might overflow the destination buffer given an argument of sufficient length or magnitude. She's not waiting for proof, she's asking "what if?"

At level 2 the guessing rules change, so pay attention:

  • unknown numeric arguments are assumed to have the minimum representable value for signed types with a precision greater than 1, and the maximum representable value otherwise.
  • unknown string arguments whose length can't be assumed to be bounded โ€” either by the directive's precision, or by a finite set of string literals they may evaluate to, or by the character array they may point to โ€” are assumed to be 1 character long.

At level 2, that example up there gets flagged 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 values those two variables hold, the destination buffer has to be at least 34 bytes. GCC is nice enough to drop the minimum buffer size into an informational note right after the warning. ๐Ÿซถ

Now โ€” instead of just making the buffer bigger, you can also constrain the range of formatted values. The max length of string arguments can be bounded by specifying the precision in the format directive. And when numeric arguments of format directives can be assumed to be bounded by less than the precision of their type, picking an appropriate length modifier for the format specifier shrinks the buffer you need. For example: if a and b up there 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 drops the maximum required buffer size down to 24 bytes. slay.

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, then do not warn about zero-length formats, okay? the C standard literally specifies that zero-length formats are allowed. let them live. โœจ
  • -Wformat-nonliteral โ€” if -Wformat is specified, also warn when the format string isn't a string literal, because then it can't be checked. the one exception: 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. rn it 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);. This can be a whole security hole if that format string came from untrusted input and it contains %n. ๐Ÿ˜ญ (right now this is a subset of what -Wformat-nonliteral warns about, but future warnings may be added to -Wformat-security that aren't included in -Wformat-nonliteral โ€” so watch this space.)
  • -Wformat-signedness โ€” if -Wformat is specified, also warn when the format string wants an unsigned argument and the argument is signed, and vice versa. mismatch behavior, we don't do that here. ๐Ÿ’…

๐Ÿฆ‹ -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 figured out at compile-time, it gets estimated based on heuristics that depend on the level argument and on optimization. Turning optimizations on will in most cases make the warning more accurate โ€” but it can also produce false positives, so like, be aware. ๐Ÿ‘€ Except as noted otherwise, this option uses the same logic as -Wformat-overflow.

Level 1, which you get from plain -Wformat-truncation and from -Wformat-truncation=1, is turned on by -Wformat and uses a conservative approach: 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. y2k said "I lived, bitch" and honestly we should all be so lucky. ๐Ÿ’€
  • -Wnonnull โ€” warn about passing a null pointer for arguments that are marked as requiring a non-null value by the nonnull function attribute. -Wnonnull is included in -Wall and -Wformat, and it can be disabled with the -Wno-nonnull option. ๐Ÿซถ
  • -Wnonnull-compare โ€” warn when you compare an argument marked with the nonnull function attribute against null inside the function. like bestie it literally cannot be null, what are we doing. ๐Ÿ˜ญ -Wnonnull-compare is included in -Wall and it can be disabled with the -Wno-nonnull-compare option.
  • -Wnull-dereference โ€” warn if the compiler detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer. this one's only active when -fdelete-null-pointer-checks is active, which gets enabled by optimizations in most targets. The precision of these warnings depends on the optimization options you used. โš ๏ธ
  • -Winfinite-recursion โ€” warn about infinitely recursive calls. It's effective at all optimization levels, but it needs optimization to detect infinite recursion in calls between two or more functions. -Winfinite-recursion is included in -Wall. Compare it with -Wanalyzer-infinite-recursion, which gives a similar diagnostic but is implemented in a totally different way โ€” as part of -fanalyzer. ๐Ÿ”
  • -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 together with the -Wuninitialized option. For example, GCC warns about i being uninitialized in the snippet below 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. That 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. That warning is enabled by default in C99 and later dialects of C, and also by -Wall. The warning gets turned 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. easy math, love that for us. ๐ŸŽ€

๐Ÿ‘‘ -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;
  }

She does not warn 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 control flow statements such as ifs into account, 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:
    ...
  }

Now, sometimes a switch case fall through is exactly what you want, so GCC gives you an attribute โ€” __attribute__ ((fallthrough)) โ€” that you use alongside a null statement to suppress the warning that would normally pop up: ๐Ÿ‘‡

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

C++17 comes through with a standard way to suppress the -Wimplicit-fallthrough warning using [[fallthrough]]; instead of the GNU attribute. And if you're on C++11 or C++14, you can use [[gnu::fallthrough]];, which is a GNU extension. ๐Ÿซถ Instead of those attributes, you can also just add a fallthrough comment to silence the warning โ€” the whole body of the C or C++ style comment has to match the regular expressions listed below. The option argument n specifies what kind of comments get accepted:

  • -Wimplicit-fallthrough=0 disables the warning altogether.
  • -Wimplicit-fallthrough=1 matches the .* regular expression โ€” any comment at all counts as a fallthrough comment.
  • -Wimplicit-fallthrough=2 โ€” case insensitively matches the ".*falls?[ \t-]*thr(ough|u).*" regular expression. ๐Ÿ’–
  • -Wimplicit-fallthrough=3 โ€” case sensitively matches one of the following regular expressions, bestie:
    • "-fallthrough"
    • "@fallthrough@"
    • "lint -fallthrough[ \t]*"
    • "[ \t.!]*(ELSE,? |INTENTIONAL(LY)? )?FALL(S | |-)?THR(OUGH|U)[ \t.!]*(-[^\n\r]*)?"
    • "[ \t.!]*(Else,? |Intentional(ly)? )?Fall((s | |-)[Tt]|t)hr(ough|u)[ \t.!]*(-[^\n\r]*)?"
    • "[ \t.!]*([Ee]lse,? |[Ii]ntentional(ly)? )?fall(s | |-)?thr(ough|u)[ \t.!]*(-[^\n\r]*)?"
  • -Wimplicit-fallthrough=4 โ€” case sensitively matches one of these regular expressions, slay:
    • "-fallthrough"
    • "@fallthrough@"
    • "lint -fallthrough[ \t]*"
    • "[ \t]*FALLTHR(OUGH|U)[ \t]*"
  • -Wimplicit-fallthrough=5 โ€” this one doesn't recognize any comments as fallthrough comments. Only attributes disable the warning. periodt. ๐Ÿ’…

The comment needs to be followed after optional whitespace and other comments by "case" or "default" keywords, or by a user label that precedes some "case" or "default" label. iykyk ๐ŸŒธ

   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 should be issued. These warnings are enabled by default. ๐Ÿซถ
  • -Wignored-qualifiers (C and C++ only) โ€” warns you if the return type of a function has a type qualifier like "const". For ISO C such a type qualifier has no effect, since the value returned by a function is not an lvalue. For C++, the warning only pops off for scalar types or "void". And heads up: ISO C prohibits qualified "void" return types on function definitions, so those return types always get a warning even without this option.

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

  • -Wno-ignored-attributes (C and C++ only) โ€” this option controls warnings when an attribute is ignored. The way it's different from the -Wattributes option?? It warns whenever the compiler decides to drop an attribute, not that the attribute is unknown or used in a wrong place or whatever. This warning is enabled by default. ๐ŸŽ€
  • -Wmain โ€” warns you if the type of "main" is suspicious. "main" should be a function with external linkage, returning int, taking either zero arguments, two, or three arguments of appropriate types. This warning is enabled by default in C++ and is enabled by either -Wall or -Wpedantic. ๐Ÿ‘‘
  • -Wmisleading-indentation (C and C++ only) โ€” warns when the indentation of the code does not reflect the block structure. Specifically, a warning is issued for "if", "else", "while", and "for" clauses with a guarded statement that doesn't use braces, followed by an unguarded statement with the same indentation. not me getting tricked by whitespace ๐Ÿ˜ญ

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

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

In the case of mixed tabs and spaces, the warning uses the -ftabstop= option to determine if the statements line up (defaulting to 8).

The warning is not issued for code involving multiline preprocessor logic such as the following example:

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

And it's not issued after a "#line" directive, since that typically indicates autogenerated code, and no assumptions can be made about the layout of the file that the directive references. ๐Ÿงš

This warning is enabled by -Wall in C and C++. โœจ

  • -Wmissing-attributes โ€” warns when a declaration of a function is missing one or more attributes that a related function is declared with, where that absence may adversely affect the correctness or efficiency of generated code. For example, the warning is issued for declarations of aliases that use attributes to specify less restrictive requirements than those of their targets. This typically represents a potential optimization opportunity. By contrast, the -Wattribute-alias=2 option controls warnings issued when the alias is more restrictive than the target, which could lead to incorrect code generation. ๐Ÿ™ˆ

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

In C++, the warning is issued when an explicit specialization of a primary template declared with attribute "alloc_align", "alloc_size", "assume_aligned", "format", "format_arg", "malloc", or "nonnull" is declared without it. Attributes "deprecated", "error", and "warning" suppress the warning.. (yes bestie, that double period is fr fr in the source, iconic)

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

-Wmissing-attributes is enabled by -Wall. ๐Ÿ’…

For example, since the declaration of the primary function template below makes use of both attribute "malloc" and "alloc_size", the declaration of the explicit specialization of the template is diagnosed because it'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 following example, the initializer for "a" is not fully bracketed, but that for "b" is fully bracketed:
           int a[2][2] = { 0, 1, 2, 3 };
           int b[2][2] = { { 0, 1 }, { 2, 3 } };

This warning is enabled by -Wall. ๐ŸŒธ

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

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

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

In C++, the related option -Wmismatched-new-delete diagnoses mismatches involving either "operator new" or "operator delete". ๐Ÿ‘‘

Option -Wmismatched-dealloc is included in -Wall. โœจ

  • -Wmultistatement-macros โ€” warns about unsafe multiple statement macros that appear to be guarded by a clause such as "if", "else", "for", "switch", or "while", in which only the first statement is actually guarded after the macro is expanded. the betrayal ๐Ÿ˜ญ

For example:

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

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

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

This warning is enabled by -Wall in C and C++. ๐ŸŽ€

  • -Wparentheses โ€” warns if parentheses are omitted in certain contexts, 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. the way we've all been there ๐Ÿ’€

Also warns if a comparison like "x<=y<=z" appears; this is equivalent to "(x<=y ? 1 : 0) <= z", which is a different interpretation from that of ordinary mathematical notation. sneaky!!

Also warns for dangerous uses of the GNU extension to "?:" with omitted middle operand. When the condition in the "?": operator is a boolean expression, the omitted value is always 1. Often programmers expect it to be a value computed inside the conditional expression instead. ๐Ÿ™ˆ

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

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

๐Ÿ‘€ bestie that one is on by -Wall, so enjoy.


-Wno-self-move (C++ and Objective-C++ only)

Yells at you when a value gets moved to itself via std::move. And honestly? A std::move like that usually does absolutely nothing. ๐Ÿ’€

struct T {
...
};
void fn()
{
  T t;
  ...
  t = std::move (t);
}

Enabled by -Wall. โœจ


-Wsequence-point

Warns about code that might have undefined semantics because it breaks the sequence point rules from the C and C++ standards. Not being dramatic โ€” this is the real deal. ๐Ÿ˜ญ

So, the C and C++ standards define the order that expressions get evaluated in terms of sequence points. A sequence point is basically a partial ordering between chunks of execution: the stuff evaluated before it, and the stuff evaluated after it. These happen:

  • after a full expression gets evaluated (a full expression = one that isn't part of a bigger expression)
  • after the first operand of &&, ||, ? : or , (the comma operator) is evaluated
  • before a function gets called (but after its arguments and the expression naming the called function are evaluated)
  • and in certain other places โœจ

Other than what the sequence point rules say, the order of evaluation of subexpressions is not specified. And all these rules only describe a partial order, not a total order โ€” because like, if two functions get called inside one expression with no sequence point between them, the order they get called in isn't specified either. However, the standards committee has ruled that function calls do not overlap.

It's also not specified when modifications to object values actually take effect in between sequence points. Programs that depend on that have undefined behavior, because the C and C++ standards say this, word for word:

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

And if your program breaks those rules, the results on any particular implementation are entirely unpredictable. So likeโ€ฆ good luck bestie ๐Ÿ’€

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's been found pretty effective at catching this sort of problem in programs. ๐ŸŽ€

Heads up: the C++17 standard will define the order of evaluation of operands in more cases โ€” specifically it requires the right-hand side of an assignment to be evaluated before the left-hand side, so those examples above are no longer undefined there. But this option will still warn about them, to help people avoid writing code that's undefined in C and earlier revisions of C++. ๐Ÿ‘‘

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

This warning is enabled by -Wall for C and C++. ๐ŸŒˆ


-Wno-return-local-addr

Do not warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns. (Iconic footgun behavior, honestly. ๐Ÿซถ)


-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 isn't void (and fyi, 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's type is also void. As a GNU extension, that latter case is accepted without a warning unless -Wpedantic is used. And 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? That's 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. no cap.

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


-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's possible to suppress this warning by casting the controlling expression to a type other than bool. Like:

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

Hot tip: -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 the __sync_fetch_and_nand and __sync_nand_and_fetch built-in functions are used. These functions changed semantics in GCC 4.4. ๐Ÿ˜ญ


-Wtrivial-auto-var-init

Warns when -ftrivial-auto-var-init cannot initialize the automatic variable. A common situation is an automatic variable that's declared between the controlling expression and the first case label of a switch statement. ๐Ÿซถ


-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 โ€” bestie, this one yells at you whenever a constant static variable is justโ€ฆ sitting there unused, aside from its declaration. Like it's in the group chat but never says anything. ๐Ÿ˜ญ

-Wunused-const-variable=1 is turned on by -Wunused-variable for C, but not for C++. Why? Because in C that declares variable storage, but in C++ it's not an error at all โ€” const variables literally take the place of #defines there. โœจ

Wanna make it shut up? Use the unused attribute. ๐Ÿ’…

  • -Wunused-const-variable=1 โ€” this is the warning level that -Wunused-variable enables for C. It only warns about unused static const variables defined in the main compilation unit โ€” not the static const ones declared in any header you included. ๐Ÿ™ˆ
  • -Wunused-const-variable=2 โ€” this level also warns about unused constant static variables in headers (system headers excluded, don't worry ๐Ÿซถ). This is the warning level of plain -Wunused-const-variable, and you have to explicitly ask for it, because in C++ it isn't an error and in C it might be way harder to clean up every single header you pulled in. ๐Ÿ’€
  • -Wunused-value โ€” warns whenever a statement computes a result that's explicitly not used. To silence it, cast the unused expression to void. โœ…

This covers an expression-statement, or the left-hand side of a comma expression that has no side effects. Example time: an expression like x[i,j] triggers a warning, while x[(void)i,j] does not. Slay. ๐ŸŽ€

This warning is enabled by -Wall.

  • -Wunused โ€” all the above -Wunused options combined. ๐Ÿ‘‘

Okay so, to get a warning about an unused function parameter, you must either specify -Wextra -Wunused (heads up: -Wall implies -Wunused), or separately specify -Wunused-parameter. Pick your fighter. ๐Ÿ’–

  • -Wuninitialized โ€” warns if an object with automatic or allocated storage duration gets used without having been initialized. In C++, it also warns if a non-static reference or a non-static const member shows up in a class with no constructors. ๐Ÿšจ

Bonus: passing a pointer (or in C++, a reference) to an uninitialized object into a const-qualified argument of a built-in function known to read that object is also diagnosed by this warning. (-Wmaybe-uninitialized is what gets issued for ordinary functions.)

Wanna also get warned about code that uses the uninitialized value of the variable in its own initializer? That's a whole different vibe โ€” use the -Winit-self option. ๐Ÿ˜Œ

These warnings happen for individual uninitialized elements of structure, union or array variables, and for variables that are uninitialized as a whole. They do not happen for variables or elements declared volatile. And because these warnings depend on optimization, the exact variables or elements you get warned about depend on the precise optimization options and the version of GCC you're running. Not me being vague, that's just how it is. ๐Ÿคท

Also note: there may be no warning about a variable that's only used to compute a value that itself is never used, because such computations may be deleted by data flow analysis before the warnings are printed. Gone. Poof. ๐Ÿ’จ

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

        struct A {
          int a;
          int b;
          A() : a(b) { }
        };
  • -Wno-invalid-memory-model โ€” this option controls warnings for invocations of __atomic Builtins, __sync Builtins, and the C11 atomic generic functions when the memory consistency argument is either invalid for the operation or outside the range of values of the memory_order enumeration. ๐Ÿง 

For example, since the __atomic_store and __atomic_store_n built-ins are only defined for the relaxed, release, and sequentially consistent memory orders, the following code is diagnosed:

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

-Winvalid-memory-model is enabled by default. โญ

  • -Wmaybe-uninitialized โ€” for an object with automatic or allocated storage duration: if there exists a path from function entry to a use of the object where it is initialized, but there also exist other paths where the object is not initialized, the compiler warns if it can't prove those uninitialized paths never get executed at run time. ๐Ÿซฃ

Also, passing a pointer (or in C++, a reference) to an uninitialized object into a const-qualified function argument is diagnosed by this warning too. (-Wuninitialized is what gets issued for built-in functions known to read the object.) Annotate the function with the attribute access (none) to say "hey, this argument isn't used to access the object" and dodge the warning. ๐ŸŒธ

These warnings are only even possible in optimizing compilation, because otherwise GCC just isn't keeping track of the state of your variables. No tracking, no warning.

They're optional because GCC may not be able to tell when the code is actually correct even though it looks like it has an error. Here's one example of how that goes down:

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

If the value of y is always 1, 2 or 3, then x is always initialized โ€” but GCC doesn't know that. ๐Ÿ’€ To suppress the warning you need to provide a default case with assert(0) or similar code.

This option also warns when a non-volatile automatic variable might be changed by a call to longjmp. The compiler only sees the calls to setjmp. It cannot know where longjmp will be called โ€” in fact, a signal handler could call it at any point in the code. So you may get a warning even when there's genuinely no problem, because longjmp can't actually be called at the place that would cause the problem. iconic but annoying, honestly. ๐Ÿ˜ญ

Some spurious warnings can be avoided if you declare all the functions you use that never return as noreturn. ๐Ÿ”ฅ

This warning is enabled by -Wall or -Wextra.

  • -Wunknown-pragmas โ€” warns when a #pragma directive shows up that GCC doesn't understand. If this command-line option is used, warnings are even issued for unknown pragmas in system header files. That is not the case if the warnings are only enabled by the -Wall command-line option. ๐Ÿ‘€
  • -Wno-pragmas โ€” do not warn about misuses of pragmas, like incorrect parameters, invalid syntax, or conflicts between pragmas. See also -Wunknown-pragmas. ๐ŸŽ€
  • -Wno-prio-ctor-dtor โ€” do not warn if a priority from 0 to 100 is used for a constructor or destructor. Here's the tea: the constructor and destructor attributes let you assign a priority to control the order of execution before main is called or after it returns. The priority values must be greater than 100, because the compiler reserves priority values between 0--100 for the implementation. ๐Ÿšซ
  • -Wstrict-aliasing โ€” 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 does not catch all cases, but it does try to catch the more common pitfalls. It's included in -Wall. It is equivalent to -Wstrict-aliasing=3. โœจ
  • -Wstrict-aliasing=n โ€” same deal, only active when -fstrict-aliasing is active, and it warns about code that might break the strict aliasing rules the compiler uses for optimization. Higher levels = higher accuracy (fewer false positives). Higher levels also = more effort, similar to the way -O works. And again: -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. ๐Ÿ‘‘
  • -Wstrict-overflow
  • -Wstrict-overflow=n โ€” 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. Important caveat bestie: it does not warn about all cases where the code might overflow โ€” it only warns about cases where the compiler 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 actually happens. So this warning can easily give a false positive: a warning about code that isn't actually a problem. To help focus on important issues, 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 โ€” warns 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 clocks the other cases where a comparison gets simplified into a constant. Like abs (x) >= 0 bestie. And the tea here is that this one can only be simplified when signed integer overflow is undefined, bc abs (INT_MIN) overflows to INT_MIN, which is literally less than zero. And psst: -Wstrict-overflow with no level at all? Same as -Wstrict-overflow=2. Slay.
  • -Wstrict-overflow=3 โ€” okay so on top of everything above, this one also warns about other cases where a comparison is simplified. Example era: x + 1 > 1 gets simplified to x > 0.
  • -Wstrict-overflow=4 โ€” and now we're warning about other simplifications that the cases above didn't cover. Example: (x * 10) / 5 simplifies to x * 2.
  • -Wstrict-overflow=5 โ€” the final boss level. This also warns when the compiler shrinks the magnitude of a constant involved in a comparison. Like x + 2 > y gets simplified to x + 1 >= y. Fair warning though: this is ONLY reported at the highest warning level, because this simplification applies to a ton of comparisons, so this level hands you a very large number of false positives. It's giving spam. ๐Ÿ”ฅ

  • -Wstring-compare โ€” warns on calls to strcmp and strncmp whose result is determined to be either zero or non-zero in tests for that equality, because one argument's length is greater than the size of the array the other argument lives in (or, for strncmp, the bound). Basically these calls might be mistakes bestie. Like, check the glow-up on this:
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");
}

The strcmp call above is diagnosed bc its result is necessarily non-zero no matter what's chilling in the array a.

-Wstring-compare is enabled by -Wextra. ๐Ÿ’…

  • -Wno-stringop-overflow
  • -Wstringop-overflow
  • -Wstringop-overflow=type โ€” these warn for calls to string manipulation functions like memcpy and strcpy that are determined to 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: that argument only means something for functions that operate on character arrays, NOT for raw memory functions like memcpy, which always use Object Size type-0. This option also warns for calls that specify a size way beyond the largest possible object, or at most SIZE_MAX / 2 bytes. It produces the best results with optimization on, but can still catch a small subset of simple buffer overflows even without optimization, in calls to GCC built-ins like __builtin_memcpy that correspond to the standard functions. Either way, it only warns about a subset of buffer overflows that the corresponding overflow-checking built-ins detect. For example, it drops a warning on the strcpy call below because it copies at least 5 characters (that's the string blue including 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
}

Also, -Wstringop-overflow=2 is enabled by default. ๐Ÿ‘‘

  • -Wstringop-overflow
  • -Wstringop-overflow=1 โ€” this one 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 actually known. When the destination might be one of several objects, it assumes it's the largest one of them. And on Linux systems, when optimization is enabled at this setting, it warns for the same code as when the _FORTIFY_SOURCE macro is defined to a non-zero value.
  • -Wstringop-overflow=2 โ€” this one uses type-one Object Size Checking to determine the sizes of destination objects. Here it warns about overflows when writing to members of the largest complete objects whose exact size is known. But ngl, it does not warn about excessive writes to those same members of unknown objects referenced by pointers, since they might point to arrays with an unknown number of elements. This is the default setting of the option. โœจ
  • -Wstringop-overflow=3 โ€” uses type-two Object Size Checking to figure out 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 yes it may result in warnings for safe code. ๐Ÿ™ˆ
  • -Wstringop-overflow=4 โ€” uses type-three Object Size Checking to figure out the sizes of destination objects. Here 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 issue a warning. Just like -Wstringop-overflow=3, this setting of the option may result in warnings for benign code.
  • -Wno-stringop-overread โ€” warns for calls to string manipulation functions like memchr, or strcpy, that are determined to read past the end of the source sequence. Lowkey chaotic.

Also: -Wstringop-overread is enabled by default.

  • -Wno-stringop-truncation โ€” do not warn for calls to bounded string manipulation functions like strncat, strncpy, and stpncpy that may either truncate the copied string or leave the destination unchanged.

So in this next example, the call to strncat specifies a bound that's less than the length of the source string. As a result the copy of the source gets truncated and therefore the call is diagnosed. To dodge the warning, use bufsize - strlen (buf) - 1) as the bound.

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

And here's another one: the strncpy call below copies to d just the characters before the terminating NUL, without appending the NUL at the end. Assuming the result of strncpy is necessarily a NUL-terminated string is a super common mistake, so the call is diagnosed. To avoid the warning when the result isn't expected to be NUL-terminated, call memcpy instead, bestie.

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

And in this example, the call to strncpy specifies the size of the destination buffer as the bound. If the length of the source string is equal to or greater than that size, the result of the copy won't be NUL-terminated. So yep, this call is diagnosed too. To avoid the warning, specify sizeof buf - 1 as the bound and set the last element of the buffer to NUL.

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

Now, in situations where a character array is intended to store a sequence of bytes with no terminating NUL, you can annotate that array with the nonstring attribute to avoid this warning. But real talk: such arrays are NOT suitable arguments to functions that expect NUL-terminated strings. To help catch accidental misuses of these arrays, GCC issues warnings unless it can prove the use is safe.

  • -Wstrict-flex-arrays โ€” warns about improper usages of flexible array members, according to the level of the strict_flex_array (level) attribute attached to the trailing array field of a structure โ€” if that's available โ€” otherwise according to the level of the option -fstrict-flex-arrays=level.

This option is effective only when level is bigger than 0. Otherwise it gets ignored, with a warning. ๐Ÿ’€

  • when level=1, warnings are issued for a trailing array reference of a structure that has 2 or more elements, if the trailing array is referenced as a flexible array member.
  • when level=2, in addition to level=1, extra warnings are issued for a trailing one-element array reference of a structure, if the array is referenced as a flexible array member.
  • when level=3, in addition to level=2, extra warnings are issued for a trailing zero-length array reference of a structure, if the array is referenced as a flexible array member.
  • -Wsuggest-attribute=[pure|const|noreturn|format|cold|malloc] โ€” warns for cases where adding an attribute might be beneficial. The attributes we currently support are listed below. ๐Ÿซถ
    • -Wsuggest-attribute=pure
    • -Wsuggest-attribute=const
    • -Wsuggest-attribute=noreturn
    • -Wmissing-noreturn
    • -Wsuggest-attribute=malloc โ€” warns about functions that might be candidates for the attributes pure, const, noreturn, or malloc. The compiler only warns for functions visible in other compilation units, or (for pure and const) when it can't prove the function returns normally. A function returns normally if it doesn't contain an infinite loop or return abnormally by throwing, calling abort, or trapping. This analysis needs the option -fipa-pure-const, which is enabled by default at -O and higher. And higher optimization levels improve the accuracy of the analysis. ๐Ÿ“ˆ
  • -Wsuggest-attribute=format, -Wmissing-format-attribute โ€” ok so this one ๐Ÿซถ warns you about function pointers that might be candidates for format attributes. And bestie, hear me: candidates, like, possible ones, not absolute ones. GCC is guessing here, not declaring. The guess is that function pointers carrying format attributes which get used in assignment, initialization, parameter passing, or return statements should have a matching format attribute in the resulting type. Translation: the left-hand side of the assignment or initialization, the type of the parameter variable, or the return type of the containing function respectively should also have a format attribute โ€” otherwise, warning. ๐Ÿ’…

GCC also warns about function definitions that might be candidates for format attributes. Again โ€” only possible candidates, don't come for GCC. The guess is that format attributes might be appropriate for any function that calls a function like vprintf or vscanf, but that might not always be the case, and some functions where format attributes would be appropriate may just not get detected. It's giving โœจvibes-based static analysisโœจ and honestly? Relatable.

  • -Wsuggest-attribute=cold โ€” warns about functions that might be candidates for the cold attribute. This is based on static detection and generally only warns about functions which always lead to a call to another cold function โ€” think wrappers of C++ throw, or fatal error reporting functions leading to abort. So basically: "this function is doomsday-coded, mark it ๐Ÿ’€".
  • -Walloc-zero โ€” warns about calls to allocation functions decorated with attribute alloc_size that specify zero bytes, including calls to the built-in forms of aligned_alloc, alloca, calloc, malloc, and realloc. Because the behavior of these functions when called with a zero size differs among implementations (and in the case of realloc it's been deprecated ๐Ÿ˜ญ), relying on it may result in subtle portability bugs and should be avoided. Fr fr, don't do it.
  • -Walloc-size-larger-than=byte-size โ€” warns about calls to functions decorated with attribute alloc_size that try to allocate objects larger than the specified number of bytes, or where the result of the size computation in an integer type with infinite precision would exceed the value of PTRDIFF_MAX on the target. -Walloc-size-larger-than=PTRDIFF_MAX is enabled by default. Warnings controlled by this option can be disabled either by specifying a byte-size of SIZE_MAX or more, or by -Wno-alloc-size-larger-than. ๐ŸŽ€
  • -Wno-alloc-size-larger-than โ€” disables the -Walloc-size-larger-than= warnings. The option is equivalent to -Walloc-size-larger-than=SIZE_MAX or larger.
  • -Walloca โ€” this option warns on all uses of alloca in the source. All of them. Every single one. Periodt.
  • -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 limiting its value to at most byte-size. It also warns for calls to alloca where the bound value is unknown. And arguments of non-integer types are considered unbounded even if they appear to be constrained to the expected range. ๐Ÿ™ˆ

For example, a bounded case of alloca could be:

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

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. But if -Walloca-larger-than=500 were passed, the compiler would emit a warning. Caught in 4K. ๐Ÿ”ฅ

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, not because of the bound itself.

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, which causes a larger-than-expected argument to be implicitly cast into the alloca call. Not the plot twist anyone wanted. ๐Ÿ˜ญ

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

-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 โ€” disables the -Walloca-larger-than= warnings. The option is equivalent to -Walloca-larger-than=SIZE_MAX or larger.
  • -Warith-conversion โ€” do warn about implicit conversions from arithmetic operations even when conversion of the operands to the same type cannot change their values. This affects warnings from -Wconversion, -Wfloat-conversion, and -Wsign-conversion.
void f (char c, int i)
{
c = c + i; // warns with -Wconversion
c = c + 1; // only warns with -Warith-conversion
}

See that second line? Only this option catches it. iykyk. ๐Ÿ’…

  • -Warray-bounds, -Warray-bounds=n โ€” warns about out of bounds subscripts or offsets into arrays. This warning is enabled by -Wall. It's more effective when -ftree-vrp is active (the default for -O2 and above) but a subset of instances are issued even without optimization.

By default, the trailing array of a structure will be treated as a flexible array member by -Warray-bounds or -Warray-bounds=n if it is declared as either a flexible array member per C99 standard onwards ([]), a GCC zero-length array extension ([0]), or a one-element array ([1]). As a result, out of bounds subscripts or offsets into zero-length arrays or one-element arrays are not warned by default.

You can add the option -fstrict-flex-arrays or -fstrict-flex-arrays=level to control how this option treats the trailing array of a structure as a flexible array member:

  • when level<=1, no change to the default behavior.
  • when level=2, additional warnings will be issued for out of bounds subscripts or offsets into one-element arrays;
  • when level=3, in addition to level=2, additional warnings will be issued for out of bounds subscripts or offsets into zero-length arrays.
  • -Warray-bounds=1 โ€” this is the default warning level of -Warray-bounds and is enabled by -Wall; higher levels are not, and must be explicitly requested. ๐Ÿ‘‘
  • -Warray-bounds=2 โ€” this warning level also warns about the intermediate results of pointer arithmetic that may yield out of bounds values. Heads up though: this warning level may give a larger number of false positives and is deactivated by default. ๐Ÿ™ˆ
  • -Warray-compare โ€” warns about equality and relational comparisons between two operands of array type. This comparison was deprecated in C++20. For example:
int arr1[5];
int arr2[5];
bool same = arr1 == arr2;

-Warray-compare is enabled by -Wall. Not you comparing arrays like that bestie ๐Ÿ˜ญ

  • -Warray-parameter, -Warray-parameter=n โ€” warns about redeclarations of functions involving arguments of array or pointer 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 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. And the -Wvla-parameter option triggers warnings for similar inconsistencies involving Variable Length Array arguments.

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

Attributes on the guest list for that one include alloc_align, alloc_size, cold, const, hot, leaf, malloc, nonnull, noreturn, nothrow, pure, returns_nonnull, and returns_twice.

-Wattribute-alias is literally just -Wattribute-alias=1 in a trench coat, and that's the default, bestie. Wanna yeet these warnings? Either -Wno-attribute-alias or -Wattribute-alias=0. Both work. Pick your fighter. ๐Ÿ’…

  • -Wbidi-chars=[none|unpaired|any|ucn] โ€” Okay so this one is genuinely kinda scary ๐Ÿ˜ญ. It warns you about UTF-8 bidirectional control characters hanging out in your comments, string literals, character constants, and identifiers where they could be misleading. Why do we care? Because these little guys can flip left-to-right writing into right-to-left (and back again), and then the logical order and the visual order in your editor are not the same thing anymore. That's a whole situation. It can be straight-up dangerous โ€” like, a chunk of code might look commented out when it's actually, no cap, live code. ๐Ÿ’€

GCC gives you three levels of warning here:

  • Default is -Wbidi-chars=unpaired, which flags improperly terminated bidi contexts.
  • -Wbidi-chars=none says nope, off, don't wanna hear it.
  • -Wbidi-chars=any flags any use of bidirectional control characters at all.

By default this warning does not check UCNs. But you can turn that on with -Wbidi-chars=unpaired,ucn or -Wbidi-chars=any,ucn. And heads up โ€” -Wbidi-chars=ucn on its own is valid, and it means the same thing as -Wbidi-chars=unpaired,ucn, but only if no earlier -Wbidi-chars=any got specified. Options have memory, apparently. ๐Ÿง โœจ

  • -Wbool-compare โ€” Warns when you compare a boolean expression against an integer value that isn't true/false. Like, bestie, this comparison is always false:
int n = 5;
...
if ((n > 1) == 2) { ... }

This warning is enabled by -Wall. ๐ŸŽ€

  • -Wbool-operation โ€” Warns about suspicious operations on boolean-typed expressions. Friendly reminder that bitwise negation of a boolean is very likely a bug in your program, not a personality trait. ๐Ÿ™ˆ For C, this one also yells 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 โ€” Warns when an if-else has two literally identical branches. It catches situations like:
if (p != NULL)
  return 0;
else
  return 0;

It does not warn when both branches contain just a null statement. And it also catches conditional operators, like:

int i = x ? *p : *p;

Same thing twice, girl. We see it. ๐Ÿ‘€

  • -Wduplicated-cond โ€” Warns about duplicated conditions in an if-else-if chain. Example, yes it warns for this:
if (p->q != NULL) { ... }
else if (p->q != NULL) { ... }

You already asked that question. It answered. Move on. ๐Ÿ˜ญ

  • -Wframe-address โ€” Warns when __builtin_frame_address or __builtin_return_address gets called with an argument greater than 0. Those calls may return indeterminate values or straight-up crash your program. This warning is included in -Wall. โš ๏ธ
  • -Wno-discarded-qualifiers (C and Objective-C only) โ€” Do not warn when type qualifiers on pointers are being discarded. Normally the compiler yells if a const char * variable gets passed to a function expecting a char * parameter. This option is your "shhh, I know what I'm doing" card for that warning.
  • -Wno-discarded-array-qualifiers (C and Objective-C only) โ€” Do not warn when type qualifiers on arrays that are pointer targets are being discarded. Typically the compiler warns if a const int (*)[] variable is passed to a function taking a int (*)[] parameter. Use this to mute it.
  • -Wno-incompatible-pointer-types (C and Objective-C only) โ€” Do not warn when a conversion happens between pointers with incompatible types. Note this is for cases not covered by -Wno-pointer-sign, which handles pointer argument passing or assignment with different signedness. Two different jobs, two different flags, don't mix them up. ๐Ÿ’–
  • -Wno-int-conversion (C and Objective-C only) โ€” Do not warn about incompatible integer-to-pointer and pointer-to-integer conversions. This one is all about implicit conversions. For explicit conversions you'd want -Wno-int-to-pointer-cast and -Wno-pointer-to-int-cast instead.
  • -Wzero-length-bounds โ€” Warns 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. ๐Ÿšจ

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

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

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

Option -Wzero-length-bounds is enabled by -Warray-bounds. Iconic chain reaction. ๐Ÿ”ฅ

  • -Wno-div-by-zero โ€” Do not warn about compile-time integer division by zero. Note that floating-point division by zero is not warned about at all, because that can be a legitimate way of obtaining infinities and NaNs. So like, integer zero division = sus, float zero division = valid technique. Math stays weird. ๐Ÿฆ‹
  • -Wsystem-headers โ€” Prints warning messages for constructs found in system header files. Normally warnings from system headers are suppressed, on the assumption that they usually don't indicate real problems and would just make the compiler output harder to read. Using this command-line option tells GCC to emit warnings from system headers as if they occurred in user code. โœจ
Careful though: using -Wall in conjunction with this option does not warn about unknown pragmas in system headers. For that, you need -Wunknown-pragmas too. Two flags, one job. That's just how it is. ๐Ÿ’…
  • -Wtautological-compare โ€” Warns if a self-comparison always evaluates to true or false. It catches a bunch of classics like:
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) { ... }

...will always be false.

This warning is enabled by -Wall. ๐Ÿ˜ญ

  • -Wtrampolines โ€” Warns about trampolines generated for pointers to nested functions. So what's a trampoline? 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. Yeah. That. ๐Ÿ“
  • -Wfloat-equal โ€” Warns if floating-point values are used in equality comparisons.

The whole idea here: sometimes it's convenient (for the programmer) to think of floating-point values as approximations to infinitely precise real numbers. If that's your vibe, then you need to compute โ€” by analyzing the code, or some other way โ€” the maximum or likely maximum error that the computation introduces, and allow for it when you do comparisons (and when producing output, but that's a different problem entirely, bestie). In particular, instead of testing for equality, you should check whether the two values have ranges that overlap. That's what the relational operators are for. So those equality comparisons? Probably a mistake. ๐Ÿ™ˆ

  • -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. The list, because of course there's a list:
    • Macro parameters that appear within string literals in the macro body. In traditional C, macro replacement takes place within string literals, but in ISO C it does not.
    • In traditional C, some preprocessor directives did not exist. Traditional preprocessors only considered a line to be a directive if the # appeared in column 1 on the line. 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. And 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 that these suffixes show up in macros defined in system headers on most modern systems, e.g. the _MIN/_MAX macros in <limits.h>. Using 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. Smart girl behavior. ๐Ÿ’…
    • A function declared external in one block and then used after the end of the block.
    • A switch statement has an operand of type long.
    • A non-static function declaration follows a static one. This construct is not accepted by some traditional C compilers.
    • The ISO type of an integer constant has a different width or signedness from its traditional type. This warning is only issued if the base of the constant is ten. I.e. hexadecimal or octal values, which typically represent bit patterns, are not warned about.
    • Usage of ISO string concatenation is detected.
    • Initialization of automatic aggregates.
    • Identifier conflicts with labels. Traditional C lacks a separate namespace for labels.
    • Initialization of unions. If the initializer is zero, the warning is omitted. This is done under the assumption that the zero initializer in user code appears conditioned on e.g. __STDC__ to avoid missing initializer warnings, and relies on default initialization to zero in the traditional C case.

  • Conversions via prototypes between fixed/floating-point values and vice versa. Bestie, when you're compiling with traditional C and those prototypes just aren't there, it causes serious problems ๐Ÿ˜ญ. And heads up โ€” this is only a subset of the possible conversion warnings; for the full set you want -Wtraditional-conversion.
    • ISO C style function definitions. Okay so this warning is intentionally not issued for prototype declarations or variadic functions, because those ISO C features show up in your code when you're using libiberty's traditional C compatibility macros, PARAMS and VPARAMS ๐Ÿซถ. It's also bypassed for nested functions, because that feature is already a GCC extension and so it's just not relevant to traditional C compatibility.
  • -Wtraditional-conversion (C and Objective-C only) โ€” warns you when a prototype forces a type conversion that would be different from what would happen to the same argument with no prototype around ๐Ÿ’…. That covers conversions of fixed point to floating and vice versa, plus conversions that change 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 shows up after a statement inside a block ๐Ÿ‘€. This construct, which you know from C++, got introduced with ISO C99 and is by default allowed in GCC. ISO C90 does not support it, periodt.
  • -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 โœจ. Ngl, 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 get ignored when -Wshadow is used. Same as -Wshadow=global.
  • -Wno-shadow-ivar (Objective-C only) โ€” do not warn whenever a local variable shadows an instance variable in an Objective-C method ๐Ÿ™ˆ.
  • -Wshadow=global โ€” warns for any shadowing. Same as -Wshadow.
  • -Wshadow=local โ€” warns when a local variable shadows another local variable or a parameter ๐Ÿ’–.
  • -Wshadow=compatible-local โ€” warns when a local variable shadows another local variable or parameter whose type is compatible with that of the shadowing variable. In C++, type compatibility here means the type of the shadowing variable can be converted to that of the shadowed variable. The whole idea behind creating this flag (on top of -Wshadow=local) is that when a local variable shadows another one of an incompatible type, it's most likely intentional โ€” not a bug, not a typo โ€” like in this iconic little 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 ๐ŸŽ€. And 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. Using this flag instead of -Wshadow=local can possibly reduce the number of warnings triggered by intentional shadowing. Note that this also means 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 a byte-size of SIZE_MAX or more, or by -Wno-larger-than.

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

  • -Wno-larger-than โ€” disables -Wlarger-than= warnings ๐Ÿ’…. This option is equivalent to -Wlarger-than=SIZE_MAX or larger.
  • -Wframe-larger-than=byte-size โ€” warns if the size of a function frame exceeds byte-size ๐ŸŒธ. Fair warning: the computation done to figure out the stack frame size is approximate and not conservative โ€” the actual requirements may be somewhat greater than byte-size even if you never get a warning ๐Ÿ˜ญ. On top of that, any space allocated via alloca, variable-length arrays, or related constructs is not included by the compiler when it decides whether or not to issue a warning. -Wframe-larger-than=PTRDIFF_MAX is enabled by default. Warnings controlled by this option can be disabled either by specifying a byte-size of SIZE_MAX or more, or by -Wno-frame-larger-than.
  • -Wno-frame-larger-than โ€” disables -Wframe-larger-than= warnings ๐Ÿซถ. Equivalent to -Wframe-larger-than=SIZE_MAX or larger.
  • -Wfree-nonheap-object โ€” warns when you attempt to deallocate an object that was either not allocated on the heap, or via a pointer that was not returned from a prior call to the corresponding allocation function ๐Ÿ’€. For example, because the call to stpcpy returns a pointer to the terminating nul character and not to the beginning of the object, the call to free below gets diagnosed:
void f (char *p)
{
  p = stpcpy (p, "abc");
  // ...
  free (p);   // warning
}

-Wfree-nonheap-object is included in -Wall โญ.

  • -Wstack-usage=byte-size โ€” warns if the stack usage of a function might exceed byte-size ๐Ÿ‘‘. The computation done to determine the stack usage is conservative. And unlike frame-larger-than, any space allocated via alloca, variable-length arrays, or related constructs is included by the compiler when it's deciding whether or not to issue a warning.

The message keeps in step with the output of -fstack-usage ๐Ÿฆ‹:

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

-Wstack-usage=PTRDIFF_MAX is enabled by default. Warnings controlled by this option can be disabled either by specifying a byte-size of SIZE_MAX or more, or by -Wno-stack-usage โœจ.

  • -Wno-stack-usage โ€” disables -Wstack-usage= warnings ๐Ÿ’œ. This option is equivalent to -Wstack-usage=SIZE_MAX or larger.
  • -Wunsafe-loop-optimizations โ€” warns if the loop cannot be optimized because the compiler can't assume anything about the bounds of the loop indices ๐Ÿ™ˆ. With -funsafe-loop-optimizations, warn if the compiler makes such assumptions. Lowkey a whole different vibe.
  • -Wno-pedantic-ms-format (MinGW targets only) โ€” when used together with -Wformat and -pedantic and without GNU extensions, this option disables the warnings about the non-ISO printf / scanf format width specifiers I32, I64, and I used on Windows targets, which depend on the MS runtime ๐ŸŽ€.
  • -Wpointer-arith โ€” warns about anything that depends on the "size of" a function type or of void ๐Ÿ‘€. GNU C assigns these types a size of 1, for convenience in calculations with void * pointers and pointers to functions. In C++, it also warns when an arithmetic operation involves NULL. This warning is also enabled by -Wpedantic.
  • -Wno-pointer-compare โ€” do not warn if a pointer is compared with a zero character constant ๐Ÿซถ. That comparison usually means the pointer was meant to be dereferenced. Like:
const char *p = foo ();
if (p == '\0')
  return 42;

Note that the code above 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 of the limited range of the data type โ€” but it does not warn for constant expressions ๐Ÿ’…. For example, warn if an unsigned variable is compared against zero with < or >=. This warning is also enabled by -Wextra.
  • -Wabsolute-value (C and Objective-C only) โ€” warns for calls to standard functions that compute the absolute value of an argument when a more appropriate standard function is available โœจ. For example, calling abs(3.14) triggers the warning, because the appropriate function to call to compute the absolute value of a double argument is fabs. The option also triggers warnings when the argument in a call to such a function has an unsigned type. This warning can be suppressed with an explicit type cast, and it's also enabled by -Wextra.
  • -Wcomment
  • -Wcomments โ€” warns whenever a comment-start sequence /* appears in a /* comment, or whenever a backslash-newline appears in a // comment ๐Ÿฆ‹. This warning is enabled by -Wall.
  • -Wtrigraphs โ€” warns if any trigraphs are encountered that might change the meaning of the program ๐Ÿ‘€. Trigraphs within comments are not warned about, except those that would form escaped newlines.

This option is implied by -Wall. If -Wall is not given, this option is still enabled unless trigraphs are enabled. To get trigraph conversion without warnings, but still get the other -Wall warnings, use -trigraphs -Wall -Wno-trigraphs ๐Ÿ’….

  • -Wundef โ€” warns if an undefined identifier is evaluated in an #if directive ๐Ÿ™ˆ. Such identifiers get replaced with zero.
  • -Wexpansion-to-defined โ€” warns whenever defined is encountered in the expansion of a macro (including the case where the macro is expanded by an #if directive) ๐Ÿ˜ญ. Such usage is not portable. This warning is also enabled by -Wpedantic and -Wextra.
  • -Wunused-macros โ€” warns about macros defined in the main file that are unused ๐Ÿ’ค. A macro counts as used if it's expanded or tested for existence at least once. The preprocessor also warns if the macro has not been used at the time it is redefined or undefined.
  • (heads up, continuing) Macros that are built-in, macros you #define on the command line, and macros defined in include files โ€” those do not get warned about. Only user macros in the actual source. โœจ
ok bestie, little gotcha: if a macro is actually used, but only used inside skipped conditional blocks, the preprocessor still reports it as unused. ๐Ÿ˜ญ To dodge the warning in that case, you might improve the scope of the macro's definition โ€” for example, tuck it into the first skipped block. Or alternatively, just feed it a lil dummy use like this:
#if defined the_macro_causing_the_warning
#endif

  • -Wno-endif-labels โ€” do not warn whenever an #else or an #endif is followed by text. Ngl, this sometimes happens in older programs with code shaped like:
#if FOO
...
#else FOO
...
#endif FOO

That second and third FOO should be in comments. This warning is on by default, so yeah, it'll show up unless you silence it. ๐Ÿซถ

  • -Wbad-function-cast (C and Objective-C only) โ€” warns when a function call gets cast to a non-matching type. Like if you call a function returning an integer type and cast it to a pointer type. It's giving "bestie why". ๐Ÿ’€
  • -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 in the expression that follows __extension__. ๐Ÿ‘‘
  • -Wc99-c11-compat (C and Objective-C only) โ€” warns about features not present in ISO C99 but present in ISO C11. For instance: anonymous structures and unions, the _Atomic type qualifier, the _Thread_local storage-class specifier, the _Alignas specifier, the Alignof operator, the _Generic keyword, and so on. Also 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 not present in ISO C11 but present in ISO C2X. For instance: omitting the string in _Static_assert, use of [[]] syntax for attributes, use of decimal floating-point types, and so on. Yep, independent of the standards mode again. Warnings are disabled in the expression that follows __extension__. โœจ
  • -Wc++-compat (C and Objective-C only) โ€” warns about ISO C constructs that live outside the common subset of ISO C and ISO C++, e.g. 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, e.g. 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. โญ
  • -Wno-c++11-extensions (C++ and Objective-C++ only) โ€” do not warn about C++11 constructs in code being compiled with an older C++ standard. Even without this option, some C++11 constructs will only be diagnosed if -Wpedantic is used. ๐Ÿงš
  • -Wno-c++14-extensions (C++ and Objective-C++ only) โ€” do not warn about C++14 constructs in code being compiled with an older C++ standard. Even without this option, some C++14 constructs will only be diagnosed if -Wpedantic is used. ๐ŸŒˆ
  • -Wno-c++17-extensions (C++ and Objective-C++ only) โ€” do not warn about C++17 constructs in code being compiled with an older C++ standard. Even without this option, some C++17 constructs will only be diagnosed if -Wpedantic is used. ๐ŸŽ€
  • -Wno-c++20-extensions (C++ and Objective-C++ only) โ€” do not warn about C++20 constructs in code being compiled with an older C++ standard. Even without this option, some C++20 constructs will only be diagnosed if -Wpedantic is used. ๐Ÿ“
  • -Wno-c++23-extensions (C++ and Objective-C++ only) โ€” do not warn about C++23 constructs in code being compiled with an older C++ standard. Even without this option, some C++23 constructs will only be diagnosed if -Wpedantic is used. ๐Ÿ’œ
  • -Wcast-qual โ€” warns whenever a pointer is cast so as to remove a type qualifier from the target type. For example, warn if a const char * is cast to an ordinary char *.

It also warns when you make a cast that introduces a type qualifier in an unsafe way. For example, casting char ** to const char ** is unsafe, like in this example:

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

Likeโ€ฆ that last line is a whole crime scene. ๐Ÿšจ

  • -Wcast-align โ€” warns whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a char * is cast to an int * on machines where integers can only be accessed at two- or four-byte boundaries. ๐Ÿ˜ตโ€๐Ÿ’ซ
  • -Wcast-align=strict โ€” warns whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a char * is cast to an int * regardless of the target machine. No hiding behind your architecture, bestie. ๐Ÿ’€
  • -Wcast-function-type โ€” warns when a function pointer is cast to an incompatible function pointer. In a cast involving function types with a variable argument list, only the types of initial arguments that are provided are considered. Any parameter of pointer-type matches any other pointer-type. Any benign differences in integral types are ignored, like int vs. long on ILP32 targets. Likewise, type qualifiers are ignored. The function type void (*) (void) is special and matches everything, which can be used to suppress this warning. In a cast involving pointer to member types, this warning warns whenever the type cast is changing the pointer to member type. This warning is enabled by -Wextra. ๐Ÿ”ฅ
  • -Wwrite-strings โ€” when compiling C, give 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 find, at compile time, code that can try to write into a string constant โ€” but only if you've been very careful about using const in declarations and prototypes. Otherwise it's just a nuisance. This is why -Wall does not request these warnings.

When compiling C++, warn 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. This warning is also enabled by -Wextra. ๐Ÿ˜ญ
  • -Wno-complain-wrong-lang โ€” by default, language front ends complain when a command-line option is valid, but not applicable to that front end. This may be disabled with -Wno-complain-wrong-lang, which is mostly useful when invoking a single compiler driver for multiple source files written in different languages, for example:
$ g++ -fno-rtti a.cc b.f90

The driver g++ invokes the C++ front end to compile a.cc and the Fortran front end to compile b.f90. The latter front end diagnoses

f951: Warning: command-line option '-fno-rtti' is valid for C++/D/ObjC++ but not for Fortran

which may be disabled with -Wno-complain-wrong-lang. So iconic of you to compile two languages at once tho. ๐Ÿซถ

  • -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). Do not warn for explicit casts like abs ((int) x) and ui = (unsigned) -1, or if the value is not 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++, also warn 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 may be confusion as to which if statement an else branch belongs to. Here's an example of such a case:
{
  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). This is often not what the programmer expected, as illustrated in the above example by the indentation the programmer chose. When there's the potential for this confusion, GCC issues a warning when this flag is specified. To eliminate 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. Not the vibes getting ambiguous ๐Ÿ’€ โ€” braces are your bestie fr fr. ๐ŸŽ€

  • -Wdangling-pointer, -Wdangling-pointer=n โ€” okay bestie, this one is literally the "your pointer is SO expired" warning ๐Ÿ’€ it yells at you for using pointers (or C++ references) that point at objects with automatic storage duration after those objects' lifetime has already ended. And it's not just plain local vars โ€” nested-block locals, compound literals, unnamed temporary objects, all of them. It also side-eyes you for stashing the address of one of those expired objects into an escaped pointer. ๐Ÿซถ The warning is enabled at all optimization levels, but heads up: it may yield different results with optimization than without.
    • -Wdangling-pointer=1 โ€” level 1 only diagnoses unconditional uses of dangling pointers. Iconic. For example:
int f (int c1, int c2, x)
{
  char *p = strchr ((char[]){ c1, c2 }, c3);
  // warning: dangling pointer to a compound literal
  return p ? *p : 'x';
}

And in this next function, the store of the address of the local variable x into the escaped pointer *p also triggers the warning:

void g (int **p)
{
  int x = 7;
  // warning: storing the address of a local variable in *p
  *p = &x;
}
  • -Wdangling-pointer=2 โ€” level 2 goes further, and honestly it's giving detective energy ๐Ÿ” because on top of unconditional uses, it also diagnoses conditional uses of dangling pointers.

For example, because the array a in the following function is out of scope by the time the pointer s (which was set to point at it) gets used, the warning triggers at this level:

void f (char *s)
{
  if (!s)
    {
      char a[12] = "tmpname";
      s = a;
    }
  // warning: dangling pointer to a may be used
  strcat (s, ".tmp");
  ...
}
Quick glow-up note: -Wdangling-pointer=2 is included in -Wall. โœจ
  • -Wdate-time โ€” warns you when the macros "__TIME__", "__DATE__" or "__TIMESTAMP__" show up, because they might prevent bit-wise-identical reproducible compilations. ๐ŸŒธ Reproducibility girlies stay winning, no cap.
  • -Wempty-body โ€” warns if there's an empty body in an if, else or do while statement. Yeah bestie, { } with nothing in it is suspicious ๐Ÿ’… This warning is also enabled by -Wextra.
  • -Wno-endif-labels โ€” do not warn about stray tokens after "#else" and "#endif". That's it. That's the whole thing. ๐Ÿ™ˆ
  • -Wenum-compare โ€” warns about a comparison between values of different enumerated types. In C++ this warning is enabled by default and enumerated type mismatches in conditional expressions are also diagnosed. In C, it's enabled by -Wall.
  • -Wenum-conversion โ€” warns when a value of an enumerated type gets implicitly converted to a different enumerated type. Sneaky little glow-down, honestly. In C this warning is enabled by -Wextra.
  • -Wenum-int-mismatch (C and Objective-C only) โ€” warns about mismatches between an enumerated type and an integer type in declarations. Like, for example:
enum E { l = -1, z = 0, g = 1 };
int foo(void);
enum E foo(void);

In C, an enumerated type is compatible with char, a signed integer type, or an unsigned integer type. BUT since the choice of the underlying type of an enumerated type is implementation-defined, these mismatches may cause portability issues. ๐Ÿ˜ญ In C++, such mismatches are an error. In C, this warning is enabled by -Wall and -Wc++-compat.

  • -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 are declared, and it's only supported for C and Objective-C โ€” in C++ this sort of branch is an error in any case, so there's nothing to warn about. ๐Ÿคทโ€โ™€๏ธ

Fun fact: -Wjump-misses-init is included in -Wc++-compat. And you can turn it off 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 gets converted to unsigned. Classic signedness betrayal ๐Ÿ’€ In C++, this warning is also enabled by -Wall. In C, it is 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 (clock it, bestie โœจ). In C, this option is enabled also by -Wconversion.
  • -Wfloat-conversion โ€” warns for implicit conversions that reduce the precision of a real value. That includes conversions from real to integer, and from higher precision real to lower precision real values. This option is also enabled by -Wconversion. ๐Ÿ“ Precision loss is not the vibe.
  • -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 will not yield the number of elements in the array, which is likely what you actually meant. ๐Ÿ˜ญ 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. That's the usual way to compute the array size, but it will not 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 it 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 right there indicates 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 folds to zero, or a cast of zero to some type, it's far less likely that the arguments were mistakenly transposed, and no warning is emitted. This warning is enabled by -Wall.
  • -Waddress โ€” warns about suspicious uses of address expressions. These include comparing the address of a function or a declared object to the null pointer constant, such as in:
void f (void);
void g (void)
{
  if (!f)   // warning: expression evaluates to false
    abort ();
}

comparisons of a pointer to a string literal, such as in:

void f (const char *x)
{
  if (x == "abc")   // warning: expression evaluates to false
    puts ("equal");
}

and tests of the results of pointer addition or subtraction for equality to null, such as in:

void f (const int *p, int i)
{
  return p + i == NULL;
}

Such uses typically indicate a programmer error: the address of most functions and objects necessarily evaluates to true (the exception are weak symbols), so their use in a conditional might indicate missing parentheses in a function call or a missing dereference in an array expression. The subset of the warning for object pointers can be suppressed by casting the pointer operand to an integer type such as intptr_t or uintptr_t. Comparisons against string literals result in unspecified behavior and are not portable, and suggest the intent was to call strcmp. The warning is suppressed if the suspicious expression is the result of macro expansion. -Waddress 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) { ... }

Like bestieโ€ฆ a < 0 && a < 0?? Twice?? ๐Ÿซ 

  • -Wlogical-not-parentheses โ€” warns about logical not used on the left hand side operand of a comparison. This option does not warn if the right operand is considered to be a boolean expression. Its purpose is to detect suspicious code like the following:
int a;
...
if (!a > 1) { ... }

okay bestie so if you ever need to suppress that warning, you can literally wrap the LHS in parentheses like this:

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

and boom, the warning is gone. Also this warning is enabled by -Wall.

  • -Waggregate-return โ€” warns if any functions that return structures or unions are defined or called. (And if you're in a language where you can return an array, that also gets a warning. ๐Ÿ’…)
  • -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. ๐Ÿซ 
  • -Wno-attributes โ€” do not warn if an unexpected "__attribute__" is used, like unrecognized attributes, function attributes applied to variables, etc. This does not stop errors for incorrect use of supported attributes.

Additionally, using -Wno-attributes=, it is possible to suppress warnings about unknown scoped attributes (in C++11 and C2X). For example, -Wno-attributes=vendor::attr disables warning about the following declaration:

[[vendor::attr]] void f();

It is also possible to disable warning about all attributes in a namespace using -Wno-attributes=vendor::, which prevents warning about both of these declarations:

[[vendor::safe]] void f();
[[vendor::unsafe]] void f2();

Note that -Wno-attributes= does not imply -Wno-attributes. ๐Ÿ’€

  • -Wno-builtin-declaration-mismatch โ€” warns if a built-in function is declared with an incompatible signature or as a non-function, or when a built-in 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, also warn 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__. ๐ŸŽ€
  • -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.) ๐Ÿ‘‘
  • -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. A definition using () is not considered an old-style definition in C2X mode, because it is equivalent to (void) in that case, but 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. This warning is issued 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. 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. Use -Wmissing-declarations to detect missing declarations in C++. ๐Ÿ’…
  • -Wmissing-declarations โ€” warns if a global function is defined without a previous declaration. Do 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. ๐ŸŒธ
  • -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-missing-requires โ€” by default, the compiler warns about a concept-id appearing as a C++20 simple-requirement:
bool satisfied = requires { C<T> };

Here satisfied will be true if C<T> is a valid expression, which it is for all T. Presumably the user meant to write:

bool satisfied = requires { requires C<T> };

so satisfied is only true if concept C is satisfied for type T.

This warning can be disabled with -Wno-missing-requires. ๐Ÿ”ฅ

  • -Wno-missing-template-keyword โ€” the member access tokens ., -> and :: must be followed by the "template" keyword if the parent object is dependent and the member being named is a template.
template <class X>
void DoStuff (X x)
{
  x.template DoSomeOtherStuff<X>(); // Good.
  x.DoMoreStuff<X>(); // Warning, x is dependent.
}

In rare cases it is possible to get false positives. To silence this, wrap the expression in parentheses. For example, the following is treated as a template, even where m and N are integers:

void NotATemplate (my_class t)
{
  int N = 5;

  bool test = t.m < N > (0); // Treated as a template.
  test = (t.m < N) > (0); // Same meaning, but not treated as a template.
}

This warning can be disabled with -Wno-missing-template-keyword. ๐Ÿฆ‹

  • -Wno-multichar โ€” do not warn if a multicharacter constant ('FOOF') is used. Usually they indicate a typo in the user's code, as they have implementation-defined values, and should not be used in portable code. ๐Ÿ’€
  • -Wnormalized=[none|id|nfc|nfkc] โ€” in ISO C and ISO C++, two identifiers are different if they are different sequences of characters. However, 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; 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. ๐Ÿ™ˆ

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. ๐ŸŽ€
  • -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 โ€” bestie, this one snitches on One Definition Rule violations during link-time optimization. It's on by default, so it's already doing its lil surveillance job. ๐Ÿ‘€
  • -Wopenacc-parallelism โ€” yells at you when your OpenACC parallelism choices are potentially suboptimal. Not illegal, justโ€ฆ not the serve it could've been. ๐Ÿ’…
  • -Wopenmp-simd โ€” fires when the vectorizer cost model overrides the OpenMP simd directive you set. Rude, honestly. If you wanna relax that cost model, reach for -fsimd-cost-model=unlimited. โœจ
  • -Woverride-init (C and Objective-C only) โ€” warns when an initialized field without side effects gets overridden while you're using designated initializers.

This one is part of -Wextra, so if you want the other -Wextra warnings but not this one, hit it with -Wextra -Wno-override-init. ๐ŸŽ€

  • -Wno-override-init-side-effects (C and Objective-C only) โ€” turns off the warning for when an initialized field with side effects gets overridden in designated initializers. This warning is enabled by default.
  • -Wpacked โ€” warns when a struct is given the packed attribute but that attribute literally does nothing to its layout or size. Which means the struct might be mis-aligned for basically zero benefit. Not the slay, it's the ๐Ÿซ .

Like, look at this โ€” f.x inside struct bar ends up misaligned even though struct bar itself has no packed attribute:

struct foo {
  int x;
  char a, b, c, d;
} __attribute__((packed));
struct bar {
  char z;
  struct foo f;
};
  • -Wnopacked-bitfield-compat โ€” okay history lesson ๐Ÿ“š: GCC 4.1, 4.2 and 4.3 straight-up ignored the packed attribute on bit-fields of type char. It got fixed in GCC 4.4, but that fix can change your struct layout, which is the kind of chaos that ruins your whole week.

So GCC tells you when the offset of such a field changed in GCC 4.4. For exaaaample, there's no longer a 4-bit padding between field a and b in this:

struct foo
{
  char a:4;
  char b:8;
} __attribute__ ((packed));

This warning is enabled by default. Use -Wno-packed-bitfield-compat to disable it.

  • -Wpacked-not-aligned (C, C++, Objective-C and Objective-C++ only) โ€” warns when a struct field with explicitly specified alignment inside a packed struct or union ends up misaligned. Ngl it's giving "you asked for alignment and the universe said no".

So a warning gets issued on struct S like warning: alignment 1 of 'struct S' is less than 8, in this code right here:

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 sneaks into a structure, whether it's to align an element or to align the whole thing. Sometimes you can rearrange the fields, shrink the padding, and make the whole struct smaller. Free diet, no gym. ๐Ÿ’ช
  • -Wredundant-decls โ€” warns if literally anything gets declared more than once in the same scope, even in the cases where the double declaration is valid and changes absolutely nothing. It's the "why are you like this" of warnings. ๐Ÿ™ˆ
  • -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 instance, the call to strcpy below is trying to truncate the string by replacing its first chars with the last four. But since the call writes the terminating NUL into a[4], the copies overlap and the call gets diagnosed. Caught in 4K. ๐Ÿ“ธ

void foo (void)
{
  char a[] = "abcd1234";
  strcpy (a, a + 4);
  ...
}

-Wrestrict catches some instances of simple overlap even without optimization, but it works best at -O2 and above. It's included in -Wall.

  • -Wnested-externs (C and Objective-C only) โ€” warns if an extern declaration shows up inside a function. Putting your externs inside a function? In this economy? ๐Ÿ˜ญ
  • -Winline โ€” warns if a function declared as inline cannot be inlined. But even with this option on, the compiler won't warn about failures to inline functions declared in system headers. It's got selective hearing, and honestly? Same.

The compiler uses a whole bunch of heuristics to decide whether to inline something or not. For example, it considers the size of the function being inlined and how much inlining has already happened in the current function.

Which means seemingly tiny, insignificant changes in your source can make -Winline warnings appear or vanish. So if you're chasing them like a detective ๐Ÿ”, know that the vibes are unstable.

  • -Winterference-size โ€” warns about using C++17 std::hardware_destructive_interference_size without specifying its value with --param destructive-interference-size. Also warns about questionable values for that option.

This variable exists to control class layout and avoid false sharing in concurrent code:

struct independent_fields {
  alignas(std::hardware_destructive_interference_size)
    std::atomic<int> one;
  alignas(std::hardware_destructive_interference_size)
    std::atomic<int> two;
};

Here one and two are meant to be far enough apart that stores to one won't force the other to reload the cache line. Space, boundaries, healthy relationships. ๐Ÿฆ‹

By default, --param destructive-interference-size and --param constructive-interference-size are set based on the current -mtune option โ€” typically the L1 cache line size for that particular target CPU, sometimes a range if you're tuning for a generic target.

So every translation unit that depends on ABI compatibility for these variables has to be compiled with the same -mtune (or -mcpu). No mixing, no matching. ๐Ÿšซ

If ABI stability is important โ€” like, say, the use is in a header for a library โ€” you should probably not use the hardware interference size variables at all. Alternatively, you can force a particular value with --param.

And if you're confident your use of the variable doesn't affect ABI outside a single build of your project, you can turn the warning off with -Wno-interference-size. Live your truth. ๐Ÿ’œ

  • -Wint-in-bool-context โ€” warns about suspicious use of integer values where boolean values are expected. Like conditional expressions (?:) using non-boolean integer constants in a boolean context, such as if (a <= b ? 2 : 3). Sussy. ๐Ÿคจ

Or left shifting signed integers in a boolean context, like for (a = 0; 1 << a; a++);. Same energy, also flagged.

And likewise for all kinds of multiplications regardless of 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, not a warning. 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. Round trip, but make it cursed. ๐Ÿ’€
  • -Winvalid-pch โ€” warns if a precompiled header is found in the search path but cannot be used. It's right there!! And yet. ๐Ÿ˜ค
  • -Winvalid-utf8 โ€” warns if an invalid UTF-8 character is found. This warning is on by default for C++23 if -finput-charset=UTF-8 is used, and it gets turned into an error with -pedantic-errors. So behave. ๐Ÿ˜‡
  • -Wno-unicode โ€” don't diagnose invalid forms of delimited or named escape sequences that are treated as separate tokens. Wunicode is enabled by default.
  • -Wlong-long โ€” warns if the long long type is used. This gets enabled by either -Wpedantic or -Wtraditional in ISO C90 and C++98 modes. To shut the warnings up, use -Wno-long-long.
  • -Wvariadic-macros โ€” warns if variadic macros are used in ISO C90 mode, or if the GNU alternate syntax is used in ISO C99 mode. Enabled by either -Wpedantic or -Wtraditional. To silence the messages, use -Wno-variadic-macros. ๐Ÿคซ
  • -Wno-varargs โ€” don't warn on questionable usage of the macros used to handle variable arguments, like va_start. These warnings are enabled by default.
  • -Wvector-operation-performance โ€” warns if a vector operation isn't implemented via the SIMD capabilities of the architecture. Mainly useful for performance tuning, aka for the number girlies ๐Ÿ“ˆ.

A vector operation can be implemented a few ways:

  • "piecewise" โ€” the scalar operation is performed on every vector element.
  • "in parallel" โ€” the vector operation is implemented using scalars of a wider type, which normally is more performance efficient. โœจ
  • "as a single scalar" โ€” the vector fits into a scalar type.
  • -Wvla โ€” warns if a variable-length array is used in the code. And -Wno-vla prevents the -Wpedantic warning about the variable-length array. Two warnings, one vibe check.
  • -Wvla-larger-than=byte-size โ€” with this option in play, the compiler warns about declarations of variable-length arrays whose size is either unbounded, or bounded by an argument that lets the array size exceed byte-size bytes.

This is similar to how -Walloca-larger-than=byte-size works, but with variable-length arrays instead. ๐ŸŒˆ

Heads up bestie: GCC may optimize small variable-length arrays of a known value into plain arrays, so this warning might not even trigger for those. Sneaky.

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

See also -Walloca-larger-than=byte-size. ๐Ÿ‘€

  • -Wno-vla-larger-than โ€” disables the -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 it enables detection of out-of-bounds accesses to such parameters by warnings like -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.

So failing to provide arguments of sufficient size, or accessing more than the maximum number of elements, may get diagnosed. The bounds are the bounds, periodt. ๐Ÿ’…


  • -Wvolatile-register-var โ€” ok so this one yells at you if you declared a register variable as volatile ๐Ÿ’€ and like, here's the thing bestie: that volatile modifier does not stop all the optimizations that could kill off reads and/or writes to register variables. Nope. So don't think it's gonna save you. This warning is switched on by -Wall.
  • -Wxor-used-as-pow (C, C++, Objective-C and Objective-C++ only) โ€” warns you about uses of ^, the exclusive-or operator, in cases where it looks like the user meant exponentiation. Specifically, it fires when the left-hand side is the decimal constant 2 or 10 and the right-hand side is also a decimal constant.

In C and C++, ^ means exclusive or โ€” but in some other languages (e.g. TeX and some versions of BASIC) it means exponentiation. So the vibe check gets confused ๐Ÿ˜ญ

This warning is enabled by default. Wanna silence it? Just convert one of the operands to hexadecimal. Boom, gone โœจ

  • -Wdisabled-optimization โ€” warns if a requested optimization pass is disabled. Ngl this usually does not mean something's wrong with your code; it just means GCC's optimizers couldn't handle it effectively. Often it's because your code is too big or too complex โ€” and GCC flat-out refuses to optimize programs when the optimization itself is probably gonna take an inordinate amount of time. Respect for the boundaries honestly ๐Ÿซถ
  • -Wpointer-sign (C and Objective-C only) โ€” warns when you pass or assign a pointer argument with different signedness. This option is only supported for C and Objective-C. It's implied by -Wall and by -Wpedantic, and you can turn it off with -Wno-pointer-sign.
  • -Wstack-protector โ€” this one is only active when -fstack-protector is active. It warns about functions that are not protected against stack smashing ๐Ÿ›ก๏ธ
  • -Woverlength-strings โ€” warns about string constants that are longer than the "minimum maximum" length specified in the C standard. Modern compilers generally let you have string constants way 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 doesn't specify a normative minimum maximum, so we don't diagnose overlength strings in C++.

This option is implied by -Wpedantic, and can be disabled with -Wno-overlength-strings.

  • -Wunsuffixed-float-constants (C and Objective-C only) โ€” issues a warning for any floating constant that doesn't have a suffix. When you use it together with -Wsystem-headers, it warns about such constants in system header files too. 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 link-time optimization, don't warn about type mismatches in global declarations from different compilation units. Requires -flto to be enabled. Enabled by default.
  • -Wno-designated-init (C and Objective-C only) โ€” suppresses warnings when a positional initializer is used to initialize a structure that has been marked with the designated_init attribute.

โœจ Options That Control Static Analysis โœจ

  • -fanalyzer โ€” bestie this option enables a static analysis of program flow that hunts for "interesting" interprocedural paths through the code, and issues warnings for the problems it finds on them ๐Ÿ”

Heads up: this analysis is much more expensive than other GCC warnings.

In technical terms, it performs coverage-guided symbolic execution of the code being compiled. It is neither sound nor complete: it can have false positives and false negatives. It's a bug-finding tool, not a tool for proving program correctness โ€” so don't ask it for a notarized certificate, okay?

In this release, the analyzer is only suitable for use on C code.

Turning this option on effectively enables the following warnings:

-Wanalyzer-allocation-size -Wanalyzer-deref-before-check
-Wanalyzer-double-fclose -Wanalyzer-double-free
-Wanalyzer-exposure-through-output-file
-Wanalyzer-exposure-through-uninit-copy
-Wanalyzer-fd-access-mode-mismatch -Wanalyzer-fd-double-close
-Wanalyzer-fd-leak -Wanalyzer-fd-phase-mismatch
-Wanalyzer-fd-type-mismatch -Wanalyzer-fd-use-after-close
-Wanalyzer-fd-use-without-check -Wanalyzer-file-leak
-Wanalyzer-free-of-non-heap -Wanalyzer-imprecise-fp-arithmetic
-Wanalyzer-infinite-recursion -Wanalyzer-jump-through-null
-Wanalyzer-malloc-leak -Wanalyzer-mismatching-deallocation
-Wanalyzer-null-argument -Wanalyzer-null-dereference
-Wanalyzer-out-of-bounds -Wanalyzer-possible-null-argument
-Wanalyzer-possible-null-dereference -Wanalyzer-putenv-of-auto-var
-Wanalyzer-shift-count-negative -Wanalyzer-shift-count-overflow
-Wanalyzer-stale-setjmp-buffer
-Wanalyzer-unsafe-call-within-signal-handler
-Wanalyzer-use-after-free
-Wanalyzer-use-of-pointer-in-stale-stack-frame
-Wanalyzer-use-of-uninitialized-value
-Wanalyzer-va-arg-type-mismatch -Wanalyzer-va-list-exhausted
-Wanalyzer-va-list-leak -Wanalyzer-va-list-use-after-va-end
-Wanalyzer-write-to-const -Wanalyzer-write-to-string-literal
This option is only available if GCC was configured with analyzer support enabled. No support, no analysis, periodt.
  • -Wanalyzer-too-complex โ€” if -fanalyzer is enabled, the analyzer uses various heuristics to try to explore the control flow and data flow in the program, but sufficiently complicated code can defeat all of that ๐Ÿ˜ต

By default, the analysis silently stops if the code is too complicated for the analyzer to fully explore and it hits an internal limit. The -Wanalyzer-too-complex option warns you if that happens.

  • -Wno-analyzer-allocation-size โ€” this warning requires -fanalyzer, which enables it; to disable it, use -Wno-analyzer-allocation-size.

This diagnostic warns for paths through the code in which a pointer to a buffer is assigned to point at a buffer with a size that is not a multiple of sizeof (*pointer).

See CWE-131: Incorrect Calculation of Buffer Size (https://cwe.mitre.org/data/definitions/131.html).

  • -Wno-analyzer-deref-before-check โ€” this warning requires -fanalyzer, which enables it; use -Wno-analyzer-deref-before-check to disable it.

This diagnostic warns for paths through the code in which a pointer is checked for NULL after it has already been dereferenced, which suggests the pointer could have been NULL. Cases like this suggest that the check for NULL is either redundant, or that it needs to be moved to before the pointer is dereferenced.

It also considers values passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value, and thus will complain if such values are checked for NULL after returning from such a function call.

Ngl this diagnostic is unlikely to be reported when any level of optimization is enabled, because GCC's optimization logic will typically consider such checks for NULL as redundant and optimize them away before the analyzer ever "sees" them. So if you wanna trigger it, disable optimization. ๐Ÿ™ˆ

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

See CWE-1341: Multiple Releases of Same Resource or Handle (https://cwe.mitre.org/data/definitions/1341.html).

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

See CWE-415: Double Free (https://cwe.mitre.org/data/definitions/415.html).

  • -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 (like writing a password to a log file ๐Ÿ˜ฌ).

See CWE-532: Information Exposure Through Log Files (https://cwe.mitre.org/data/definitions/532.html).

  • -Wanalyzer-exposure-through-uninit-copy โ€” this warning requires both -fanalyzer and the use of a plugin to specify a function that copies across a "trust boundary". Use -Wno-analyzer-exposure-through-uninit-copy to disable it.

This diagnostic warns for "infoleaks" โ€” paths through the code in which uninitialized values are copied across a security boundary (like code within an OS kernel that copies a partially-initialized struct on the stack to user space ๐Ÿ’€).

See CWE-200: Exposure of Sensitive Information to an Unauthorized Actor (https://cwe.mitre.org/data/definitions/200.html).

  • -Wno-analyzer-fd-access-mode-mismatch โ€” this warning requires -fanalyzer, which enables it; use -Wno-analyzer-fd-access-mode-mismatch to disable it.

This diagnostic warns for paths through code in which a read on a write-only file descriptor is attempted, or vice versa.

...and it also yells at you when a function tagged with fd_arg_read (N) gets called with a file descriptor that was opened with O_WRONLY at referenced argument N, or when a function tagged with fd_arg_write (N) gets a file descriptor opened with O_RDONLY at referenced argument N. Like bestie the analyzer read your intent and your actual open call and they are NOT texting back. ๐Ÿ’€

  • -Wno-analyzer-fd-double-close โ€” okay so this warning only exists if -fanalyzer is on (that's what enables it), so you'd use -Wno-analyzer-fd-double-close to turn it off.

This diagnostic warns you about code paths where a file descriptor can be closed more than once. Closing it once: fine. Closing it twice: chaos. ๐Ÿ™ˆ

See CWE-1341: Multiple Releases of Same Resource or Handle (https://cwe.mitre.org/data/definitions/1341.html).

  • -Wno-analyzer-fd-leak โ€” requires -fanalyzer (it's the thing enabling it, bestie); use -Wno-analyzer-fd-leak to disable it.

This diagnostic warns for paths through your code where an open file descriptor just... gets leaked. Nobody closes it. It's still out here holding a slot. ๐Ÿ˜ญ

See CWE-775: Missing Release of File Descriptor or Handle after Effective Lifetime (https://cwe.mitre.org/data/definitions/775.html).

  • -Wno-analyzer-fd-phase-mismatch โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-fd-phase-mismatch to disable it.

This diagnostic warns for paths through code where you attempt an operation in the wrong phase of a file descriptor's lifetime. The classic: trying to call accept on a stream socket that hasn't had listen successfully called on it yet. Ma'am, the socket isn't even listening. ๐ŸŽ€

See CWE-666: Operation on Resource in Wrong Phase of Lifetime (https://cwe.mitre.org/data/definitions/666.html).

  • -Wno-analyzer-fd-type-mismatch โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-fd-type-mismatch to disable it.

This diagnostic warns for paths through code where you attempt an operation on the wrong type of file descriptor. For example it'll warn when you try socket operations on a file descriptor you got from open, or when you try to use a stream socket operation on a datagram socket. Different species, bestie. ๐Ÿฆ‹

  • -Wno-analyzer-fd-use-after-close โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-fd-use-after-close to disable it.

This diagnostic warns for paths through code where a read or write is called on a closed file descriptor. It's giving "texting your ex after the breakup," ngl.

It also warns for paths through code where a function tagged with fd_arg (N), fd_arg_read (N) or fd_arg_write (N) is called with a closed file descriptor at referenced argument N.

  • -Wno-analyzer-fd-use-without-check โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-fd-use-without-check to disable it.

This diagnostic warns for paths through code where a file descriptor is used without ever being checked for validity. Do we even know this fd is valid? No. And yet we're using it. Bold. ๐ŸŒˆ

It also warns for paths through code where a function tagged with fd_arg (N), fd_arg_read (N) or fd_arg_write (N) is called with a file descriptor at referenced argument N without being checked for validity.

  • -Wno-analyzer-file-leak โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-file-leak to disable it.

This diagnostic warns for paths through the code where a <stdio.h> FILE * stream object gets leaked. That FILE * is just out there, un-fclosed, living its life. โœจ

See CWE-775: Missing Release of File Descriptor or Handle after Effective Lifetime (https://cwe.mitre.org/data/definitions/775.html).

  • -Wno-analyzer-free-of-non-heap โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-free-of-non-heap to disable it.

This diagnostic warns for paths through the code where free is called on a non-heap pointer โ€” like an on-stack buffer, or a global. free only takes heap pointers, bestie, please don't hand it a stack address. ๐Ÿ˜ญ

See CWE-590: Free of Memory not on the Heap (https://cwe.mitre.org/data/definitions/590.html).

  • -Wno-analyzer-imprecise-fp-arithmetic โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-imprecise-fp-arithmetic to disable it.

This diagnostic warns for paths through the code where floating-point arithmetic is used in places where precise computation is needed. Heads up: at the moment this diagnostic only warns on floating-point operands used inside the calculation of an allocation size. That's the whole scope rn.

  • -Wno-analyzer-infinite-recursion โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-infinite-recursion to disable it.

This diagnostics warns for paths through the code which appear to lead to infinite recursion. ๐ŸŒ€

Specifically, when the analyzer "sees" a recursive call, it compares the state of memory at the entry to the new frame with the state at the entry to the previous frame of that function on the stack. The warning fires if nothing in memory appears to be changing. Any changes it observes to parameters or globals are assumed to lead to termination of the recursion, and that suppresses the warning.

Fr fr, this diagnostic is likely to miss cases of infinite recursion that got converted to iteration by the optimizer before the analyzer "sees" them. So optimization should be disabled when you're trying to trigger this diagnostic.

Compare with -Winfinite-recursion, which gives a similar diagnostic but is implemented in a different way.

  • -Wno-analyzer-jump-through-null โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-jump-through-null to disable it.

This diagnostic warns for paths through the code where a NULL function pointer is called. A NULL pointer at the call site is giving "calling an empty contact," and it never ends well. ๐Ÿ’€

  • -Wno-analyzer-malloc-leak โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-malloc-leak to disable it.

This diagnostic warns for paths through the code where a pointer allocated via an allocator is leaked: either malloc, or a function marked with attribute malloc.

See CWE-401: Missing Release of Memory after Effective Lifetime (https://cwe.mitre.org/data/definitions/401.html).

  • -Wno-analyzer-mismatching-deallocation โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-mismatching-deallocation to disable it.

This diagnostic warns for paths through the code where the wrong deallocation function is called on a pointer value, based on which function was used to allocate that pointer value. It'll warn about mismatches between free, scalar delete and vector delete[], and those marked as allocator/deallocator pairs using attribute malloc. You cannot malloc and then delete[], babes. The analyzer WILL notice. ๐Ÿ‘‘

See CWE-762: Mismatched Memory Management Routines (https://cwe.mitre.org/data/definitions/762.html).

  • -Wno-analyzer-out-of-bounds โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-out-of-bounds to disable it.

This diagnostic warns for paths through the code where a buffer is definitely read or written out-of-bounds. It applies to cases where the analyzer can determine a constant offset, and for accesses past the end of a buffer that also has a constant capacity. And further, it does limited checking for accesses past the end when the offset as well as the capacity is symbolic.

See CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer (https://cwe.mitre.org/data/definitions/119.html).

  • -Wno-analyzer-possible-null-argument โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-possible-null-argument to disable it.

This diagnostic warns for paths through the code where a possibly-NULL value is passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. The attribute said no NULLs and you said "maybe NULL tho." Rude, honestly. ๐Ÿซถ

See CWE-690: Unchecked Return Value to NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/690.html).

  • -Wno-analyzer-possible-null-dereference โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-possible-null-dereference to disable it.

This diagnostic warns for paths through the code where a possibly-NULL value is dereferenced. Possible is enough to make the analyzer nervous, and honestly, same.

See CWE-690: Unchecked Return Value to NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/690.html).

  • -Wno-analyzer-null-argument โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-null-argument to disable it.

This diagnostic warns for paths through the code where a value known to be NULL is passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. No "maybe" here โ€” the analyzer literally knows. Caught in 4K. ๐Ÿ“ธ

See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/476.html).

  • -Wno-analyzer-null-dereference โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-null-dereference to disable it.

This diagnostic warns for paths through the code where a value known to be NULL is dereferenced. Straight to NULL at address zero, no cap. ๐Ÿ’…

See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/definitions/476.html).

  • -Wno-analyzer-putenv-of-auto-var โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-putenv-of-auto-var to disable it.

This diagnostic warns for paths through the code where a call to putenv is passed a pointer to an automatic variable or an on-stack buffer. That stack memory's gonna vanish the second the function returns, and the environment will be left holding a stale pointer. Iconic in the worst way. ๐Ÿ˜ญ

See POS34-C. Do not call putenv() with a pointer to an automatic variable as the argument (https://wiki.sei.cmu.edu/confluence/x/6NYxBQ).

  • -Wno-analyzer-shift-count-negative โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-shift-count-negative to disable it.

This diagnostic warns for paths through the code where a shift is attempted with a negative count. It's analogous to the -Wshift-count-negative diagnostic implemented in the C/C++ front ends, but this one is implemented by analyzing interprocedural paths instead of merely parsing the syntax tree. However โ€” and this is the tea โ€” the analyzer does not prioritize detection of such paths, so false negatives are more likely here relative to other warnings. ๐Ÿ“

  • -Wno-analyzer-shift-count-overflow โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-shift-count-overflow to disable it.

Okay bestie, quick PSA before we dive in: this one is about shift counts! ๐Ÿ’…

This diagnostic yells at you for paths through your code where a shift gets attempted with a count that's greater than or equal to the precision of the operand's type. It's like the cousin of the -Wshift-count-overflow diagnostic that lives in the C/C++ front ends โ€” except this one is built from analyzing interprocedural paths instead of just vibing with the syntax tree. ๐Ÿ™ˆ But here's the tea: the analyzer does not prioritize spotting these paths, so false negatives are more likely here compared to other warnings. F in the chat. ๐Ÿ˜ญ


  • -Wno-analyzer-stale-setjmp-buffer โ€” this one needs -fanalyzer to even exist (that flag turns it on); hit it with -Wno-analyzer-stale-setjmp-buffer to switch it off. ๐Ÿ”‡

It warns about paths through the code where longjmp gets called to rewind back to a jmp_buf that belongs to a setjmp call inside a function that has already returned. ๐Ÿ’€

When setjmp is called on a jmp_buf to record a rewind location, it records the stack frame. And that stack frame becomes invalid the moment the function containing the setjmp call returns. So trying to rewind to it via longjmp would reference a stack frame that literally does not exist anymore, and that's probably gonna crash (or do something even worse ๐Ÿ‘€).

  • -Wno-analyzer-tainted-allocation-size โ€” needs both -fanalyzer and -fanalyzer-checker=taint to enable it; use -Wno-analyzer-tainted-allocation-size to disable it.

Warns about paths where a value that could be under an attacker's control gets used as the size of an allocation without being sanitized first โ€” so an attacker could inject a comically large allocation and potentially cause a denial of service attack. Not it. ๐Ÿ˜ค

See CWE-789: Memory Allocation with Excessive Size Value (https://cwe.mitre.org/data/definitions/789.html).

  • -Wno-analyzer-tainted-assertion โ€” needs both -fanalyzer and -fanalyzer-checker=taint to enable it; use -Wno-analyzer-tainted-assertion to disable it.

Warns about paths where a value that could be under an attacker's control gets used as part of a condition without being sanitized first, and that condition guards a call to a function marked with the noreturn attribute (like __builtin_unreachable). Those functions usually mean the program is terminating abnormally, like an assertion failure handler. For example:

assert (some_tainted_value < SOME_LIMIT);

In such cases:

  • when assertion-checking is enabled: an attacker could trigger a denial of service by injecting an assertion failure ๐Ÿ˜ต
  • when assertion-checking is disabled, like by defining NDEBUG: an attacker could inject data that subverts the process, since it presumably violates a precondition the code is assuming. spooky fr fr ๐Ÿ‘ป
Heads up ๐Ÿซถ: when assertion-checking is disabled, the assertions usually get removed by the preprocessor before the analyzer even has a chance to "see" them โ€” so this diagnostic can only generate warnings on builds where assertion-checking is enabled.

For this warning's purposes, any function marked with the noreturn attribute counts as a possible assertion failure handler, including __builtin_unreachable. And ngl, those functions are sometimes removed by the optimizer before the analyzer "sees" them either โ€” so you should disable optimization when you're trying to trigger this diagnostic. ๐Ÿ™

See CWE-617: Reachable Assertion (https://cwe.mitre.org/data/definitions/617.html).

It can also flag constructions like this:

switch (some_tainted_value) {
case 0:
  /* [...etc; various valid cases omitted...] */
  break;

default:
  __builtin_unreachable (); /* BUG: attacker can trigger this  */
}

...even though, strictly speaking, that's technically not an assertion failure. ๐Ÿ’โ€โ™€๏ธ

  • -Wno-analyzer-tainted-array-index โ€” needs both -fanalyzer and -fanalyzer-checker=taint to enable it; use -Wno-analyzer-tainted-array-index to disable it.

Warns about paths where a value that could be under an attacker's control gets used as the index of an array access without being sanitized, so an attacker could inject an out-of-bounds access. ๐Ÿšจ

See CWE-129: Improper Validation of Array Index (https://cwe.mitre.org/data/definitions/129.html).

  • -Wno-analyzer-tainted-divisor โ€” needs both -fanalyzer and -fanalyzer-checker=taint to enable it; use -Wno-analyzer-tainted-divisor to disable it.

Warns about paths where a value that could be under an attacker's control gets used as the divisor in a division or modulus operation without being sanitized โ€” so an attacker could inject a division-by-zero. โž—๐Ÿ’ฅ

See CWE-369: Divide By Zero (https://cwe.mitre.org/data/definitions/369.html).

  • -Wno-analyzer-tainted-offset โ€” needs both -fanalyzer and -fanalyzer-checker=taint to enable it; use -Wno-analyzer-tainted-offset to disable it.

Warns about paths where a value that could be under an attacker's control gets used as a pointer offset without being sanitized, so an attacker could inject an out-of-bounds access. ๐ŸŽฏ

See CWE-823: Use of Out-of-range Pointer Offset (https://cwe.mitre.org/data/definitions/823.html).

  • -Wno-analyzer-tainted-size โ€” needs both -fanalyzer and -fanalyzer-checker=taint to enable it; use -Wno-analyzer-tainted-size to disable it.

Warns about paths where a value that could be under an attacker's control gets used as the size of an operation like memset without being sanitized, so an attacker could inject an out-of-bounds access. ๐Ÿซ 

See CWE-129: Improper Validation of Array Index (https://cwe.mitre.org/data/definitions/129.html).

  • -Wno-analyzer-unsafe-call-within-signal-handler โ€” this one needs -fanalyzer to even exist (that flag enables it); use -Wno-analyzer-unsafe-call-within-signal-handler to disable it.

Warns about paths where a function that's known to be async-signal-unsafe (like fprintf) gets called from a signal handler. โšก๐Ÿ™…โ€โ™€๏ธ

See CWE-479: Signal Handler Use of a Non-reentrant Function (https://cwe.mitre.org/data/definitions/479.html).

  • -Wno-analyzer-use-after-free โ€” needs -fanalyzer to enable it; use -Wno-analyzer-use-after-free to disable it.

Warns about paths where a pointer gets used after a deallocator was called on it โ€” either free, or a deallocator referenced by the malloc attribute. ๐Ÿ—‘๏ธ๐Ÿ‘€

See CWE-416: Use After Free (https://cwe.mitre.org/data/definitions/416.html).

  • -Wno-analyzer-use-of-pointer-in-stale-stack-frame โ€” needs -fanalyzer to enable it; use -Wno-analyzer-use-of-pointer-in-stale-stack-frame to disable it.

Warns about paths where a pointer gets dereferenced that points to a variable sitting in a stale stack frame. ๐Ÿฅ€

  • -Wno-analyzer-va-arg-type-mismatch โ€” needs -fanalyzer to enable it; use -Wno-analyzer-va-arg-type-mismatch to disable it.

Warns about interprocedural paths where the analyzer catches an attempt to use va_arg to extract a value passed to a variadic call, but with a type that does not match the type of the expression that was passed to the call. ๐Ÿ™ƒ

See CWE-686: Function Call With Incorrect Argument Type (https://cwe.mitre.org/data/definitions/686.html).

  • -Wno-analyzer-va-list-exhausted โ€” needs -fanalyzer to enable it; use -Wno-analyzer-va-list-exhausted to disable it.

Warns about interprocedural paths where the analyzer catches an attempt to use va_arg to access the next value passed to a variadic call โ€” except all the values in the va_list have already been consumed. ๐Ÿฝ๏ธโŒ

See CWE-685: Function Call With Incorrect Number of Arguments (https://cwe.mitre.org/data/definitions/685.html).

  • -Wno-analyzer-va-list-leak โ€” needs -fanalyzer to enable it; use -Wno-analyzer-va-list-leak to disable it.

Warns about interprocedural paths where the analyzer catches that va_start or va_copy got called on a va_list with no matching call to va_end. ๐Ÿšฐ๐Ÿ’ง

  • -Wno-analyzer-va-list-use-after-va-end โ€” needs -fanalyzer to enable it; use -Wno-analyzer-va-list-use-after-va-end to disable it.

Warns about interprocedural paths where the analyzer catches an attempt to use a va_list after va_end has been called on it. va_list. ๐Ÿ’€

  • -Wno-analyzer-write-to-const โ€” needs -fanalyzer to enable it; use -Wno-analyzer-write-to-const to disable it.

Warns about paths where the analyzer catches an attempt to write through a pointer to a const object. But again, the analyzer does not prioritize detecting these paths, so false negatives are more likely compared to other warnings. ๐Ÿซฃ

  • -Wno-analyzer-write-to-string-literal โ€” needs -fanalyzer to enable it; use -Wno-analyzer-write-to-string-literal to disable it.

Warns about paths where the analyzer catches an attempt to write through a pointer to a string literal. And same deal โ€” no prioritization, so false negatives are more likely relative to other warnings. โœ๏ธ๐Ÿšซ

  • -Wno-analyzer-use-of-uninitialized-value โ€” needs -fanalyzer to enable it; use -Wno-analyzer-use-of-uninitialized-value to disable it.

Warns about paths where an uninitialized value is used. ๐Ÿ˜ฌ

See CWE-457: Use of Uninitialized Variable (https://cwe.mitre.org/data/definitions/457.html).


So yeah, the analyzer has hardcoded knowledge about the behavior of the following memory-management functions: โœจ to be continued โœจ ๐ŸŒˆ

Continuing the analyzer's little black book of functions it already knows the tea on, because it's nosy like that ๐Ÿ’…:

  • alloca โ€” yeah bestie, it knows this one intimately
  • the built-in functions __builtin_alloc, __builtin_alloc_with_align, __builtin_calloc, __builtin_free, __builtin_malloc, __builtin_memcpy, __builtin_memcpy_chk, __builtin_memset, __builtin_memset_chk, __builtin_realloc, __builtin_stack_restore, and __builtin_stack_save
  • calloc
  • free
  • malloc
  • memset
  • operator delete
  • operator delete []
  • operator new
  • operator new []
  • realloc
  • strdup
  • strndup

...and it's equally obsessed with these file-descriptor besties:

  • open
  • close
  • creat
  • dup, dup2 and dup3
  • isatty
  • pipe, and pipe2
  • read
  • write
  • socket, bind, listen, accept, and connect

...and it keeps receipts on these <stdio.h> stream functions too ๐ŸŽ€:

  • the built-in functions __builtin_fprintf, __builtin_fprintf_unlocked, __builtin_fputc, __builtin_fputc_unlocked, __builtin_fputs, __builtin_fputs_unlocked, __builtin_fwrite, __builtin_fwrite_unlocked, __builtin_printf, __builtin_printf_unlocked, __builtin_putc, __builtin_putchar, __builtin_putchar_unlocked, __builtin_putc_unlocked, __builtin_puts, __builtin_puts_unlocked, __builtin_vfprintf, and __builtin_vprintf
  • fopen
  • fclose
  • ferror
  • fgets
  • fgets_unlocked
  • fileno
  • fread
  • getc
  • getchar
  • fprintf
  • printf
  • fwrite

...and also, respectfully, these ones ๐Ÿ‘‘:

  • the built-in functions __builtin_expect, __builtin_expect_with_probability, __builtin_strchr, __builtin_strcpy, __builtin_strcpy_chk, __builtin_strlen, __builtin_va_copy, and __builtin_va_start
  • the GNU extensions error and error_at_line
  • getpass
  • longjmp
  • putenv
  • setjmp
  • siglongjmp
  • signal
  • sigsetjmp
  • strchr
  • strlen

Bonus lore: a whole bunch of functions with an __analyzer_ prefix have special meaning to the analyzer too, and the deets on those live in the GCC Internals manual. iykyk โœจ

The pertinent parameters for controlling the exploration (aka how far it's willing to wander off) are:

  • --param analyzer-bb-explosion-factor=value
  • --param analyzer-max-enodes-per-program-point=value
  • --param analyzer-max-recursion-depth=value
  • --param analyzer-min-snodes-for-call-summary=value

The following options control the analyzer. Strap in ๐Ÿ’–

  • -fanalyzer-call-summaries โ€” simplifies interprocedural analysis by computing the effect of certain calls, instead of going on a whole side quest through every single path from callsite to each possible return. If it's 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). Basically it only summarises the messy ones fr fr.
  • -fanalyzer-checker=name โ€” restricts the analyzer to run just the named checker, and enables it. Some checkers are off by default (even with -fanalyzer), like the taint checker that implements -Wanalyzer-tainted-array-index, and you need this option to wake them up.
Note: currently, -fanalyzer-checker=taint disables the following warnings from -fanalyzer:
  • -Wanalyzer-deref-before-check
  • -Wanalyzer-double-fclose
  • -Wanalyzer-double-free
  • -Wanalyzer-exposure-through-output-file
  • -Wanalyzer-fd-access-mode-mismatch
  • -Wanalyzer-fd-double-close
  • -Wanalyzer-fd-leak
  • -Wanalyzer-fd-use-after-close
  • -Wanalyzer-fd-use-without-check
  • -Wanalyzer-file-leak
  • -Wanalyzer-free-of-non-heap
  • -Wanalyzer-malloc-leak
  • -Wanalyzer-mismatching-deallocation
  • -Wanalyzer-null-argument
  • -Wanalyzer-null-dereference
  • -Wanalyzer-possible-null-argument
  • -Wanalyzer-possible-null-dereference
  • -Wanalyzer-unsafe-call-within-signal-handler
  • -Wanalyzer-use-after-free
  • -Wanalyzer-va-list-leak
  • -Wanalyzer-va-list-use-after-va-end
  • -fno-analyzer-feasibility โ€” this one is for analyzer developers, bestie, not for the rest of us. By default the analyzer checks that there's actually a feasible control flow path for each diagnostic it emits: that the conditions holding are not mutually exclusive. Any diagnostic with no feasible path found gets rejected. You can suppress that filtering with -fno-analyzer-feasibility, for debugging issues in this code.
  • -fanalyzer-fine-grained โ€” also for analyzer developers ๐Ÿงš. Internally the analyzer builds an "exploded graph" that combines control flow graphs with data flow information. By default, an edge in this graph can contain the effects of a run of multiple statements within a basic block. With -fanalyzer-fine-grained, every single statement gets its own edge. No sharing.
  • -fanalyzer-show-duplicate-count โ€” analyzer developers only: if multiple diagnostics were detected as duplicates of each other, it emits a note when reporting the best diagnostic, telling you the number of additional diagnostics that got suppressed by the deduplication logic. It's like "and 12 others ๐Ÿ™ˆ".
  • -fno-analyzer-state-merge โ€” analyzer developers only. By default the analyzer tries to keep things cute and simple 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 โ€” analyzer developers only. By default the analyzer simplifies analysis by purging aspects of state at a program point that look like they don't matter anymore, e.g. the values of locals that aren't accessed later in the function and aren't relevant to leak analysis. With -fno-analyzer-state-purge that purging can be suppressed, for debugging state-handling issues.
  • -fno-analyzer-suppress-followups โ€” analyzer developers only. By default the analyzer stops exploring an execution path after it hits certain diagnostics, so it doesn't spiral into a whole cascade of follow-up diagnostics. The diagnostics that terminate analysis along a path are:
    • -Wanalyzer-null-argument
    • -Wanalyzer-null-dereference
    • -Wanalyzer-use-after-free
    • -Wanalyzer-use-of-pointer-in-stale-stack-frame
    • -Wanalyzer-use-of-uninitialized-value

With -fno-analyzer-suppress-followups the analyzer keeps exploring those paths even after such diagnostics, which can help for debugging issues in the analyzer, or for microbenchmarks for detecting undefined behavior. Chaotic but valid.

  • -fanalyzer-transitivity โ€” this option enables transitivity of constraints within the analyzer. Math girlies rise ๐ŸŒธ
  • -fno-analyzer-undo-inlining โ€” analyzer developers only. -fanalyzer runs relatively late compared to other code analysis tools, and some optimizations have already been applied to the code. In particular function inlining may have occurred, which means the interprocedural execution paths the analyzer emits can contain function frames that don't correspond to the ones in the original source code ๐Ÿ˜ญ. By default the analyzer tries to reconstruct the original function frames, and to emit events showing the inlined calls. With -fno-analyzer-undo-inlining that attempt at reconstructing the original frame info can be disabled, which may help when debugging issues in the analyzer.
  • -fanalyzer-verbose-edges โ€” analyzer developers only. Enables more verbose, lower-level detail in the descriptions of control flow within diagnostic paths. It's giving unhinged levels of detail, respectfully.
  • -fanalyzer-verbose-state-changes โ€” analyzer developers only. Enables more verbose, lower-level detail in the descriptions of events relating to state machines within diagnostic paths.
  • -fanalyzer-verbosity=level โ€” this controls the complexity of the control flow paths that get emitted for analyzer diagnostics. The level can be one of:
    • 0 โ€” at this level, interprocedural call and return events are displayed, along with the most pertinent state-change events relating to a diagnostic. For example, for a double-free diagnostic, both calls to free will be shown.
    • 1 โ€” as per the previous level, but also show events for the entry to each function.
    • 2 โ€” as per the previous level, but also show events relating to control flow that are significant to triggering the issue (e.g. "true path taken" at a conditional). This level is the default.
    • 3 โ€” as per the previous level, but show all control flow events, not just significant ones.
    • 4 โ€” this level is intended for analyzer developers; it adds various other events intended for debugging the analyzer.
  • -fdump-analyzer โ€” dumps internal details about what the analyzer is doing to file.analyzer.txt. Careful tho: -fdump-analyzer-stderr overrides this option.
  • -fdump-analyzer-stderr โ€” dumps internal details about what the analyzer is doing to stderr. This option overrides -fdump-analyzer. It wins, periodt.
  • -fdump-analyzer-callgraph โ€” dumps a representation of the call graph suitable for viewing with GraphViz to file.callgraph.dot. Pretty graphs, we love to see it ๐Ÿฆ‹
  • -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. Aesthetic and informative โœจ
  • -fdump-analyzer-exploded-nodes โ€” emits diagnostics showing where nodes in the "exploded graph" are in relation to the program source.
  • -fdump-analyzer-exploded-nodes-2 โ€” dumps a textual representation of the "exploded graph" to file.eg.txt.
  • -fdump-analyzer-exploded-nodes-3 โ€” dumps a textual representation of the "exploded graph" to one dump file per node, to file.eg-id.txt. Heads up bestie: this is typically a large number of dump files ๐Ÿ’€
  • -fdump-analyzer-exploded-paths โ€” dumps a textual representation of the "exploded path" for each diagnostic to file.idx.kind.epath.txt.
  • -fdump-analyzer-feasibility โ€” dumps internal details about the analyzer's search for feasible paths. The details are written in a form suitable for viewing with GraphViz to filenames of the form file.*.fg.dot, file.*.tg.dot, and file.*.fpath.txt.
  • -fdump-analyzer-json โ€” dumps a compressed JSON representation of the analyzer's internal organs into file.analyzer.json.gz. ๐Ÿ’… heads up bestie: the precise format is subject to change, so don't you dare build a parser on it and then come crying to me.
  • -fdump-analyzer-state-purge โ€” same energy as -fdump-analyzer-supergraph, it dumps a representation of the "supergraph" that's suitable for viewing with GraphViz, except this one annotates the graph with info on what state will be purged at each node. ๐Ÿงš It gets written to file.state-purge.dot.
  • -fdump-analyzer-supergraph โ€” dumps representations of the "supergraph" so you can view them with GraphViz, going 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 the diagnostics associated with them. iconic.
  • -fdump-analyzer-untracked โ€” emits custom warnings with internal details, literally intended for analyzer developers. ๐Ÿซถ if that's not you, enjoy the mystery.

๐ŸŒธ Options for Debugging Your Program ๐ŸŒธ

okay so to tell GCC to emit extra info for a debugger, in almost all cases you just add -g to your other options. Some debug formats can co-exist (like DWARF with CTF) when each of them is enabled explicitly by adding the respective command line option to your other options. ๐Ÿ’–

GCC lets you use -g with -O. The shortcuts taken by optimized code may occasionally be surprising, and I'm not gonna lie to you: 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. no cap.

If you're not using some other optimization option, consider using -Og with -g. With no -O option at all, some compiler passes that collect information useful for debugging 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 -gvms (see below).

  • -ggdb โ€” produces debugging information for use by GDB. This means using 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's 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. the way the names are just โœจ legacy โœจ, we love her.

  • -gbtf โ€” requests BTF debug information. BTF is the default debugging format for the eBPF target. On other targets, like x86, BTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options. ๐Ÿ’œ
  • -gctf
  • -gctflevel โ€” requests CTF debug information and uses level to specify how much CTF debug information should be produced. If -gctf is specified without a value for level, the default level of CTF debug information is 2. ๐ŸŽ€

CTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options.

Level 0 produces no CTF debug information at all. Thus, -gctf0 negates -gctf. ๐Ÿ’€

Level 1 produces CTF information for tracebacks only. This includes callsite information, but does not include type information.

Level 2 produces type information for entities (functions, data objects etc.) at file-scope or global-scope only. โญ

  • -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
  • -gvmslevel โ€” requests debugging information and also uses level to specify how much information. The default level is 2. ๐ŸŒธ

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

  • -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. ๐Ÿ’–
  • -femit-class-debug-always โ€” instead of emitting debugging information for a C++ class in only one object file, emit it in all object files using the class. This option should be used only with debuggers that are unable to handle the way GCC normally emits debugging information for classes because using this option increases the size of debugging information by as much as a factor of two. ๐Ÿ˜ญ so like, know what you're doing.
  • -fno-merge-debug-strings โ€” directs the linker to not merge together strings in the debugging information that are identical in different object files. Merging is not supported by all assemblers or linkers. Merging decreases the size of the debug information in the output file at the cost of increasing link processing time. Merging is enabled by default. โœจ
  • -fdebug-prefix-map=old=new โ€” when compiling files residing in directory old, record debugging information describing them as if the files resided in directory new instead. This can be used to replace a build-time path with an install-time path in the debug info. It can also be used to change an absolute path to a relative path by using . for new. This can give more reproducible builds, which are location independent, but may require an extra command to tell GDB where to find the source files. See also -ffile-prefix-map and -fcanon-prefix-map. ๐Ÿฆ‹
  • -fvar-tracking โ€” runs the variable tracking pass. It computes where variables are stored at each position in code. Better debugging information is then generated (if the debugging information format supports this information). ๐Ÿ’…

It is enabled by default when compiling 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 the compilation and attempts to carry the annotations over throughout the compilation all the way to the end, in an attempt to improve debug information while optimizing. Use of -gdwarf-4 is recommended along with it. โญ

It can be enabled even if var-tracking is disabled, in which case annotations are created and maintained, but discarded at the end. By default, this flag is enabled together with -fvar-tracking, except when selective scheduling is enabled. ๐Ÿ‘‘

  • -gsplit-dwarf โ€” if DWARF debugging information is enabled, separate as much debugging information as possible into a separate output file with the extension .dwo. This option allows the build system to avoid linking files with debug information. To be useful, this option requires a debugger capable of reading .dwo files. ๐ŸŽ€
  • -gdwarf32
  • -gdwarf64 โ€” if DWARF debugging information is enabled, -gdwarf32 selects the 32-bit DWARF format and -gdwarf64 selects the 64-bit DWARF format. The default is target specific, on most targets it is -gdwarf32 though. The 32-bit DWARF format is smaller, but can't support more than 2GiB of debug information in any of the DWARF debug information sections. The 64-bit DWARF format allows larger debug information and might not be well supported by all consumers yet. ๐Ÿ’€
  • -gdescribe-dies โ€” adds description attributes to some DWARF DIEs that have no name attribute, such as artificial variables, external references and call site parameter DIEs. ๐Ÿงš
  • -gpubnames โ€” generates DWARF .debug_pubnames and .debug_pubtypes sections. โœจ
  • -ggnu-pubnames โ€” generates .debug_pubnames and .debug_pubtypes sections in a format suitable for conversion into a GDB index. This option is only useful with a linker that can produce GDB index version 7. ๐ŸŒˆ
  • -fdebug-types-section โ€” when using DWARF Version 4 or higher, type DIEs can be put into their own .debug_types section instead of making them part of the .debug_info section. It is more efficient to put them in a separate comdat section since the linker can then remove duplicates. But not all DWARF consumers support .debug_types sections yet and on some objects .debug_types produces larger instead of smaller debugging information. ๐Ÿ˜ญ the betrayal fr fr.
  • -grecord-gcc-switches, -gno-record-gcc-switches โ€” okay so bestie, this one shoves the command-line options you used to invoke the compiler (the ones that might affect code generation) straight into the DW_AT_producer attribute in your DWARF debugging info โœจ. They get concatenated together, with spaces separating them from each other and from the compiler version. It's enabled by default, periodt. Also peep -frecord-gcc-switches for a whole other way of stashing compiler options into the object file ๐Ÿ‘€.
  • -gstrict-dwarf โ€” nope, no extensions of a later DWARF standard version than whatever you picked with -gdwarf-version. On most targets, using non-conflicting DWARF extensions from later standard versions is allowed, but not with this flag on. Strict queen ๐Ÿ’….
  • -gno-strict-dwarf โ€” allow using extensions of later DWARF standard versions than the one selected with -gdwarf-version. Live a little ๐ŸŒธ.
  • -gas-loc-support โ€” tells the compiler that your assembler supports ".loc" directives ๐Ÿซถ. Then it may use them so the assembler generates DWARF2+ line number tables for you.

This is generally desirable, because assembler-generated line-number tables are a lot more compact than the ones the compiler can generate itself. Lowkey iconic.

This option gets enabled by default if, at GCC configure time, the assembler was found to support such directives.

  • -gno-as-loc-support โ€” forces GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are going to be generated at all. DIY energy ๐Ÿ”ฅ.
  • -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 โ€” emit location column info into DWARF debugging info, not just file and line ๐Ÿ“. Enabled by default, no cap.
  • -gstatement-frontiers, -gno-statement-frontiers โ€” this makes GCC drop markers into the internal representation at the beginning of statements, and keep them roughly in place all through compilation, using them to guide the output of "is_stmt" markers in the line number table ๐ŸŒˆ. Enabled by default when compiling with optimization (-Os, -O1, -O2, ...), and outputting DWARF 2 debug information at the normal level.
  • -gvariable-location-views, -gvariable-location-views=incompat5, -gno-variable-location-views โ€” augments variable location lists with progressive view numbers implied from the line number table ๐Ÿ‘‘. This lets debug info consumers inspect state at certain points of the program, even if no instructions associated with the corresponding source locations are present at that point. If the assembler lacks support for view numbers in line number tables, this makes the compiler 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 aren't aware of these augmentations can still consume them โ€” they just won't derive any benefit from them either ๐Ÿ™ˆ.

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, this may still be enabled, but it'll force GCC to output internal line number tables, and if -ginternal-reset-location-views isn't 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, which you can turn on with -gvariable-location-views=incompat5. This option may be removed in the future, and is only provided as a reference implementation of the proposed representation. Debug info consumers aren't expected to support this extended format, and they'd be rendered unable to decode location lists using 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 you're using an assembler that doesn't support location view lists. The GNU assembler will flag any such error as a "view number mismatch". This is only enabled on ports that define a reliable estimation function.
  • -ginline-points, -gno-inline-points โ€” generates extended debug info for inlined functions โœจ. Location view tracking markers get inserted at inlined entry points, so address and view numbers can be computed and output in debug info. This can be enabled independently of location views, in which case the view numbers won't be output โ€” but it can only be enabled along with statement frontiers, and it's only enabled by default if location views are enabled ๐ŸŽ€.
  • -gz[=type] โ€” 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 used. type may be one of none (don't compress debug sections), or zlib (use zlib compression in ELF gABI format). If the linker doesn't support writing compressed debug sections, the option is rejected โ€” full stop. Otherwise, if the assembler doesn't support them, -gz is silently ignored when producing object files ๐Ÿ˜ถ.
  • -femit-struct-debug-baseonly โ€” emits debug info for struct-like types only when the base name of the compilation source file matches the base name of the file in which the struct is defined.

This option substantially reduces the size of debugging information, but at significant potential loss in type information to the debugger ๐Ÿ˜ญ. See -femit-struct-debug-reduced for a less aggressive option. See -femit-struct-debug-detailed for more detailed control.

This option works only with DWARF debug output.

  • -femit-struct-debug-reduced โ€” emits debug info for struct-like types only when the base name of the compilation source file matches the base name of the file in which the type is defined, unless the struct is a template or defined in a system header ๐Ÿ’œ.

This option significantly reduces the size of debugging information, with some potential loss in type information to the debugger. See -femit-struct-debug-baseonly for a more aggressive option. See -femit-struct-debug-detailed for more detailed control.

This option works only with DWARF debug output.

  • -femit-struct-debug-detailed[=spec-list] โ€” specifies the struct-like types for which the compiler generates debug info. The intent? Reduce duplicate struct debug info between different object files within the same program ๐ŸŒˆ.

This option is a detailed version of -femit-struct-debug-reduced and -femit-struct-debug-baseonly, which serve most needs.

A specification has the syntax [dir:|ind:][ord:|gen:](any|sys|base|none)

The optional first word limits the specification to structs that are used directly (dir:) or used indirectly (ind:). A struct type is used directly when it's the type of a variable, member. Indirect uses arise through pointers to structs. That is, when use of an incomplete struct is valid, the use is indirect. An example is struct one direct; struct two * indirect;.

The optional second word limits the specification to ordinary structs (ord:) or generic structs (gen:). Generic structs are a bit complicated to explain ๐Ÿ‘€. For C++, these are non-explicit specializations of template classes, or non-template classes within the above. Other programming languages have generics, but -femit-struct-debug-detailed doesn't yet implement them.

The third word specifies the source files for those structs for which the compiler should emit debug info. The values none and any have the normal meaning. The value base means that the base of name of the file in which the type declaration appears must match the base of the name of the main compilation file. In practice, this means that when compiling foo.c, debug info is generated for types declared in that file and foo.h, but not other header files. The value sys means those types satisfying base or declared in system or compiler headers.

You may need to experiment to determine the best settings for your application ๐Ÿงช.

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

This option works only with DWARF debug output.

  • -fno-dwarf2-cfi-asm โ€” emit DWARF unwind info as a compiler-generated ".eh_frame" section instead of using GAS ".cfi_*" directives.
  • -fno-eliminate-unused-debug-types โ€” normally, when producing DWARF output, GCC avoids producing debug symbol output for types that are nowhere used in the source file being compiled. Sometimes it's useful to have GCC emit debugging information for all types declared in a compilation unit, regardless of whether or not they're actually used in that compilation unit โ€” for example if, in the debugger, you want to cast a value to a type that isn't actually used in your program (but is declared) ๐Ÿ’…. More often, however, this results in a significant amount of wasted space ๐Ÿ’€.

๐ŸŒˆ Options That Control Optimization ๐ŸŒˆ

These options control various sorts of optimizations, bestie. Strap in.

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. Chef's kiss predictability.

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

Okay so GCC is out here optimizing based on what it knows about your program. Like, if you compile multiple files at once into a single output file, it can use all that info from every file when it's compiling each one. It's giving โœจcross-file wisdomโœจ.

But lowkey, not every optimization has its own flag, bestie. Only the ones with flags are getting listed in this section. The rest are just vibing in the background.

Most optimizations are fully off at -O0 or if you don't set an -O level at all โ€” even if you specify individual optimization flags. Yeah, it's like that. And -Og also suppresses a bunch of optimization passes. Not me being extra, it's just facts.

And depending on your target and how GCC was configured, the optimizations enabled at each -O level might be a lil different from what's listed here. If you wanna know exactly what's enabled at each level, run gcc -Q --help=optimizers. It's the receipts, periodt.

  • -O, -O1 โ€” Optimize. Optimizing compilation takes somewhat more time, and a lot more memory for a large function.

With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.

-O turns on the following optimization flags:

-fauto-inc-dec -fbranch-count-reg -fcombine-stack-adjustments
-fcompare-elim -fcprop-registers -fdce -fdefer-pop -fdelayed-branch
-fdse -fforward-propagate -fguess-branch-probability -fif-conversion
-fif-conversion2 -finline-functions-called-once -fipa-modref
-fipa-profile -fipa-pure-const -fipa-reference
-fipa-reference-addressable -fmerge-constants -fmove-loop-invariants
-fmove-loop-stores -fomit-frame-pointer -freorder-blocks
-fshrink-wrap -fshrink-wrap-separate -fsplit-wide-types
-fssa-backprop -fssa-phiopt -ftree-bit-ccp -ftree-ccp -ftree-ch
-ftree-coalesce-vars -ftree-copy-prop -ftree-dce
-ftree-dominator-opts -ftree-dse -ftree-forwprop -ftree-fre
-ftree-phiprop -ftree-pta -ftree-scev-cprop -ftree-sink -ftree-slsr
-ftree-sra -ftree-ter -funit-at-a-time
  • -O2 โ€” Optimize even more. GCC performs nearly all supported optimizations that do not involve a space-speed tradeoff. As compared to -O, this option increases both compilation time and the performance of the generated code.

-O2 turns on all optimization flags specified by -O1. It also turns on the following optimization flags:

-falign-functions  -falign-jumps -falign-labels  -falign-loops
-fcaller-saves -fcode-hoisting -fcrossjumping -fcse-follow-jumps
-fcse-skip-blocks -fdelete-null-pointer-checks -fdevirtualize
-fdevirtualize-speculatively -fexpensive-optimizations
-ffinite-loops -fgcse  -fgcse-lm -fhoist-adjacent-loads
-finline-functions -finline-small-functions -findirect-inlining
-fipa-bit-cp  -fipa-cp  -fipa-icf -fipa-ra  -fipa-sra  -fipa-vrp
-fisolate-erroneous-paths-dereference -flra-remat
-foptimize-sibling-calls -foptimize-strlen -fpartial-inlining
-fpeephole2 -freorder-blocks-algorithm=stc
-freorder-blocks-and-partition  -freorder-functions
-frerun-cse-after-loop -fschedule-insns  -fschedule-insns2
-fsched-interblock  -fsched-spec -fstore-merging -fstrict-aliasing
-fthread-jumps -ftree-builtin-call-dce -ftree-loop-vectorize
-ftree-pre -ftree-slp-vectorize -ftree-switch-conversion
-ftree-tail-merge -ftree-vrp -fvect-cost-model=very-cheap
Please note the warning under -fgcse about invoking -O2 on programs that use computed gotos. ๐Ÿ‘€
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.
NOTE: In Debian 13 and Ubuntu 24.04 and later versions, -D_TIME_BITS=64 together with -D_FILE_OFFSET_BITS=64 is set by default on the 32bit architectures armel, armhf, hppa, m68k, mips, mipsel, powerpc and sh4.
  • -O3 โ€” Optimize yet more. -O3 turns on all optimizations specified by -O2 and also turns on the following optimization flags:
-fgcse-after-reload -fipa-cp-clone -floop-interchange
-floop-unroll-and-jam -fpeel-loops -fpredictive-commoning
-fsplit-loops -fsplit-paths -ftree-loop-distribution
-ftree-partial-pre -funswitch-loops -fvect-cost-model=dynamic
-fversion-loops-for-strides
  • -O0 โ€” Reduce compilation time and make debugging produce the expected results. This is the default. ๐Ÿ›
  • -Os โ€” Optimize for size. -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. It's giving minimalism, but make it fast. ๐Ÿ’…

  • -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. It turns off -fsemantic-interposition. YOLO, but for math. ๐Ÿ”ฅ
  • -Og โ€” Optimize 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.

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  -fmove-loop-stores  -fssa-phiopt
-ftree-bit-ccp  -ftree-dse  -ftree-pta  -ftree-sra
  • -Oz โ€” Optimize aggressively for size rather than speed. This may increase the number of instructions executed if those instructions require fewer bytes to encode. -Oz behaves similarly to -Os including enabling most -O2 optimizations. Tiny but mighty. โœจ

If you use multiple -O options, with or without level numbers, the last such option is the one that is effective. So the last one wins, bestie. No take-backs.

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.

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.

  • -fno-defer-pop โ€” For machines that must pop arguments after a function call, always pop the arguments as soon as each function returns. At levels -O1 and higher, -fdefer-pop is the default; this allows the compiler to let arguments accumulate on the stack for several function calls and pop them all at once.
  • -fforward-propagate โ€” Perform a forward propagation pass on RTL. The pass tries to combine two instructions and checks if the result can be simplified. If loop unrolling is active, two passes are performed and the second is scheduled after loop unrolling.

This option is enabled by default at optimization levels -O1, -O2, -O3, -Os.

  • -ffp-contract=style โ€” -ffp-contract=off disables floating-point expression contraction. -ffp-contract=fast enables floating-point expression contraction such as forming of fused multiply-add operations if the target has native support for them. -ffp-contract=on enables floating-point expression contraction if allowed by the language standard. This is currently not implemented and treated equal to -ffp-contract=off.

The default is -ffp-contract=fast.

  • -fomit-frame-pointer โ€” Omit the frame pointer in functions that don't need one. This avoids the instructions to save, set up and restore the frame pointer; on many targets it also makes an extra register available.

On some targets this flag has no effect because the standard calling sequence always uses a frame pointer, so it cannot be omitted.

Note that -fno-omit-frame-pointer doesn't guarantee the frame pointer is used in all functions. Several targets always omit the frame pointer in leaf functions.

Enabled by default at -O1 and higher.

  • -foptimize-sibling-calls โ€” Optimize sibling and tail recursive calls.

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

  • -foptimize-strlen โ€” Optimize various standard C string functions (e.g. strlen, strchr or strcpy) and their _FORTIFY_SOURCE counterparts into faster alternatives.

Enabled at levels -O2, -O3.

  • -fno-inline โ€” Do not expand any functions inline apart from those marked with the always_inline attribute. This is the default when not optimizing.

Single functions can be exempted from inlining by marking them with the noinline attribute.

  • -finline-small-functions โ€” Integrate functions into their callers when their body is smaller than expected function call code (so overall size of program gets smaller). The compiler heuristically decides which functions are simple enough to be worth integrating in this way. This inlining applies to all functions, even those not declared inline.

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

  • -findirect-inlining โ€” Inline also indirect calls that are discovered to be known at compile time thanks to previous inlining. This option has any effect only when inlining itself is turned on by the -finline-functions or -finline-small-functions options.

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

  • -finline-functions โ€” Consider all functions for inlining, even if they are not declared inline. The compiler heuristically decides which functions are worth integrating in this way.

If all calls to a given function are integrated, and the function is declared static, then the function is normally not output as assembler code in its own right.

Enabled at levels -O2, -O3, -Os. Also enabled by -fprofile-use and -fauto-profile.

  • -finline-functions-called-once โ€” bestie, this one says: consider every static function that gets called exactly once for inlining into whoever called it, even if nobody bothered to mark it inline. And the way that works is, if a call to a given function actually gets integrated, then that function doesn't get output as assembler code in its own right anymore. Bye bye, standalone version. ๐Ÿ’…

It's enabled at levels -O1, -O2, -O3 and -Os, but not -Og.

  • -fearly-inlining โ€” so this one inlines functions marked by always_inline, plus functions whose body seems smaller than the function call overhead, and it does all that early โ€” before doing -fprofile-generate instrumentation and the real inlining pass. Why do we care? Because doing it this way makes profiling significantly cheaper, and usually makes inlining faster on programs that have big chains of nested wrapper functions. We love an efficiency queen. โœจ

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. Glow up for your function signatures, fr fr.

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

  • -finline-limit=n โ€” okay so by default GCC limits the size of functions that can be inlined, and this flag gives you coarse control of that limit. n here is the size of functions that can be inlined, counted in number of pseudo instructions. ๐ŸŽ€

Inlining is actually controlled by a whole bunch of parameters, which you can specify individually with --param name=value. The -finline-limit=n option sets some of those parameters like this:

  • max-inline-insns-single โ€” is set to n/2.
  • max-inline-insns-auto โ€” is set to n/2.

See below for documentation of the individual parameters that control inlining, and for the defaults of those parameters.

Note: there may be no value of -finline-limit that results in default behavior. Not me finding out the hard way ๐Ÿ˜ญ
Note: pseudo instruction here means an abstract measurement of a function's size, in this particular context. It is in no way a count of assembly instructions, so its exact meaning might change from one release to another. It's giving vibes-based units, honestly.
  • -fno-keep-inline-dllexport โ€” this is a more fine-grained version of -fkeep-inline-functions, and it only applies to functions declared using the dllexport attribute or declspec. Very specific, very demure. ๐Ÿฆ‹
  • -fkeep-inline-functions โ€” in C, this emits static functions that are declared inline into the object file, even if the function has already been inlined into all of its callers. This switch does not affect functions using the extern inline extension in GNU C90. In C++, it emits any and all inline functions into the object file. Collect them all, I guess. ๐Ÿ’€
  • -fkeep-static-functions โ€” emit static functions into the object file, even if the function is never used. That's right, we keep the unused ones too. Main character energy for functions nobody calls. ๐Ÿ‘‘
  • -fkeep-static-consts โ€” emit variables declared static const when optimization isn't turned on, even if the variables aren't referenced.

GCC enables this option by default. If you want to force the compiler to check whether a variable is referenced โ€” regardless of whether optimization is turned on or not โ€” use the -fno-keep-static-consts option instead.

  • -fmerge-constants โ€” attempts to merge identical constants (string constants and floating-point constants) across compilation units. Twin merge, but it's constants. ๐ŸŒธ

This option is the default for optimized compilation if the assembler and linker support it. Use -fno-merge-constants to inhibit this behavior.

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

  • -fmerge-all-constants โ€” attempts to merge identical constants and identical variables.

This option implies -fmerge-constants. On top of what -fmerge-constants does, it also considers e.g. even constant initialized arrays, or initialized constant variables with integral or floating-point types.

Okay so real talk, this one is non-conforming behavior territory. 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. It's giving "I know what I'm doing" and honestly? Sometimes you do. But you've been warned. ๐Ÿ™ˆ
  • -fmodulo-sched โ€” perform swing modulo scheduling immediately before the first scheduling pass. This pass looks at innermost loops and reorders their instructions by overlapping different iterations. Loops getting a little makeover. โœจ
  • -fmodulo-sched-allow-regmoves โ€” perform more aggressive SMS-based modulo scheduling, with register moves allowed. Setting this flag deletes certain anti-dependences edges, which triggers the generation of reg-moves based on the life-range analysis. Heads up though: this option is only effective when -fmodulo-sched is enabled. They're a package deal, bestie. ๐Ÿซถ
  • -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 on the result.

This option is only meaningful on architectures that support such instructions โ€” which include x86, PowerPC, IA-64 and S/390. Also note that -fno-branch-count-reg does not remove the decrement and branch instructions from the generated instruction stream that were introduced by other optimization passes. It can't undo what's already been done, lowkey.

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

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. Sometimes the chaos is the point.

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. Space saving, we love her. ๐Ÿ’–

This option turns that behavior off, because some programs explicitly rely on variables going to the data section โ€” e.g. so that the resulting executable can find the beginning of that section and/or make assumptions based on that. Respect the weird programs, they have their reasons.

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 either to the destination of the second branch, or to a point immediately following it, depending on whether the condition is known to be true or false. Gymnastics, but for control flow. ๐Ÿคธ

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

  • -fsplit-wide-types โ€” when you're using a type that occupies multiple registers, such as long long on a 32-bit system, this splits the registers apart and allocates them independently. This normally generates better code for those types, but it may make debugging more difficult. Trade-offs, always trade-offs. ๐Ÿ˜ญ

Enabled at levels -O1, -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. Package deal again, keep up bestie.

This is the default on some targets.

  • -fcse-follow-jumps โ€” in common subexpression elimination (CSE), scan through jump instructions when the target of the jump is not reached by any other path. For example, when CSE encounters an if statement with an else clause, CSE follows the jump when the condition tested is false. She's nosy, but productively. ๐Ÿ‘€

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

  • -fcse-skip-blocks โ€” similar to -fcse-follow-jumps, but this one causes CSE to follow jumps that conditionally skip over blocks. When CSE encounters a simple if statement with no else clause, -fcse-skip-blocks causes CSE to follow the jump around the body of the if. Sibling behavior, equally iconic. ๐ŸŒˆ

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

  • -frerun-cse-after-loop โ€” re-runs common subexpression elimination after loop optimizations are performed. Because sometimes you gotta do it twice. Once before the glow-up, once after. ๐Ÿ’…

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

  • -fgcse โ€” performs a global common subexpression elimination pass. This pass also performs global constant and copy propagation. Multi-tasking queen. ๐Ÿ‘‘
Note: when compiling a program that uses computed gotos โ€” a GCC extension โ€” you may get better run-time performance if you disable the global common subexpression elimination pass by adding -fno-gcse to the command line. Just a heads up, iykyk.

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

  • -fgcse-lm โ€” when -fgcse-lm is enabled, global common subexpression elimination attempts to move loads that are only killed by stores into themselves. This allows a loop containing a load/store sequence to be changed into a load outside the loop, and a copy/store within the loop. Moved out of the loop like it's moving out of its hometown. ๐Ÿงš

Enabled by default when -fgcse is enabled.

  • -fgcse-sm โ€” when -fgcse-sm is enabled, a store motion pass is run after global common subexpression elimination. This pass attempts to move stores out of loops. When used in conjunction with -fgcse-lm, loops containing a load/store sequence can be changed to a load before the loop and a store after the loop. Dynamic duo behavior. ๐Ÿซถ

Not enabled at any optimization level.

  • -fgcse-las โ€” when -fgcse-las is enabled, the global common subexpression elimination pass eliminates redundant loads that come after stores to the same memory location โ€” both partial and full redundancies, no cap.

Not enabled at any optimization level.

  • -fgcse-after-reload โ€” when -fgcse-after-reload is enabled, a redundant load elimination pass is performed after reload. The purpose of this pass is to clean up redundant spilling. Cleaning up after the party โœจ

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

  • -faggressive-loop-optimizations โ€” this option tells the loop optimizer to use language constraints to derive bounds for the number of iterations of a loop. This assumes that loop code does not invoke undefined behavior, by for example causing signed integer overflows or out-of-bound array accesses. The bounds for the number of iterations of a loop are used to guide loop unrolling and peeling, and loop exit test optimizations.
It's enabled by default, which means it is assuming no UB is happening in your loops. If your loops are doing crimes, that's on you. ๐Ÿ’€
  • -funconstrained-commons โ€” this option tells the compiler that variables declared in common blocks (e.g. Fortran) may later be overridden with longer trailing arrays. This prevents certain optimizations that depend on knowing the array bounds. Mystery-sized arrays get to stay mysterious. ๐ŸŽ€
  • -fcrossjumping โ€” perform 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. Honestly? Could go either way, and that's the fun of it. ๐Ÿ™ˆ

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

  • -fauto-inc-dec โ€” combine increments or decrements of addresses with memory accesses. This pass is always skipped on architectures that do not have instructions to support this. Enabled by default at -O1 and higher on architectures that support this. Two steps, one move. ๐Ÿ”ฅ
  • -fdce โ€” bestie, this does dead code elimination (DCE) on RTL ๐Ÿงนโœจ like... code that literally never runs? gone. deleted. not invited to the function ๐Ÿ˜Œ It's enabled by default at -O1 and higher.
  • -fdse โ€” dead store elimination (DSE) on RTL ๐Ÿ’€ You're gonna write to a variable and then immediately overwrite it before anyone reads it? girl what was the point. This removes the pointless one. Enabled by default at -O1 and higher.
  • -fif-conversion โ€” okay so this attempts to turn conditional jumps into branch-less equivalents ๐Ÿฆ‹ The glow-up includes conditional moves, min, max, set flags and abs instructions, plus some little tricks doable by standard arithmetics. Whether it uses conditional execution on chips where that's available is controlled by -fif-conversion2.

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

  • -fif-conversion2 โ€” uses conditional execution (where available) to transform conditional jumps into branch-less equivalents ๐Ÿ’… same vibe, different flavor.

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

  • -fdeclone-ctor-dtor โ€” so the C++ ABI requires multiple entry points for constructors and destructors, right? one for a base subobject, one for a complete object, and one for a virtual destructor that calls operator delete afterwards ๐Ÿ˜ตโ€๐Ÿ’ซ And for a hierarchy with virtual bases, the base and complete variants are clones โ€” meaning two whole copies of the function. NOT it.

With this option, the base and complete variants get changed into thunks that call a common implementation. Slay ๐Ÿ’–

Enabled by -Os.

  • -fdelete-null-pointer-checks โ€” assumes programs cannot safely dereference null pointers, and that no code or data element lives at address zero ๐Ÿšซ0๏ธโƒฃ This enables simple constant folding optimizations at all optimization levels. Also, other optimization passes in GCC use this flag to control global dataflow analyses that eliminate useless checks for null pointers โ€” those assume a memory access to address zero always results in a trap, so if a pointer is checked after it's already been dereferenced, it cannot be null.
ngl bestie, in some environments this assumption is simply 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 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 the analysis of the type inheritance graph, it determines for a given call the set of likely targets. If the set is small โ€” preferably of size 1 โ€” it changes the call into a conditional deciding between direct and indirect calls. The speculative calls enable more optimizations, like inlining. And when they seem useless after further optimization, they're converted back into original form. so it's giving "we're just gonna try it, no pressure" ๐Ÿฆ‹
  • -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's disabled by default.
  • -fexpensive-optimizations โ€” performs a number of minor optimizations that are relatively expensive ๐Ÿ’ธโœจ

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. love that for them.

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

  • -fno-lifetime-dse โ€” so 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. iykyk ๐ŸŒธ

  • -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.
  • -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. periodt.
  • -fira-region=region โ€” use 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. trade-offs, bestie ๐Ÿ’…

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 โ€” disables sharing of stack slots used for saving call-used hard registers living through a call ๐Ÿ™ˆ Each hard register gets a separate stack slot, and as a result function stack frames are larger.
  • -fno-ira-share-spill-slots โ€” disables sharing of stack slots allocated for pseudo-registers ๐Ÿ˜ฌ Each pseudo-register that does not get a hard register gets a separate stack slot, and as a result function stack frames are larger.
  • -flra-remat โ€” enables CFG-sensitive rematerialization in LRA โ™ป๏ธ Instead of loading values of spilled pseudos, LRA tries to rematerialize (recalculate) values if it's profitable. iconic behavior honestly.

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

  • -fdelayed-branch โ€” if supported for the target machine, attempts to reorder instructions to exploit instruction slots available after delayed branch instructions ๐ŸŽฏ

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

  • -fschedule-insns โ€” if supported for the target machine, attempts to reorder instructions to eliminate execution stalls due to required data being unavailable ๐Ÿšฆ This helps machines that have slow floating point or memory load instructions by allowing other instructions to be issued until the result of the load or floating-point instruction is required. it's giving "keep everyone busy while we wait" ๐Ÿซถ

Enabled at levels -O2, -O3.

  • -fschedule-insns2 โ€” similar to -fschedule-insns, but requests an additional pass of instruction scheduling after register allocation has been done ๐Ÿ’ซ This is especially useful on machines with a relatively small number of registers and where memory load instructions take more than one cycle.

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

  • -fno-sched-interblock โ€” disables instruction scheduling across basic blocks ๐Ÿ™…โ€โ™€๏ธ which is normally enabled when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher.
  • -fno-sched-spec โ€” disables speculative motion of non-load instructions ๐Ÿ›‘ which is normally enabled when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher.
  • -fsched-pressure โ€” 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 this option can improve the generated code and decrease its size by preventing register pressure increase above the number of available hard registers and the subsequent spills in register allocation.
  • -fsched-spec-load โ€” allows speculative motion of some load instructions ๐Ÿฆ‹ This only makes sense when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher.
  • -fsched-spec-load-dangerous โ€” allows speculative motion of more load instructions ๐Ÿ˜ณ dangerous is literally in the name, bestie. This only makes sense when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher.
  • -fsched-stalled-insns
  • -fsched-stalled-insns=n โ€” 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 that no insns are moved prematurely, -fsched-stalled-insns=0 means there is no limit on how many queued insns can be moved prematurely. And -fsched-stalled-insns without a value is equivalent to -fsched-stalled-insns=1. no cap ๐ŸŒˆ
  • -fsched-stalled-insns-dep, -fsched-stalled-insns-dep=n โ€” bestie, this one decides how many insn groups (aka cycles) get examined looking for a dependency on a stalled insn that's a candidate for premature removal from the queue of stalled insns ๐Ÿซถ. Plot twist: it only does anything during the second scheduling pass, and only if you've also got -fsched-stalled-insns on. And -fno-sched-stalled-insns-dep is literally the same thing as -fsched-stalled-insns-dep=0, while -fsched-stalled-insns-dep with no value at all is the same as -fsched-stalled-insns-dep=1. slay โœจ
  • -fsched2-use-superblocks โ€” when we're scheduling after register allocation, use superblock scheduling ๐Ÿ’…. This lets stuff move across basic block boundaries, which means faster schedules โ€” cute! But ngl it's experimental, bc not every machine description GCC uses models the CPU closely enough to keep this algorithm from giving you unreliable results ๐Ÿ˜ญ. Also it only makes sense when you're scheduling after register allocation, i.e. with -fschedule-insns2 or at -O2 or higher.
  • -fsched-group-heuristic โ€” turns on the group heuristic in the scheduler, which favors the instruction that belongs to a schedule group ๐Ÿ‘‘. It's enabled by default whenever scheduling is on, 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, which favors instructions on the critical path ๐Ÿ”ฅ. Enabled by default whenever scheduling is on, 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, which favors speculative instructions with greater dependency weakness ๐Ÿ’ซ. Enabled by default whenever scheduling is on, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -fsched-rank-heuristic โ€” enables the rank heuristic in the scheduler, which favors the instruction belonging to a basic block with greater size or frequency ๐ŸŒธ. Enabled by default whenever scheduling is on, 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, which favors the instruction that is less dependent on the last instruction scheduled ๐Ÿฆ‹. Enabled by default whenever scheduling is on, 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, which favors the instruction that has more instructions depending on it ๐ŸŽ€. Enabled by default whenever scheduling is on, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.

  • -freschedule-modulo-scheduled-loops โ€” so modulo scheduling happens before traditional scheduling, right? And if a loop is modulo scheduled, the later scheduling passes might still go in and 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 โ€” but this time it runs instead of the second scheduler pass โœจ.
  • -fsel-sched-pipelining โ€” enables software pipelining of innermost loops during selective scheduling ๐ŸŒ€. Heads up: this has literally no effect unless one of -fselective-scheduling or -fselective-scheduling2 is turned on.
  • -fsel-sched-pipelining-outer-loops โ€” when you're pipelining loops during selective scheduling, this also pipelines outer loops ๐Ÿซถ. And same deal: no effect unless -fsel-sched-pipelining is turned on.
  • -fsemantic-interposition โ€” some object formats, like ELF, let the dynamic linker interpose symbols ๐Ÿ‘€. Which means that for symbols exported from the DSO, the compiler cannot do interprocedural propagation, inlining and other optimizations, because it has to assume the function or variable in question might change. While this feature is useful โ€” like, say, to rewrite memory allocation functions with a debugging implementation โ€” it's expensive when it comes to 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. And no cap: this flag has no effect for functions explicitly declared inline (where it is 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 them, instead of up 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 only get executed when they're needed ๐Ÿ’œ. It's on by default, but it has no effect unless -fshrink-wrap is also turned on and the target supports this.
  • -fcaller-saves โ€” enables allocation of values to registers that are clobbered by function calls, by emitting extra instructions to save and restore those registers around such calls ๐Ÿ’พ. That allocation only happens when it looks like it'll result in better code. Also, this option is always enabled by default on certain machines, usually the ones with 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 the 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 โ€” attempt to minimize stack usage. The compiler tries to use less stack space, even if that makes the program slower ๐ŸŒ. This option implies setting the large-stack-frame parameter to 100 and the large-stack-frame-growth parameter to 400.
  • -ftree-reassoc โ€” perform reassociation on trees ๐ŸŒณ. This flag is enabled by default at -O1 and higher.
  • -fcode-hoisting โ€” perform code hoisting. Code hoisting tries to move the evaluation of expressions executed on all paths to the function exit as early as possible โซ. 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 โ€” perform partial redundancy elimination (PRE) on trees ๐ŸŒณโœจ. This flag is enabled by default at -O2 and -O3.
  • -ftree-partial-pre โ€” makes partial redundancy elimination (PRE) more aggressive ๐Ÿ˜ค. This flag is enabled by default at -O3.
  • -ftree-forwprop โ€” perform forward propagation on trees ๐ŸŒฟ. This flag is enabled by default at -O1 and higher.
  • -ftree-fre โ€” perform full redundancy elimination (FRE) on trees ๐ŸŒณ. The difference between FRE and PRE is that FRE only considers expressions that are computed on all paths leading to the redundant computation. This analysis is faster than PRE, though it exposes fewer redundancies. This flag is enabled by default at -O1 and higher.
  • -ftree-phiprop โ€” perform hoisting of loads from conditional pointers on trees โคด๏ธ. This pass is enabled by default at -O1 and higher.
  • -fhoist-adjacent-loads โ€” speculatively hoist loads from both branches of an if-then-else, if the loads are from adjacent locations in the same structure and the target architecture has a conditional move instruction ๐Ÿ‘€. This flag is enabled by default at -O2 and higher.
  • -ftree-copy-prop โ€” perform copy propagation on trees ๐ŸŒฒ. This pass eliminates unnecessary copy operations. This flag is enabled by default at -O1 and higher.
  • -fipa-pure-const โ€” discover which functions are pure or constant ๐Ÿงš. Enabled by default at -O1 and higher.
  • -fipa-reference โ€” discover which static variables do not escape the compilation unit ๐Ÿซง. Enabled by default at -O1 and higher.
  • -fipa-reference-addressable โ€” discover read-only, write-only and non-addressable static variables ๐Ÿ“–. Enabled by default at -O1 and higher.
  • -fipa-stack-alignment โ€” reduce stack alignment on call sites if possible ๐Ÿ“. Enabled by default.
  • -fipa-pta โ€” perform interprocedural pointer analysis and interprocedural modification and reference analysis ๐Ÿง . Heads up bestie, this option can cause excessive memory and compile-time usage on large compilation units ๐Ÿ˜ญ. It is not enabled by default at any optimization level.
  • -fipa-profile โ€” perform interprocedural profile propagation. Functions called only from cold functions get marked as cold โ„๏ธ. Also, functions executed once (such as "cold", "noreturn", static constructors or destructors) are identified. Cold functions and loop less parts of functions executed once are then optimized for size. Enabled by default at -O1 and higher.
  • -fipa-modref โ€” perform interprocedural mod/ref analysis ๐Ÿ”. This optimization analyzes the side effects of functions (memory locations that are modified or referenced) and enables better optimization across the function call boundary. This flag is enabled by default at -O1 and higher.
  • -fipa-cp โ€” perform interprocedural constant propagation ๐Ÿ”ข. This optimization analyzes the program to figure out when values passed to functions are constants, and then optimizes accordingly. It can substantially increase performance if the application has constants passed to functions ๐Ÿš€. This flag is enabled by default at -O2, -Os and -O3. It is also enabled by -fprofile-use and -fauto-profile.
  • -fipa-cp-clone</p> โ€” okay so this one does function cloning so that interprocedural constant propagation hits harder. When it's on, the ICP pass clones a function whenever an externally visible function can be called with constant arguments. Slay, right? Except ๐Ÿซ  because cloning means multiple copies of functions, which can bump your code size up a LOT (peep --param ipa-cp-unit-growth=value if that hurts). It's on by default at -O3, and it also gets switched on by -fprofile-use and -fauto-profile. ๐Ÿ’…
  • -fipa-bit-cp โ€” when enabled, it does interprocedural bitwise constant propagation. On by default at -O2, and also by -fprofile-use and -fauto-profile. Important: it needs -fipa-cp to be enabled first โ€” no -fipa-cp, no bit-cp bestie. โœจ
  • -fipa-vrp โ€” when enabled, it does interprocedural propagation of value ranges. On by default at -O2. And yeah, same deal: it requires -fipa-cp to be enabled. ๐Ÿฆ‹
  • -fipa-icf โ€” performs Identical Code Folding for functions and read-only variables. It shrinks code size, and heads up ๐Ÿ˜ญ it may disturb unwind stacks by replacing a function with an equivalent one that has a different name. It works more effectively with link-time optimization enabled.

So even though the behaviour is similar to the Gold Linker's ICF optimization, GCC's ICF works on different levels, so the optimizations are not the same โ€” there are equivalences only GCC finds, and equivalences only Gold finds. Not the same girl, not the same job. ๐Ÿ’€

This flag is enabled by default at -O2 and -Os.

  • -flive-patching=level โ€” controls GCC's optimizations so the output is suitable for live-patching. ๐Ÿฉน

Here's the whole situation: if the compiler's optimization uses a function's body (or info pulled out of its body) to optimize or change another function, that other one is called an impacted function of the former. So if a function gets patched, its impacted functions gotta be patched too. Periodt.

The impacted functions are decided by the compiler's interprocedural optimizations. For example, a caller is impacted when inlining a function into its caller, when cloning a function and changing its caller to call this new clone, or when extracting a function's pureness/constness info to optimize its direct or indirect callers, etc.

Usually the more IPA optimizations you turn on, the more impacted functions each function has. So to control how many impacted functions there are and to make computing the impacted-function list easier, the 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. Which means: when you patch a function, all its callers and its clones' callers are impacted, so they need patching too. ๐Ÿ‘‘

-flive-patching=inline-clone disables these 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. So when you patch a static function, all its callers are impacted and therefore need to be patched as well.

On top of all the flags that -flive-patching=inline-clone disables, -flive-patching=inline-only-static disables these 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). Don't try it bestie, it's not giving.
  • -fisolate-erroneous-paths-dereference โ€” detects paths that trigger erroneous or undefined behavior by dereferencing a null pointer. It isolates those paths from the main control flow and turns the statement with the erroneous/undefined behavior into a trap. Enabled 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 because a null value is used in a way that's forbidden by a "returns_nonnull" or "nonnull" attribute. Same treatment: isolate those paths from the main control flow and turn the offending statement into a trap. This is not currently enabled, but it may be enabled by -O2 in the future. ๐Ÿ”ฎ
  • -ftree-sink โ€” performs forward store motion on trees. On by default at -O1 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 it's enabled 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. Also only operates on local scalar variables, and on by default at -O1 and higher. ๐Ÿ’œ
  • -fssa-backprop โ€” propagates info about the uses of a value up the definition chain so the definitions can get simplified. For example, this pass strips sign operations if the sign of a value never matters. Enabled by default at -O1 and higher. ๐ŸŽ€
  • -fssa-phiopt โ€” does pattern matching on SSA PHI nodes to optimize conditional code. Enabled by default at -O1 and higher, except for -Og. ๐ŸŒธ
  • -ftree-switch-conversion โ€” converts simple initializations in a switch into initializations from a scalar array. Enabled by default at -O2 and higher. ๐Ÿ”ฅ
  • -ftree-tail-merge โ€” looks for identical code sequences, and when it finds them 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. You can limit the compilation time this pass eats up with the max-tail-merge-comparisons parameter and the max-tail-merge-iterations parameter. โณ
  • -ftree-dce โ€” performs dead code elimination (DCE) on trees. Enabled by default at -O1 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. Enabled by default at -O2 and higher, if -Os is not also specified. ๐Ÿ˜Œ
  • -ffinite-loops โ€” assumes that a loop with an exit will eventually take that exit and not loop forever. Which lets the compiler remove loops that otherwise have no side-effects, since it's not counting eventual endless looping as a side effect anymore. ๐ŸŒ€

This option is enabled by default at -O2 for C++ with -std=c++11 or higher.

  • -ftree-dominator-opts โ€” performs a whole lil variety of simple scalar cleanups (constant/copy propagation, redundancy elimination, range propagation and expression simplification) based on a dominator tree traversal. It also does jump threading (to reduce jumps to jumps). Enabled by default at -O1 and higher. โœจ
  • -ftree-dse โ€” performs dead store elimination (DSE) on trees. A dead store is a store into a memory location that later gets overwritten by another store with no intervening loads โ€” in that case the earlier store can be deleted. Enabled by default at -O1 and higher. ๐Ÿ‘‘
  • -ftree-ch โ€” performs loop header copying on trees. This is beneficial because it makes code motion optimizations more effective, and it also saves one jump. Enabled by default at -O1 and higher. It's not enabled for -Os, since it usually increases code size. ๐Ÿซถ
  • -ftree-loop-optimize โ€” performs loop optimizations on trees. Enabled by default at -O1 and higher. ๐ŸŒˆ
  • -ftree-loop-linear
  • -floop-strip-mine
  • -floop-block โ€” perform loop nest optimizations. Same as -floop-nest-optimize. To use this code transformation, GCC has to be configured with --with-isl to enable the Graphite loop transformation infrastructure. ๐Ÿงฉ
  • -fgraphite-identity โ€” enables the identity transformation for graphite. For every SCoP we generate the polyhedral representation and transform it back to gimple. Using -fgraphite-identity we can check the costs or benefits of the GIMPLE -> GRAPHITE -> GIMPLE transformation. Some minimal optimizations are also performed by the code generator isl, like index splitting and dead code elimination in loops. ๐Ÿฆ‹
  • -floop-nest-optimize โ€” enables the isl based loop nest optimizer. This is a generic loop nest optimizer based on the Pluto optimization algorithms. It calculates a loop structure optimized for data-locality and parallelism. This option is experimental. ๐Ÿงช
  • -floop-parallelize-all โ€” uses the Graphite data dependence analysis to find loops that can be parallelized, then parallelizes all the loops that can be analyzed to not contain loop carried dependences โ€” without checking whether parallelizing them is actually profitable. ๐Ÿ˜ญ
  • -ftree-coalesce-vars โ€” while transforming the program out of the SSA representation, it tries to reduce copying by coalescing versions of different user-defined variables instead of just compiler temporaries. Heads up โš ๏ธ this may severely limit your ability to debug an optimized program compiled with -fno-var-tracking-assignments. In the negated form, this flag prevents SSA coalescing of user variables. It's enabled by default if optimization is enabled, and it does very little otherwise. ๐Ÿ’…
  • -ftree-loop-if-convert โ€” tries to transform conditional jumps in the innermost loops into branch-less equivalents. The intent is to remove control-flow from the innermost loops so the vectorization pass has an easier time handling those loops. Enabled by default if vectorization is enabled. ๐Ÿ”ฅ
  • -ftree-loop-distribution โ€” performs loop distribution. This flag can improve cache performance on big loop bodies and allows 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

okay and to close that one out: this flag is enabled by default at -O3. it's also enabled by -fprofile-use and -fauto-profile. slay. ๐Ÿ’…


  • -ftree-loop-distribute-patterns โ€” bestie this one does loop distribution on patterns that can be code generated with calls to a library ๐Ÿ“šโœจ. this flag is enabled by default at -O2 and higher, and by -fprofile-use and -fauto-profile.

what this pass actually does is distribute the initialization loops and generate a call to memset zero. like, watch โ€” for example, the loop

DO I = 1, N
  A(I) = 0
  B(I) = A(I) + I
ENDDO

gets transformed to

DO I = 1, N
   A(I) = 0
ENDDO
DO I = 1, N
   B(I) = A(I) + I
ENDDO

and then the initialization loop gets transformed into a call to memset zero ๐Ÿซถ. this flag is enabled by default at -O3. it is also enabled by -fprofile-use and -fauto-profile.

  • -floop-interchange โ€” performs loop interchange outside of graphite ๐Ÿ”ฅ. this one can improve cache performance on loop nest and let further loop optimizations โ€” like vectorization โ€” take place. the way that it works, okay: for example, the loop
for (int i = 0; i < N; i++)
  for (int j = 0; j < N; j++)
    for (int k = 0; k < N; k++)
      c[i][j] = c[i][j] + a[i][k]*b[k][j];

is transformed to

for (int i = 0; i < N; i++)
  for (int k = 0; k < N; k++)
    for (int j = 0; j < N; j++)
      c[i][j] = c[i][j] + a[i][k]*b[k][j];

this flag is enabled by default at -O3. it is also enabled by -fprofile-use and -fauto-profile. iconic behavior honestly ๐ŸŒˆ

  • -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. this flag is enabled by default at -O3. it is also enabled by -fprofile-use and -fauto-profile.
  • -ftree-loop-im โ€” performs loop invariant motion on trees ๐ŸŒณ. okay important detail: this pass moves only invariants that are hard to handle at RTL level (function calls, operations that expand to nontrivial sequences of insns). with -funswitch-loops it also moves operands of conditions that are invariant out of the loop, so that we can use just trivial invariantness analysis in loop unswitching ๐Ÿงš. the pass also includes store motion.
  • -ftree-loop-ivcanon โ€” creates a canonical counter for number of iterations in loops for which determining number of iterations requires complicated analysis ๐Ÿ˜ตโ€๐Ÿ’ซ. later optimizations then may determine the number easily. useful especially in connection with unrolling. no cap ๐Ÿ’ฏ
  • -ftree-scev-cprop โ€” performs final value replacement. so here's the tea โ˜•: if a variable is modified in a loop in such a way that its value when exiting the loop can be determined using only its initial value and the number of loop iterations, replace uses of the final value by such a computation โ€” provided it is sufficiently cheap ๐Ÿ’ธ. this reduces data dependencies and may allow further simplifications. enabled by default at -O1 and higher.
  • -fivopts โ€” performs induction variable optimizations on trees: strength reduction, induction variable merging and induction variable elimination ๐ŸŒฟ.
  • -ftree-parallelize-loops=n โ€” parallelize loops!! โœจ i.e., split their iteration space to run in n threads. this is only possible for loops whose iterations are independent and can be arbitrarily reordered ๐ŸŒ€. also like, heads up: the optimization is only profitable on multiprocessor machines, for loops that are CPU-intensive, rather than constrained e.g. by memory bandwidth ๐Ÿซ . this option implies -pthread, and thus is only supported on targets that have support for -pthread.
  • -ftree-pta โ€” performs function-local points-to analysis on trees ๐Ÿ‘€. this flag is 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. this flag is 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. this is enabled by default at -O2 and higher as well as -Os.
  • -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 gives the expanders much more complex trees to work on resulting in better RTL generation. this is enabled by default at -O1 and higher.
  • -ftree-slsr โ€” performs straight-line strength reduction on trees โœจ. this recognizes related expressions involving multiplications and replaces them by less expensive calculations when possible. this is enabled by default at -O1 and higher.
  • -ftree-vectorize โ€” performs vectorization on trees ๐Ÿฆ‹. this flag enables -ftree-loop-vectorize and -ftree-slp-vectorize if not explicitly specified.
  • -ftree-loop-vectorize โ€” performs loop vectorization on trees. this flag is enabled by default at -O2 and by -ftree-vectorize, -fprofile-use, and -fauto-profile.
  • -ftree-slp-vectorize โ€” performs basic block vectorization on trees. this flag is enabled by default at -O2 and by -ftree-vectorize, -fprofile-use, and -fauto-profile.
  • -ftrivial-auto-var-init=choice โ€” initializes automatic variables with either a pattern or with zeroes, to increase the security and predictability of a program by preventing uninitialized memory disclosure and use ๐Ÿ”’โœจ.
okay so this is the important part bestie: GCC still considers an automatic variable that doesn't have an explicit initializer as uninitialized. -Wuninitialized and -Wanalyzer-use-of-uninitialized-value will still report warning messages on such automatic variables, and the compiler will perform optimization as if the variable were uninitialized ๐Ÿ˜ญ

with this option, GCC will also initialize any padding of automatic variables that have structure or union types to zeroes. however, the current implementation cannot initialize automatic variables that are declared between the controlling expression and the first case of a "switch" statement. use -Wtrivial-auto-var-init to report all such cases ๐Ÿ™ˆ.

the three values of choice are:

  • uninitialized โ€” doesn't initialize any automatic variables. this is C and C++'s default ๐Ÿ’€
  • pattern โ€” initialize automatic variables with values which will likely transform logic bugs into crashes down the line, are easily recognized in a crash dump and without being values that programmers can rely on for useful program semantics. the current value is byte-repeatable pattern with byte "0xFE". the values used for pattern initialization might be changed in the future ๐Ÿ‘€
  • zero โ€” initialize automatic variables with zeroes. clean, simple, iconic ๐Ÿซถ

the default is uninitialized.

you can control this behavior for a specific variable by using the variable attribute "uninitialized".

  • -fvect-cost-model=model โ€” alters the cost model used for vectorization ๐Ÿ’ธ. the model argument should be one of unlimited, dynamic, cheap or very-cheap. let's break it down:
    • 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 to enable it only for iteration counts that will likely execute faster than when executing 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 is 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.

  • -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 โ€” performs Value Range Propagation on trees ๐ŸŒณ. this is similar to the constant propagation pass, but instead of values, ranges of values are propagated ๐Ÿ“ˆ๐Ÿ“‰. this allows the optimizers to remove unnecessary range checks like array bound checks and null pointer checks ๐Ÿšซ. this is enabled by default at -O2 and higher. heads up tho: null pointer check elimination is only done if -fdelete-null-pointer-checks is enabled.
  • -fsplit-paths โ€” splits paths leading to loop backedges ๐Ÿ”€. this can improve dead code elimination and common subexpression elimination. this is enabled by default at -O3 and above.
  • -fsplit-ivs-in-unroller โ€” enables expression of values of induction variables in later iterations of the unrolled loop using the value in the first iteration ๐ŸŒ€. this breaks long dependency chains, thus improving efficiency of the scheduling passes. slay โœจ

a combination of -fweb and CSE is often sufficient to obtain the same effect. however, that is not reliable in cases where the loop body is more complicated than a single basic block ๐Ÿ˜ฌ. it also does not work at all on some architectures due to restrictions in the CSE pass ๐Ÿ™ƒ

this optimization is enabled by default.

  • -fvariable-expansion-in-unroller โ€” with this option, the compiler creates multiple copies of some local variables when unrolling a loop, which can result in superior code ๐Ÿ’โ€โ™€๏ธ

this optimization is enabled by default for PowerPC targets, but disabled by default otherwise ๐ŸŽ€

  • -fpartial-inlining โ€” bestie, this one inlines parts of functions. Like not the whole function, just the juicy bits. But heads up: it literally does nothing unless inlining itself is already turned on by -finline-functions or -finline-small-functions. ๐Ÿ’…

It's enabled at levels -O2, -O3, -Os.

  • -fpredictive-commoning โ€” does the predictive commoning optimization, which is a fancy way of saying it reuses computations from previous iterations of loops โ€” especially memory loads and stores. it's giving "why recompute when you already know" energy. โœจ

Enabled at level -O3. It's also enabled by -fprofile-use and -fauto-profile.

  • -fprefetch-loop-arrays โ€” if your target machine supports it, GCC generates instructions to prefetch memory, which makes loops that access big arrays go faster. ๐ŸŽ๏ธ
real talk: this option may generate better or worse code. results are highly dependent on the structure of the loops in your source. no cap.

Disabled at level -Os.

  • -fno-printf-return-value โ€” do NOT substitute constants for the known return value of formatted output functions like sprintf, snprintf, vsprintf, and vsnprintf (but not printf of fprintf). This transformation is what lets GCC optimize โ€” or literally eliminate โ€” branches based on the known return value of these functions when they're called with arguments that are either constant, or whose values are known to be in a range that makes figuring out 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 the -fprintf-return-value option is enabled by default. ๐Ÿ’–

  • -fno-peephole, -fno-peephole2 โ€” disables any machine-specific peephole optimizations. The difference between -fno-peephole and -fno-peephole2 is how they're implemented in the compiler; some targets use one, some use the other, a few use both. it's giving sibling energy fr fr. ๐Ÿ™ˆ

-fpeephole is enabled by default. -fpeephole2 is enabled at levels -O2, -O3, -Os.

  • -fno-guess-branch-probability โ€” don't guess branch probabilities using heuristics. periodt.

GCC uses heuristics to guess branch probabilities if nobody gives it profiling feedback (-fprofile-arcs). These heuristics are based on the control flow graph. If some branch probabilities are specified by __builtin_expect, then the heuristics are used to guess branch probabilities for the rest of the control flow graph, taking the __builtin_expect info into account. The interactions between the heuristics and __builtin_expect can be... complex ๐Ÿ˜ญ, and in some cases it may be useful to disable the heuristics so the effects of __builtin_expect are easier to understand.

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 โ€” reorders basic blocks in the compiled function to reduce the number of taken branches and improve code locality. slay. โœจ

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

  • -freorder-blocks-algorithm=algorithm โ€” use the specified algorithm for 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 -O1, -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 partitions hot and cold basic blocks into separate sections of the assembly and .o files, to improve paging and cache locality performance. iconic behavior. ๐Ÿ”ฅ

This optimization is automatically turned off in the presence of exception handling or unwind tables (on targets using setjump/longjump or a target-specific scheme), for linkonce sections, for functions with a user-defined section attribute, and on any architecture that doesn't 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 you're using a working linker).

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

  • -freorder-functions โ€” reorders 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 the unlikely-executed ones. The 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.
ngl this option isn't effective unless you either provide profile feedback (see -fprofile-arcs for the deets) or manually annotate functions with hot or cold attributes.

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

  • -fstrict-aliasing โ€” lets the compiler assume the strictest aliasing rules that apply 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 to never 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, bestie:

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.

  • -fipa-strict-aliasing โ€” controls whether the rules of -fstrict-aliasing get applied across function boundaries. Note that if multiple functions get inlined into a single function, the memory accesses are no longer considered to be crossing a function boundary. ๐ŸŒˆ

The -fipa-strict-aliasing option is enabled by default and is effective only in combination with -fstrict-aliasing.

  • -falign-functions, -falign-functions=n, -falign-functions=n:m, -falign-functions=n:m:n2, -falign-functions=n:m:n2:m2 โ€” aligns the start of functions to the next power-of-two greater than or equal to n, skipping up to m-1 bytes. This ensures 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: -falign-functions=32 aligns functions to the next 32-byte boundary, -falign-functions=24 aligns to the next 32-byte boundary only if this can be done by skipping 23 bytes or less, -falign-functions=32:7 aligns to the next 32-byte boundary only if this can be done by skipping 6 bytes or less.

The second pair of n2:m2 values lets you specify a secondary alignment: -falign-functions=64:7:32:3 aligns to the next 64-byte boundary if this can be done by skipping 6 bytes or less, otherwise aligns to the next 32-byte boundary if this can be done by skipping 2 bytes or less. If m2 is not specified, it defaults to n2.

Some assemblers only support this flag when n is a power of two; in that case, it 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 โ€” aligns all branch targets to a power-of-two boundary. ๐Ÿซถ

The parameters of this option are analogous to the -falign-functions option. -fno-align-labels and -falign-labels=1 are equivalent and mean that labels are not aligned.

If -falign-loops or -falign-jumps are applicable and are greater than this value, then their values are used instead.

If n is not specified or is zero, use a machine-dependent default which is very likely to be 1, meaning no alignment. The maximum allowed n option value is 65536.

Enabled at levels -O2, -O3.

  • -falign-loops, -falign-loops=n, -falign-loops=n:m, -falign-loops=n:m:n2, -falign-loops=n:m:n2:m2 โ€” aligns loops to a power-of-two boundary. If the loops are executed many times, this makes up for any execution of the dummy padding instructions. it pays for itself, bestie. ๐Ÿ’–

If -falign-labels is greater than this value, then its value is used instead.

The parameters of this option are analogous to the -falign-functions option. -fno-align-loops and -falign-loops=1 are equivalent and mean that loops are not aligned. The maximum allowed n option value is 65536.

If n is not specified or is zero, use a machine-dependent default.

Enabled at levels -O2, -O3.

  • -falign-jumps, -falign-jumps=n, -falign-jumps=n:m, -falign-jumps=n:m:n2, -falign-jumps=n:m:n2:m2 โ€” okay so this one lines up your branch targets on a power-of-two boundary โœจ but ONLY for branch targets you can literally only reach by jumping to them. And the slay part? No dummy operations have to get executed. Zero. None. Iconic behavior honestly.

And if -falign-labels is bigger than this value? Then -falign-labels's value wins and gets used instead. Periodt.

The parameters work just like the -falign-functions option does, iykyk. Also fun fact: -fno-align-jumps and -falign-jumps=1 are genuinely the same thing โ€” both mean loops don't get aligned at all ๐ŸŒธ

If n isn't specified, or it's zero? Machine-dependent default, bestie, we don't decide that. And the max allowed n value is 65536.

Enabled at levels -O2, -O3. ๐Ÿ’…

  • -fno-allocation-dce โ€” bestie do NOT remove unused C++ allocations during dead code elimination. Like, leave them alone. ๐Ÿ™ˆ
  • -fallow-store-data-races โ€” okay so this lets the compiler do optimizations that might introduce new data races on stores, without it having to first prove the variable can't be touched by other threads at the same time. It does not affect optimization of local data though. And it's safe to use if you KNOW global data won't be accessed by multiple threads ๐Ÿซถ

So what optimizations does this actually unlock? Stuff like hoisting or if-conversions that might cause a value that was already chilling in memory to get re-written with that exact same value. In a single-threaded context that re-writing is totally fine and safe. In a multi-threaded context? Could be unsafe, no cap. Also heads up: on some processors, if-conversions might be required in order to enable vectorization. ๐Ÿ’€

Enabled at level -Ofast.

  • -funit-at-a-time โ€” this one's just left here for compatibility reasons, fr fr. -funit-at-a-time has literally no effect, while -fno-unit-at-a-time implies -fno-toplevel-reorder and -fno-section-anchors.

Enabled by default. โœจ

  • -fno-toplevel-reorder โ€” do NOT reorder top-level functions, variables, and "asm" statements. Output them in the exact same order they show up in the input file, periodt. When you use this option, unreferenced static variables don't get removed either.

This option exists to support existing code that depends on a particular ordering. For new code though? Better to use attributes when you can, bestie ๐ŸŒธ

-ftoplevel-reorder is the default at -O1 and higher, and also at -O0 if -fsection-anchors is explicitly requested. Also: -fno-toplevel-reorder implies -fno-section-anchors.

  • -funreachable-traps โ€” with this one, the compiler turns calls to "__builtin_unreachable" into traps instead of using them for optimization. This also affects any such calls that the compiler implicitly generated on its own ๐Ÿ‘‘

It does the same thing as -fsanitize=unreachable -fsanitize-trap=unreachable, BUT it does not change the values of those options. And if -fsanitize=unreachable is enabled, that option takes priority over this one. Sorry bestie, priority is priority ๐Ÿ’…

This option is enabled by default at -O0 and -Og.

  • -fweb โ€” constructs webs the way they're commonly used for register allocation purposes, and assigns each web its own individual pseudo register. This lets the register allocation pass work directly on pseudos, but it ALSO strengthens several other optimization passes โ€” think CSE, the loop optimizer, and the trivial dead code remover. Slay? Kinda. ๐Ÿ˜ญ

BUT โ€” and this is a big but โ€” it can make debugging impossible, since variables no longer stay in a "home register". It's giving chaos.

Enabled by default with -funroll-loops.

  • -fwhole-program โ€” assume that the current compilation unit is the whole program being compiled. Every public function and variable โ€” except "main" and anything merged by the attribute "externally_visible" โ€” becomes a static function, and in effect they get optimized way more aggressively by the interprocedural optimizers ๐Ÿ”ฅ

With -flto this option has limited use. In most cases the precise list of symbols used or exported from the binary is known from the resolution info passed to the link-time optimizer by the linker plugin. It's still useful if no linker plugin is used, or during the incremental link step when final code is produced (with -flto -flinker-output=nolto-rel).

  • -flto[=n] โ€” okay this is the big one, bestie, gather round ๐ŸŽ€ This option runs the standard link-time optimizer. When you invoke it with source code, it generates GIMPLE (one of GCC's internal representations) and writes it to special ELF sections in the object file. Then when the object files get linked together, all the function bodies are read from those ELF sections and instantiated as if they'd been part of the same translation unit the whole time. It's giving โœจone single mindโœจ.

To actually use the link-time optimizer, -flto AND your optimization options should be specified at compile time and during the final link. The recommendation is that you compile all the files participating in the same link with the same options, and also specify those options at link time. Like so:

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, all the interprocedural analyses and optimizations in GCC 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. Cross-file glow-up, we love to see it.

Another (and 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 your head, bestie: to enable link-time optimizations you need to use the GCC driver to do the link step. GCC automatically performs link-time optimization if any of the objects involved were compiled with the -flto command-line option. And you can always override that automatic decision by passing -fno-lto to the link command. You're the main character here, not the compiler ๐Ÿ’…

To make whole program optimization actually effective, it's 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 the linker supports it, the linker plugin (see -fuse-linker-plugin) passes info to the compiler about used and externally visible symbols. When the linker plugin isn't available, -fwhole-program should be used to let the compiler 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 object files with LTO information can be linked as normal object files; if -fno-lto is passed to the linker, no interprocedural optimizations get applied. Note that when -fno-fat-lto-objects is enabled the compile stage is faster, but you cannot do a regular, non-LTO link on them. Trade-offs, bestie, trade-offs. ๐Ÿ˜ญ

When producing the final binary, GCC only applies link-time optimizations to those files that contain bytecode. So you can mix and match object files and libraries with GIMPLE bytecodes and final object code. GCC automatically picks which files get optimized in LTO mode and which files get linked without further processing โœจ

Generally, options specified at link time override those specified at compile time, although in some cases GCC tries to infer link-time options from the settings used to compile the input files ๐Ÿ”ฎ

If you don't 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's generally ineffective to specify an optimization level option only at link time and not at compile time, for two big reasons. First: compiling without optimization suppresses compiler passes that gather the info needed for effective optimization at link time. Second: some early optimization passes can only happen at compile time and not at link time. So like, don't do that. ๐Ÿ™ˆ

There are some code generation flags that GCC preserves when generating bytecodes, because 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 this 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 just... ignored. Nothing you can do, bestie. This includes options such as -freg-struct-return and -fpcc-struct-return. ๐Ÿ’€

Other options such as -ffp-contract, -fno-strict-overflow, -fwrapv, -fno-trapv or -fno-strict-aliasing get 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 though, so that's your escape hatch ๐ŸŒˆ

Diagnostic options such as -Wstringop-overflow get passed through to the link stage too, and their setting matches that of the compile-step at function granularity. Note that this only matters for diagnostics emitted during optimization. And note that code transforms like inlining can lead to warnings being enabled or disabled for regions of code that aren't consistent with the setting at compile time. Little chaos gremlin behavior, ngl ๐Ÿงš

When you need to pass options to the assembler via -Wa or -Xassembler, make sure to either compile such translation units with -fno-lto OR consistently use the same assembler options on all translation units. You can alternatively also specify assembler options at LTO link time. Pick your lane, bestie ๐Ÿ’œ

For debug info to actually get generated you need to hand over -g at compile time, bestie โ€” no -g, no debug info, that's the deal ๐ŸŽ€. And here's the cute part: if any of the input files at link time were built with debug info generation turned on, then the link turns debug info generation on too โœจ. But watch out ๐Ÿ‘€ โ€” the fancy elaborate debug info settings, like the dwarf level -gdwarf-5, have to be explicitly repeated at the linker command line, and mixing different settings across different translation units is discouraged. Periodt.

So LTO has a little warning for you: if it runs into objects with C linkage that are declared with incompatible types in separate translation units that are being linked together (which is undefined behavior according to ISO C99 6.2.7 ๐Ÿ˜ญ), it may issue a non-fatal diagnostic. And the behavior is still undefined at run time, so likeโ€ฆ it told you, but it can't save you ๐Ÿ’€. Similar diagnostics can pop up for other languages too.

Another lil superpower of LTO? You can apply interprocedural optimizations across 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 how the final link is done with g++ so you get the C++ runtime libraries, and -lgfortran is tacked on to grab the Fortran runtime libraries. In general, when you're mixing languages in LTO mode, use the same link command options you'd use when mixing languages in a regular (non-LTO) compilation. Iconic behavior honestly.

Now, if object files containing GIMPLE bytecode are sitting in a library archive โ€” say libfoo.a โ€” it's possible to extract them and use them in an LTO link, as long as you're using a linker with plugin support ๐Ÿซถ. To build static libraries suitable for LTO, use gcc-ar and gcc-ranlib instead of ar and ranlib. And 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. Then at link time, use the flag -fuse-linker-plugin to make sure the library actually 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 GIMPLE files it needs out of libfoo.a and passes them on to the running GCC so they can join the aggregated GIMPLE image that gets optimized โœจ.

If you're not using a linker with plugin support, and/or you don't enable the linker plugin, then the objects inside libfoo.a get extracted and linked the usual way โ€” but they do not participate in the LTO optimization process, sadly ๐Ÿ˜”. And if you want a static library that's suitable for both LTO optimization and usual linkage, compile its object files with -flto -ffat-lto-objects.

Link-time optimizations do not require the whole program to be present to operate โ€” no cap. If your program doesn't need any symbols exported, you can combine -flto and -fwhole-program to let the interprocedural optimizers use way more aggressive assumptions, which may lead to improved optimization opportunities ๐Ÿ‘‘. But heads up: use of -fwhole-program is not needed when the linker plugin is active (peep -fuse-linker-plugin).

Real talk moment: the current implementation of LTO makes no attempt to generate bytecode that's portable between different types of hosts. The bytecode files are versioned and there's 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, don't try it ๐Ÿ’€.

Also lowkey important: 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 runs in parallel using n parallel jobs, by utilizing an installed make program. The environment variable MAKE can be used to override the program that's used ๐Ÿ› ๏ธ.

You can also specify -flto=jobserver to use GNU make's job server mode to figure out the number of parallel jobs. This is so 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 โ€” no +, no party. This option likely only works if MAKE is GNU make. And even without the option value, GCC tries to automatically detect a running GNU make's job server ๐Ÿ‘€.

Then there's -flto=auto, which uses GNU make's job server if it's available, or otherwise falls back to autodetecting the number of CPU threads present in your system. Bestie just handles it for you ๐Ÿ’….


-flto-partition=alg

Pick the partitioning algorithm the link-time optimizer uses, bestie โ€” you've got options ๐ŸŽ€:

  • 1to1 โ€” a partitioning that mirrors the original source files
  • balanced โ€” partitioning into equally sized chunks (whenever possible)
  • max โ€” creates a new partition for every symbol where possible
  • none โ€” disables partitioning and streaming completely. Also, when you specify the value none, it bypasses partitioning and executes the link-time optimization step directly from the WPA phase.
  • one โ€” specifies that exactly one partition should be used.

The default value is balanced. 1to1 can be used as a workaround for various code ordering issues, while the max partitioning is intended for internal testing only (so, not for you, sorry ๐Ÿ”ฅ).

-flto-compression-level=n

This one sets the level of compression used for the intermediate language written to LTO object files, and it's only meaningful in conjunction with LTO mode (-flto). GCC currently supports two LTO compression algorithms:

  • zstd โ€” valid values are 0 (no compression) up to 19 (maximum compression)
  • zlib โ€” supports values from 0 to 9

Values outside the supported range get clamped to either the minimum or the maximum of the supported values ๐Ÿซถ. If you don't give the option, 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, which improves the quality of optimization by exposing more code to the link-time optimizer ๐Ÿ‘‘. This info specifies what symbols can be accessed externally (by non-LTO objects or during dynamic linking). The resulting code quality improvements on binaries (and shared libraries that use hidden visibility) are similar to -fwhole-program. Peep -flto for a description of the effect of this flag and how to use it.

This option is enabled by default when LTO support in GCC is enabled and GCC was configured for use with a linker supporting plugins (GNU ld 2.21 or newer, or gold).

-ffat-lto-objects

Fat LTO objects are object files that contain both the intermediate language and the object code ๐Ÿ“. That makes them usable for both LTO linking and normal linking. This option is only effective when compiling with -flto, and it's ignored at link time.

-fno-fat-lto-objects improves compilation time over plain LTO, but it requires the complete toolchain to be aware of LTO ๐Ÿ˜ญ. It requires a linker with linker plugin support for basic functionality. On top of that, nm, ar and ranlib need to support linker plugins to allow a full-featured build environment (one capable of building static libraries etc). GCC provides the gcc-ar, gcc-nm, gcc-ranlib wrappers to pass the right options to these tools. With non-fat LTO, makefiles need to be modified to use them.

Note that modern binutils provide a plugin auto-load mechanism โ€” installing the linker plugin into $libdir/bfd-plugins has the same effect as using 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, this pass identifies arithmetic instructions that compute processor flags similar to a comparison operation based on that arithmetic ๐Ÿ”. If possible, it eliminates the explicit comparison operation.

This pass only applies to certain targets that cannot explicitly represent the comparison operation before register allocation is complete.

Enabled at levels -O1, -O2, -O3, -Os โœจ.

-fcprop-registers

After register allocation and post-register allocation instruction splitting, this one performs a copy-propagation pass to try to reduce scheduling dependencies and occasionally eliminate the copy. Lowkey elegant.

Enabled at levels -O1, -O2, -O3, -Os โœจ.

-fprofile-correction

Profiles collected using an instrumented binary for multi-threaded programs may be inconsistent because of missed counter updates ๐Ÿ˜ญ. When this option is specified, GCC uses heuristics to correct or smooth out those inconsistencies. By default, GCC just emits an error message when it detects an inconsistent profile (dramatic much).

This option is enabled by -fauto-profile.

-fprofile-partial-training

So with -fprofile-use, all portions of the program that weren't executed during the train run get optimized aggressively for size rather than speed ๐Ÿ‘€. But sometimes it's just not practical to train every possible hot path in a program โ€” like, the program might contain functions specific to a given hardware config, and the training might not cover all the hardware configurations the program gets run on, y'know?

With -fprofile-partial-training, profile feedback gets ignored for all functions not executed during the train run, leading them to be optimized as if they were compiled without profile feedback. This leads to better performance when the train run isn't representative โ€” but also leads to significantly bigger code, so it's a trade-off, bestie โš–๏ธ.

-fprofile-use, -fprofile-use=path

Enables profile feedback-directed optimizations, plus the following optimizations โ€” a lot of which are generally profitable only when profile feedback is available:

          -fbranch-probabilities  -fprofile-values -funroll-loops
          -fpeel-loops  -ftracer  -fvpt -finline-functions  -fipa-cp
          -fipa-cp-clone  -fipa-bit-cp -fpredictive-commoning  -fsplit-loops
          -funswitch-loops -fgcse-after-reload  -ftree-loop-vectorize
          -ftree-slp-vectorize -fvect-cost-model=dynamic
          -ftree-loop-distribute-patterns -fprofile-reorder-functions
Before you can use this option, you must first generate profiling information. No profile info, no -fprofile-use โ€” that's the rule ๐ŸŽ€.

Okay so, quick heads-up bestie: by default GCC throws an error if the feedback profiles don't match the source code. ๐Ÿ˜ญ You can downgrade that drama to a mere warning with -Wno-error=coverage-mismatch โ€” but heads up, that may result in poorly optimized code. Also, by default GCC emits a warning message if the feedback profiles don't exist at all (peep -Wmissing-profile). So like, it will absolutely tell on you. ๐Ÿ™ˆ

If path is specified, GCC looks at path to find the profile feedback data files. See -fprofile-dir. ๐Ÿ’…


๐ŸŒŸ sampling-based feedback, aka the AutoFDO corner ๐ŸŒŸ

  • -fauto-profile
  • -fauto-profile=path

Turns on sampling-based feedback-directed optimizations, plus this whole squad of optimizations โ€” most of which are only really worth it when profile feedback is available:

  • -fbranch-probabilities
  • -fprofile-values
  • -funroll-loops
  • -fpeel-loops
  • -ftracer
  • -fvpt
  • -finline-functions
  • -fipa-cp
  • -fipa-cp-clone
  • -fipa-bit-cp
  • -fpredictive-commoning
  • -fsplit-loops
  • -funswitch-loops
  • -fgcse-after-reload
  • -ftree-loop-vectorize
  • -ftree-slp-vectorize
  • -fvect-cost-model=dynamic
  • -ftree-loop-distribute-patterns
  • -fprofile-correction

path is the name of a file containing AutoFDO profile information. If you just don't give one, it defaults to fbdata.afdo in the current directory. (It's giving "I'll find it myself bestie" energy. ๐ŸŽ€)

Now listen โ€” producing an AutoFDO profile data file means running your program with the perf utility on a supported GNU/Linux target system. For more info, see <https://perf.wiki.kernel.org/>. ๐Ÿ‘‘

E.g.

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

Then use the create_gcov tool to convert the raw profile data into a format GCC can actually use. You must also supply the unstripped binary for your program to this tool. See <https://github.com/google/autofdo> for the lore. ๐Ÿฆ‹

E.g.

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

๐Ÿ’œ floating-point vibe check ๐Ÿ’œ

The following options control compiler behavior regarding floating-point arithmetic. These options trade off between speed and correctness. All must be specifically enabled โ€” none of them are coming to save you by default, no cap. ๐Ÿซถ

  • -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 situation on 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. โœจ

  • -fexcess-precision=style โ€” lets you have more control over excess precision on machines where floating-point operations happen 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 โ€” meaning 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's lowkey unpredictable when rounding to the types specified in the source code takes place. ๐Ÿ˜ตโ€๐Ÿ’ซ

When compiling C or C++, if -fexcess-precision=standard is specified, then excess precision follows the rules specified in ISO C99 or C++; 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 or C++ if a strict conformance option such as -std=c99 or -std=c++17 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 or 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. It's giving "turn off all the safety rails, we ball." ๐Ÿ”ฅ

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 don't require the guarantees of these specifications. So like, speed vs. correctness, pick your fighter. โš”๏ธ

  • -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 don't require the guarantees of these specifications.

The default is -fmath-errno.

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

  • -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. Yeah. Unsafe is literally in the name bestie. ๐Ÿ™ˆ

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 don't 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 the 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. Like, imagine infinities just don't exist. Manifesting. โœจ

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 don't 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. Big yikes territory. ๐Ÿ˜ญ

The default is -ftrapping-math.

Future versions of GCC may provide finer control of this setting using C99's "FENV_ACCESS" pragma. This command-line option will be used along with -frounding-math to specify the default state for "FENV_ACCESS". ๐Ÿ”ฎ

  • -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 along with -ftrapping-math to specify the default state for "FENV_ACCESS". ๐ŸŒˆ

  • -fsignaling-nans โ€” compile your code assuming that IEEE signaling NaNs are out here potentially generating user-visible traps during floating-point operations. Flipping this on disables the optimizations that could change how many exceptions you actually see with signaling NaNs, and it implies -ftrapping-math. โœจ

It also makes the preprocessor macro __SUPPORT_SNAN__ get defined. ๐Ÿ‘‘

Default? -fno-signaling-nans, bestie.

โš ๏ธ Heads up: this option is experimental, and it does not currently guarantee that it disables every single GCC optimization that messes with signaling NaN behavior. So likeโ€ฆ proceed with awareness. ๐Ÿ˜ญ
  • -fno-fp-int-builtin-inexact โ€” 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 do let these functions raise that inexact exception, but ISO/IEC TS 18661-1:2014 โ€” the C bindings to IEEE 754-2008, as integrated into ISO C2X โ€” does not allow them to do so. ๐ŸŽ€

The default is -ffp-int-builtin-inexact, which lets the exception be raised โ€” unless C2X or a later C standard is selected. And honestly? This option does absolutely 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 get raised, in the case where the library implementation doesn't follow TS 18661. ๐ŸŒธ

  • -fsingle-precision-constant โ€” treat floating-point constants as single precision instead of quietly converting them into double-precision constants. ๐Ÿฆ‹
  • -fcx-limited-range โ€” when enabled, this option states that a range reduction step is not needed when doing complex division. Also, there is no checking whether the result of a complex multiplication or division is NaN + I*NaN with an attempt to rescue the situation in that case. ๐Ÿ˜ฎโ€๐Ÿ’จ The default is -fno-cx-limited-range, but 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. iykyk. โœจ

  • -fcx-fortran-rules โ€” complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there's no checking whether the result of a complex multiplication or division is NaN + I*NaN, with an attempt to rescue the situation in that case. ๐Ÿ™ˆ

The default is -fno-cx-fortran-rules.


The following options control optimizations that may improve performance, but are not enabled by any -O options. This section includes experimental options that may produce broken code. ๐Ÿ‘€ (Yes, broken. That's not me being dramatic, that's the manpage.)

  • -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. See the details about file naming under -fprofile-arcs.

With -fbranch-probabilities, GCC puts a REG_BR_PROB note on each JUMP_INSN and CALL_INSN. These can be used to improve optimization. Currently they're only used in one place: in reorg.cc, instead of guessing which path a branch is most likely to take, the REG_BR_PROB values are used to exactly determine which path is taken more often. ๐Ÿ”ฅ

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

  • -fprofile-values โ€” if you combine it 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 that gathers 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 โ€” try 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 โ€” perform tail duplication to enlarge superblock size. This transformation simplifies the control flow of the function, allowing other optimizations to do a better job. โœจ

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

  • -funroll-loops โ€” unroll 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). This option makes code larger, and may or may not make it run faster. ๐ŸŽข

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

  • -funroll-all-loops โ€” unroll 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. ๐Ÿ’œ
  • -fmove-loop-stores โ€” enables the loop store motion pass in the GIMPLE loop optimizer. This moves invariant stores to after the end of the loop, in exchange for carrying the stored value in a register across the iteration. Note: for this option to have an effect, -ftree-loop-im has to be enabled as well. Enabled at level -O1 and higher, except for -Og.
  • -fsplit-loops โ€” split 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 โ€” move 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, create 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 especially 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 โ€” optimize the prologue of variadic argument functions with respect to usage of those arguments. โœจ
  • -fsection-anchors โ€” try to reduce the number of symbolic address calculations by using shared "anchor" symbols to address nearby objects. This transformation can help to 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 works out the addresses of all three variables, but if you hit it with -fsection-anchors, it grabs them from one common anchor point instead โœจ The effect is basically this lil pseudocode situation (and no, it is not valid C, don't come for me):

int foo (void)
{
  register int *xr = &x;
  return xr[&a - &x] + xr[&b - &x] + xr[&c - &x];
}

Not all targets support this option, bestie. Some of them just said "no ๐Ÿ’…".

  • -fzero-call-used-regs=choice โ€” zeroes out call-used registers when a function returns, which levels up your program's security by either mitigating Return-Oriented Programming (ROP) attacks or stopping info from leaking out through the registers ๐Ÿ›ก๏ธ

The possible values of choice are the exact same ones as for the zero_call_used_regs attribute. The default is skip. ๐Ÿซถ

You can control this behavior for one specific function by using the function attribute zero_call_used_regs.

  • --param name=value โ€” okay so GCC be using a whole bunch of constants to control how much optimization happens. Like, GCC won't inline functions that have more than a certain number of instructions, that kind of thing. You can control some of these constants right from the command line with the --param option ๐Ÿ”ฅ
The names of specific parameters, and the meaning of the values, are tied to the internals of the compiler, and are subject to change without notice in future releases. So don't get too attached, girl ๐Ÿ’€

To get the minimal, maximal and default values of a parameter, use the --help=param -Q options.

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

  • predictable-branch-outcome โ€” when a branch is predicted to be taken with a probability lower than this threshold (in percent), then it counts as well predictable.
  • max-rtl-if-conversion-insns โ€” RTL if-conversion tries to yeet the conditional branches around a block and replace them with conditionally executed instructions instead. This parameter gives the maximum number of instructions in a block that should even be considered for if-conversion. The compiler also uses other heuristics to decide whether if-conversion is likely to be profitable, so it's not the only factor bestie.
  • 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. The units for this parameter are the same as those for the GCC internal seq_cost metric. The compiler will try to provide a reasonable default for this parameter 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. Increasing values mean more aggressive optimization, so compilation time goes up with probably only a small improvement in executable size. It's giving "slightly slimmer, much slower" ngl.
  • min-crossjump-insns โ€” the minimum number of instructions that must be matched at the end of two blocks before cross-jumping gets performed on them. This value is ignored in the case where all instructions in the block being cross-jumped from are matched.
  • max-grow-copy-bb-insns โ€” the maximum code size expansion factor when copying basic blocks instead of jumping. The expansion is relative to a jump instruction.
  • max-goto-duplication-insns โ€” the maximum number of instructions to duplicate to a block that jumps to a computed goto. To avoid O(N^2) behavior in a number 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 are unfactored. โœจ
  • max-delay-slot-insn-search โ€” the maximum number of instructions to consider when looking 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 stop searching. Increasing values mean more aggressive optimization, making the compilation time increase with probably small improvement in execution time.
  • max-delay-slot-live-search โ€” when trying to fill delay slots, the maximum number of instructions to consider when searching for a block with valid live register information. Increasing this arbitrarily chosen value means more aggressive optimization, and it increases compilation time. This parameter should be removed when the delay slot code is rewritten to maintain the control-flow graph. (Not me โœ‹ โ€” that's just what the docs say, fr fr.)
  • max-gcse-memory โ€” the approximate maximum amount of memory in kB that can be allocated in order to perform the global common subexpression elimination optimization. If more memory than specified is required, the optimization is just not done. Sorry babe ๐Ÿ™ˆ
  • max-gcse-insertion-ratio โ€” if the ratio of expression insertions to deletions is larger than this value for any expression, then RTL PRE inserts or removes the expression and thus leaves partially redundant computations in the instruction stream.
  • max-pending-list-length โ€” the maximum number of pending dependencies scheduling allows before flushing the current state and starting over. Large functions with few branches or calls can create excessively large lists which needlessly consume memory and resources. Iconic waste honestly ๐Ÿ’€
  • max-modulo-backtrack-attempts โ€” the maximum number of backtrack attempts the scheduler should make when modulo scheduling a loop. Larger values can exponentially increase compilation time. Exponentially!! bestie be careful ๐Ÿ˜ญ
  • max-inline-functions-called-once-loop-depth โ€” maximal loop depth of a call considered by inline heuristics that tries to inline all functions called once.
  • max-inline-functions-called-once-insns โ€” maximal estimated size of functions produced while inlining functions called once.
  • max-inline-insns-single โ€” so several parameters control the tree inliner used in GCC, and this number sets the maximum number of instructions (counted in GCC's internal representation) in a single function that the tree inliner considers for inlining. This only affects functions declared inline and methods implemented in a class declaration (C++).
  • max-inline-insns-auto โ€” when you use -finline-functions (which is included in -O3), a lot of functions that would otherwise not 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. Small growth may be desirable to anticipate optimization opportunities exposed by inlining.
  • uninlined-function-insns โ€” number of instructions accounted by the inliner for function overhead such as function prologue and epilogue.
  • uninlined-function-time โ€” extra time accounted by the inliner for function overhead such as 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 inline heuristics hints that inlining is very profitable (aka it will enable later optimizations). Slay.
  • 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. Rules were made to be broken ๐Ÿ’…
  • large-function-insns โ€” the limit specifying really large functions. For functions larger than this limit after inlining, inlining is constrained by --param large-function-growth. This parameter is useful primarily to avoid extreme compilation time caused by non-linear algorithms used by the back end.
  • 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. Besties stay chilly ๐ŸงŠ
  • 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 a translation unit that the IPA-CP pass is gonna look at and go "okay that one's large". ๐Ÿ’…
  • large-stack-frame โ€” the limit that defines what counts as a large stack frame. While it's inlining, the algorithm is literally trying its best not to blow past this limit too hard. ๐Ÿซถ
  • large-stack-frame-growth โ€” the max growth of large stack frames that inlining is allowed to cause, in percent. Say you set it to 1000 โ€” that caps large stack frame growth at 11 times the original size. no cap. ๐Ÿ”ฅ
  • max-inline-insns-recursive, max-inline-insns-recursive-auto โ€” the maximum number of instructions an out-of-line copy of a self-recursive inline function can grow into by doing recursive inlining.

--param max-inline-insns-recursive applies to functions declared inline. For functions that are not declared inline, recursive inlining only happens when -finline-functions (which is included in -O3) is enabled โ€” and then --param max-inline-insns-recursive-auto applies instead. bestie it's a whole switch-up. ๐Ÿฆ‹

  • max-inline-recursive-depth, max-inline-recursive-depth-auto โ€” the maximum recursion depth used for recursive inlining.

Same deal: --param max-inline-recursive-depth applies to functions declared inline. For functions not declared inline, recursive inlining only happens when -finline-functions (included in -O3) is enabled, and --param max-inline-recursive-depth-auto applies instead. ๐Ÿ’ซ

  • min-inline-recursive-probability โ€” recursive inlining is only profitable for functions with deep recursion on average, and it can actually hurt functions with shallow recursion depth โ€” it bloats the prologue size or makes the function body more complex for all the other optimizers. ๐Ÿ˜ญ

When profile feedback is available (see -fprofile-generate), the actual recursion depth can be guessed from the probability that a function recurses through a given call expression. This parameter limits inlining to only those call expressions whose probability exceeds the given threshold (in percent).

  • early-inlining-insns โ€” specify the growth the early inliner is allowed to make. Effectively, it increases how much inlining happens for code carrying a big abstraction penalty. โœจ
  • max-early-inliner-iterations โ€” the iteration limit of the early inliner. Basically it bounds how many nested indirect calls the early inliner can resolve. Deeper chains still get handled by late inlining, so don't stress. ๐Ÿงš
  • comdat-sharing-probability โ€” the probability (in percent) that a C++ inline function with comdat visibility gets shared across multiple compilation units. ๐Ÿ‘‘
  • modref-max-bases, modref-max-refs, modref-max-accesses โ€” the maximum number of base pointers, references and accesses that mod/ref analysis will store for a single function.
  • modref-max-tests โ€” the maximum number of tests the alias oracle can perform to disambiguate memory locations using the mod/ref information. This parameter should be bigger than --param modref-max-bases and --param modref-max-refs, periodt.
  • modref-max-depth โ€” the maximum depth of the DFS walk used by modref escape analysis. Setting it to 0 disables the analysis completely. ๐Ÿ’€
  • modref-max-escape-points โ€” the maximum number of escape points that modref tracks per SSA-name.
  • modref-max-adjustments โ€” the maximum number of times the access range gets enlarged during modref dataflow analysis.
  • profile-func-internal-id โ€” a parameter controlling whether to use function internal id in profile database lookup. If the value is 0, the compiler uses an id based on function assembler name and filename, which makes old profile data more tolerant to source changes like function reordering and such. ๐ŸŒˆ
  • min-vect-loop-bound โ€” the minimum number of iterations below which loops are not vectorized when -ftree-vectorize is used. The number of iterations after vectorization has to be greater than the value specified by this option to allow vectorization.
  • gcse-cost-distance-ratio โ€” the scaling factor used when calculating 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 gets with simple expressions โ€” meaning the expressions whose cost is less than gcse-unrestricted-cost. Specifying 0 disables hoisting of simple expressions. ๐ŸŽ€
  • gcse-unrestricted-cost โ€” the cost, roughly measured as the cost of a single typical machine instruction, at which GCSE optimizations stop constraining 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 gets. Specifying 0 lets all expressions travel unrestricted distances. โœˆ๏ธ
  • max-hoist-depth โ€” the depth of the search in the dominator tree for expressions to hoist. This exists to avoid quadratic behavior in the hoisting algorithm. A value of 0 doesn't limit the search at all, but heads up: it may slow down compilation of huge functions. ๐ŸŒ
  • max-tail-merge-comparisons โ€” the maximum number of similar bbs to compare a bb with. This is here to avoid quadratic behavior in tree tail merging.
  • max-tail-merge-iterations โ€” the maximum number of iterations of the pass over the function. This limits compilation time in tree tail merging. โณ
  • store-merging-allow-unaligned โ€” allow the store merging pass to introduce unaligned stores, if it's legal to do so.
  • max-stores-to-merge โ€” the maximum number of stores to attempt to merge into wider stores in the store merging pass.
  • max-store-chains-to-track โ€” the maximum number of store chains to track at the same time while trying to merge them into wider stores in the store merging pass. ๐Ÿ“
  • max-stores-to-track โ€” the maximum number of stores to track at the same time while trying to merge them into wider stores in the store merging pass.
  • max-unrolled-insns โ€” the maximum number of instructions a loop may have for it to be unrolled. And if a loop does get unrolled, this parameter also decides how many times the loop code gets unrolled. ๐Ÿ”
  • max-average-unrolled-insns โ€” the maximum number of instructions, biased by the probabilities of their execution, that a loop may have for it to be unrolled. If a loop is unrolled, this parameter also decides how many times the loop code gets unrolled.
  • max-unroll-times โ€” the maximum number of unrollings of a single loop.
  • max-peeled-insns โ€” the maximum number of instructions a loop may have for it to be peeled. If a loop is peeled, this parameter also decides how many times the loop code gets peeled. ๐ŸŒ
  • max-peel-times โ€” the maximum number of peelings of a single loop.
  • max-peel-branches โ€” the maximum number of branches on the hot path through the peeled sequence.
  • max-completely-peeled-insns โ€” the maximum number of insns of a completely peeled loop.
  • max-completely-peel-times โ€” the maximum number of iterations of a loop for it to be suitable for complete peeling.
  • max-completely-peel-loop-nest-depth โ€” the maximum depth of a loop nest suitable for complete peeling.
  • max-unswitch-insns โ€” the maximum number of insns of an unswitched loop.
  • max-unswitch-depth โ€” the maximum depth of a loop nest to be unswitched.
  • lim-expensive โ€” the minimum cost of an expensive expression in loop invariant motion. ๐Ÿ’ธ
  • min-loop-cond-split-prob โ€” when FDO profile information is available, min-loop-cond-split-prob specifies the minimum threshold for the probability of a semi-invariant condition statement to trigger a loop split.
  • iv-consider-all-candidates-bound โ€” the 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 get considered โ€” all to avoid quadratic time complexity. ๐ŸŒ€
  • iv-max-considered-uses โ€” the induction variable optimizations give up on loops that contain more induction variable uses than this.
  • iv-always-prune-cand-set-bound โ€” if the number of candidates in the set is smaller than this value, always try to remove unnecessary ivs from the set when adding a new one. ๐Ÿงน
  • avg-loop-niter โ€” the average number of iterations of a loop.
  • 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. โฐ
  • 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.
  • scev-max-expr-size โ€” a bound on the size of expressions used in the scalar evolutions analyzer. Large expressions slow the analyzer down. ๐Ÿข
  • scev-max-expr-complexity โ€” a bound on the complexity of the expressions in the scalar evolutions analyzer. Complex expressions slow the analyzer down.
  • max-tree-if-conversion-phi-args โ€” the maximum number of arguments in a PHI that TREE if conversion will support, unless the loop is marked with the simd pragma.
  • vect-max-layout-candidates โ€” the maximum number of possible vector layouts (think permutations) to consider when optimizing to-be-vectorized code.
  • 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.
  • 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.
  • 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. ๐Ÿ˜Œ
  • max-iterations-to-track โ€” bestie, this is the cap on how many iterations of a loop the brute-force algorithm (the one analyzing loop iteration counts) will actually sit there and try to evaluate. ๐ŸŒธ
  • hot-bb-count-fraction โ€” the denominator n of the fraction 1/n ๐Ÿ’…. A basic block only counts as "hot" if its execution count is at least 1/n of the biggest execution count any basic block in the whole program got. Default is 10000, so a block is hot if its exec count beats 1/10000 of that max. Set it to 0 and nothing is ever considered hot. This one's for non-LTO mode.
  • hot-bb-count-ws-permille โ€” okay so, the number of most-executed permilles (0 to 1000, yes permille not percent, we're fancy) of the profiled execution of the entire program that a basic block's execution count has to fall inside to be called hot. Default 990 โ†’ a block is hot if its count lands in the top 990 permilles, aka 99.0%, of the profiled execution of the whole program. 0 means never hot, periodt. This one's for LTO mode. โœจ
  • hot-bb-frequency-fraction โ€” the denominator n of fraction 1/n of the entry block's execution frequency ๐Ÿ‘‘. A basic block of a function needs to be executed at least 1/n as often as the function's entry block to be considered hot. Default is 1000, so a block is hot in a function if it runs more frequently than 1/1000 of the entry block's frequency. 0 = never considered hot. No cap.
  • unlikely-bb-count-fraction โ€” the denominator n of fraction 1/n of the number of profiled runs of the entire program, and a basic block's execution count has to be below that line to be considered "unlikely executed." Default is 20, so a block is unlikely-executed if it runs in fewer than 1/20, or 5%, of the program's runs. And 0? That means it's always considered unlikely executed. ๐Ÿ™ˆ
  • max-predicted-iterations โ€” the max number of loop iterations we predict statically. This slaps when a function has one loop with a known bound and another loop with an unknown bound: the known one gets predicted correctly, while the unknown one averages out to roughly 10. Which means the loop without bounds ends up looking artificially cold next to its sibling. ๐Ÿฅถ
  • builtin-expect-probability โ€” controls the probability of the expression having the specified value. Takes a percentage (i.e. 0 ... 100) as input. ๐Ÿ’ฏ
  • builtin-string-cmp-inline-length โ€” the maximum length of a constant string for a builtin string cmp call to be eligible for inlining. ๐ŸŽ€
  • align-threshold โ€” picks the fraction of the maximal execution frequency of a basic block in a function that's needed to align that basic block.
  • align-loop-iterations โ€” a loop that's expected to iterate at least the selected number of iterations gets aligned. โญ
  • tracer-dynamic-coverage, tracer-dynamic-coverage-feedback โ€” this value limits superblock formation once the given percentage of executed instructions is covered. Basically it stops unnecessary code size expansion, thank u next. โœ‹ The tracer-dynamic-coverage-feedback param is only used when profile feedback is available, because real profiles (as opposed to statically estimated ones) are way less balanced, which lets the threshold be a larger value. ๐ŸŒˆ
  • tracer-max-code-growth โ€” stops tail duplication once code growth hits the given percentage. Kinda artificial as a limit ngl, since most of the duplicates get eliminated later during cross jumping, so you can set it way higher than the actual code growth you want. ๐Ÿ’…
  • tracer-min-branch-ratio โ€” stops 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 โ€” stops forward growth if the best edge's probability is lower than this threshold. Same deal as tracer-dynamic-coverage: two params, one for each mode. tracer-min-branch-probability-feedback is for compilation with profile feedback, and tracer-min-branch-probability is for compilation without. Heads up: for profile feedback compilation the value needs to be more conservative (higher) for the tracer to actually be effective. ๐Ÿ‘€
  • stack-clash-protection-guard-size โ€” specifies the size of the operating system provided stack guard as 2 raised to num bytes. Higher values may reduce the number of explicit probes, BUT a value larger than the operating system provided guard will leave your code vulnerable to stack clash style attacks. So likeโ€ฆ don't. ๐Ÿ’€
  • stack-clash-protection-probe-interval โ€” stack clash protection means probing stack space as it gets allocated. This param controls the maximum distance between probes into the stack, as 2 raised to num bytes. Higher values may reduce the number of explicit probes, but again โ€” a value larger than the operating system provided guard leaves code vulnerable to stack clash style attacks. Same warning, same energy. ๐Ÿšจ
  • max-cse-path-length โ€” the maximum number of basic blocks on a path that CSE considers.
  • max-cse-insns โ€” the maximum number of instructions CSE processes before it flushes. ๐Ÿšฝ
  • ggc-min-expand โ€” okay so GCC uses a garbage collector to manage its own memory allocation, and this parameter is the minimum percentage by which the GC's heap is allowed to expand between collections. Tuning it may improve compilation speed; it has no effect on code generation. The default is 30% + 70% * (RAM/1GB) with an upper bound of 100% when RAM >= 1GB. If getrlimit is available, the notion of "RAM" is the smallest of actual RAM and RLIMIT_DATA or RLIMIT_AS. If GCC can't calculate RAM on a particular platform, the lower bound of 30% is used. And setting this parameter and ggc-min-heapsize to zero causes a full collection to occur at every opportunity โ€” extremely slow, but can be useful for debugging. ๐ŸŒ
  • ggc-min-heapsize โ€” minimum size of the garbage collector's heap before it starts bothering to collect garbage. The first collection happens after the heap expands by ggc-min-expand% beyond ggc-min-heapsize. Again, tuning this 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 โ€” 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, and setting it plus ggc-min-expand to zero causes a full collection to occur at every opportunity. Iconic debugging move. ๐Ÿ‘‘
  • max-reload-search-insns โ€” the maximum number of instructions reload should look backward for an equivalent register. Increasing values mean more aggressive optimization, which pumps up compilation time, probably for slightly better performance. โœจ
  • max-cselib-memory-locations โ€” the maximum number of memory locations cselib should take into account. Increasing values mean more aggressive optimization, making compilation time go up with probably slightly better performance.
  • max-sched-ready-insns โ€” the maximum 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 increase with probably little benefit. ๐Ÿ˜ญ
  • max-sched-region-blocks โ€” the maximum number of blocks in a region to be considered for interblock scheduling.
  • max-pipeline-region-blocks โ€” the maximum number of blocks in a region to be considered for pipelining in the selective scheduler.
  • max-sched-region-insns โ€” the maximum number of insns in a region to be considered for interblock scheduling.
  • max-pipeline-region-insns โ€” the maximum number of insns in a region to be considered for pipelining in the selective scheduler.
  • min-spec-prob โ€” the minimum probability (in percents) of reaching a source block for interblock speculative scheduling.
  • max-sched-extend-regions-iters โ€” the maximum number of iterations through CFG to extend regions. A value of 0 disables region extensions entirely. ๐Ÿ›‘
  • max-sched-insn-conflict-delay โ€” the maximum conflict delay for an insn to be considered for speculative motion.
  • sched-spec-prob-cutoff โ€” the minimal probability of speculation success (in percents) so that speculative insns 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 โ€” minimal distance (in CPU cycles) between a store and a load targeting the same memory locations.
  • selsched-max-lookahead โ€” the maximum size of the lookahead window of selective scheduling. It's a depth of search for available instructions. ๐Ÿ”
  • selsched-max-sched-times โ€” the maximum number of times an instruction is scheduled during selective scheduling. It's the limit on the number of iterations through which the instruction may be pipelined.
  • selsched-insns-to-rename โ€” the maximum number of best instructions in the ready list that get considered for renaming in the selective scheduler. ๐Ÿ’…
  • sms-min-sc โ€” the minimum value of stage count that swing modulo scheduler generates. ๐Ÿฆ‹

๐ŸŽ€ max-last-value-rtl

The biggest size โ€” measured as a count of RTLs โœจ โ€” that can be stashed in an expression in the combiner for a pseudo register playing the role of that register's last known value. That's literally it bestie.


๐Ÿ’… max-combine-insns

The max number of instructions the RTL combiner will even attempt to combine. Like, it's got a limit and it respects it. Periodt.


๐Ÿ“ integer-share-limit

Small integer constants can share a data structure (so cute, so communal ๐Ÿ’–), which cuts down the compiler's memory usage and makes it faster. This one sets the maximum value of a shared integer constant.


๐Ÿฆ‹ ssp-buffer-size

The minimum size of buffers (i.e. arrays) that get stack smashing protection when -fstack-protector is on.

Heads up: this default was "8" before Ubuntu 10.10. 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 you're not optimizing. No optimization, no big sharing energy.


โญ max-jump-thread-duplication-stmts

Max number of statements allowed in a block that needs to be duplicated when threading jumps. That's the ceiling, girlie.


๐Ÿงš max-jump-thread-paths

The max number of paths to consider when hunting for jump threading opportunities. Here's the tea โ˜•: when you arrive at a block, incoming edges are only considered if the number of paths to be searched so far multiplied by the number of incoming edges does not exhaust the specified maximum number of paths to consider.


๐Ÿ‘‘ max-fields-for-field-sensitive

Max number of fields in a structure that get treated in a field sensitive manner during pointer analysis. Structure said "I'm sensitive" and the analyzer said "okay noted."


๐Ÿ”ฅ prefetch-latency

An estimate of, on average, how many instructions get executed before the prefetch finishes. The distance prefetched ahead is proportional to this constant. Ramping this number up may also lead to fewer streams being prefetched (go peek at simultaneous-prefetches).


๐Ÿ’œ simultaneous-prefetches

Max number of prefetches that can be running at the same time. Multitasking icon behavior.


๐ŸŒˆ l1-cache-line-size

The size of a cache line in L1 data cache, in bytes.


โœจ l1-cache-size

The size of L1 data cache, in kilobytes.


โœจ l2-cache-size

The size of L2 data cache, in kilobytes. (Yes bestie, same unit energy as L1.)


๐Ÿซถ prefetch-dynamic-strides

Should the loop array prefetch pass drop software prefetch hints for strides that are non-constant? Sometimes that's genuinely beneficial โ€” though the fact that the stride is non-constant may make 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 be issued only 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. Simple as that.

This setting slays 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, you should use it 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.

Ngl, this setting is only useful for strides that are known and constant. No guessing games.

๐ŸŒŸ destructive-interference-size / constructive-interference-size

These two are the values for the C++17 variables std::hardware_destructive_interference_size and std::hardware_constructive_interference_size. ๐Ÿ‘ฏ

  • The destructive interference size is the minimum recommended offset between two independent concurrently-accessed objects.
  • The constructive interference size is the maximum recommended size of contiguous memory accessed together.

Typically both of them will be the size of an L1 cache line for the target, in bytes. For a generic target covering a range of L1 cache line sizes, typically the constructive interference size will be the small end of the range and the destructive size will be the large end.

The destructive interference size is intended to be used for layout, and thus it has ABI impact. ๐Ÿ˜ญ The default value is not expected to be stable, and on some targets it varies with -mtune โ€” so using this variable in a context where ABI stability is important, like the public interface of a library, is strongly discouraged. If you do use it in that context, users can stabilize the value using this option.

The constructive interference size is less sensitive, since it's typically only used in a static_assert to make sure that a type fits within a cache line. ๐Ÿ’…

See also -Winterference-size.


๐ŸŽ€ loop-interchange-max-num-stmts

The maximum number of stmts in a loop to be interchanged. Cap it, bestie.


๐Ÿงš loop-interchange-stride-ratio

The minimum ratio between the strides of two loops for an interchange to even be profitable. If it ain't worth it, we don't do it. โœ‹


๐Ÿ“ min-insn-to-prefetch-ratio

The minimum ratio between the number of instructions and the number of prefetches needed 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 needed to enable prefetching in a loop. Sibling energy with the one above.


๐ŸŒธ use-canonical-types

Should the compiler use the "canonical" type system? It should always be 1 โ€” that's the version that 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. Emergency mode activated. ๐Ÿšจ

โญ 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. That's the rule and it's not negotiating.


๐Ÿ”ฅ max-partial-antic-length

Maximum length of the partial antic set computed during the tree partial redundancy elimination optimization (-ftree-pre) when optimizing at -O3 and above.

Okay this one matters: for some sorts of source code, the enhanced partial redundancy elimination optimization can run away, consuming all of the memory available on the host machine. ๐Ÿ’€ This parameter sets a limit on the length of the sets that are computed, which prevents that runaway behavior. Setting a value of 0 for this parameter allows an unlimited set length โ€” so like, you've been warned.

๐Ÿ‘‘ rpo-vn-max-loop-depth

Maximum loop depth that gets value-numbered optimistically. When the limit hits, the innermost rpo-vn-max-loop-depth loops and the outermost loop in the loop nest are value-numbered optimistically, and the remaining ones are not. Iconic selective behavior honestly.


๐Ÿ’œ sccvn-max-alias-queries-per-access

Maximum number of alias-oracle queries we perform when looking for redundancies for loads and stores. If this limit gets hit, the search is aborted and that load or store is not considered redundant.

Fun fact: 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. Only the popular loops get the spotlight. ๐ŸŒŸ


๐Ÿซถ ira-max-conflict-table-size

Even though IRA uses a sophisticated algorithm to compress the conflict table, the table can still require excessive amounts of memory for huge functions. ๐Ÿ˜ญ If the conflict table for a function could be more than the size in MB given by this parameter, the register allocator instead uses a faster, simpler, and lower-quality algorithm that does not require building a pseudo-register conflict table. Trade-offs, bestie!


๐Ÿ’€ ira-loop-reserved-regs

IRA can be used to evaluate more accurate register pressure in loops for decisions to move loop invariants (see -O3). The number of available registers reserved for some other purposes is given by this parameter. The default of the parameter is the best one found from numerous experiments. Science! ๐Ÿ”ฌ


โœจ ira-consider-dup-in-all-alts

Makes IRA consider the matching constraint (duplicated operand number) heavily in all available alternatives for the preferred register class.

  • If it's set as zero, it means IRA only respects the matching constraint when it's in the only available alternative with an appropriate register class.
  • Otherwise, it means IRA will check all available alternatives for the preferred register class, even if it has already found some choice with an appropriate register class, and respect the found qualified matching constraint.

๐ŸŽ€ ira-simple-lra-insn-threshold

Approximate function insn number in 1K units triggering simple local RA. Approximate is the key word here, she's estimating. ๐Ÿ™ˆ


๐Ÿ“ lra-inheritance-ebb-probability-cutoff

LRA tries to reuse values reloaded in registers in subsequent insns. This optimization is called inheritance (so cute, passing things down ๐Ÿฅน). EBB is used as the region to do this optimization. The parameter defines a minimal fall-through edge probability, in percentage, used to add a BB to the inheritance EBB in LRA.

The default value was chosen from numerous runs of SPEC2000 on x86-64. Very researched, very slay.


๐Ÿงš 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. Sorry girl, too big, no motion for you. ๐Ÿ’…


๐Ÿ’– 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 that use loop data dependencies. Big loops, big feelings, no datadeps. ๐Ÿ˜Œ

  • max-vartrack-size โ€” okay bestie, this 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 โ€” this one sets a maximum number of recursion levels when attempting to map variable names or debug temporaries to value expressions. It's literally trading compilation time for more complete debug information. If you set it too low, value expressions that are available and could be represented in debug information may end up not being used; setting this higher may enable the compiler to find more complex debug expressions, but compile time and memory use may grow. ๐ŸŒ€
  • max-debug-marker-count โ€” sets a threshold on the number of debug markers (e.g. begin stmt markers) to avoid complexity explosion at inlining or expanding to RTL. If a function has more such gimple stmts than the set limit, such stmts will be dropped from the inlined copy of a function, and from its RTL expansion. ๐Ÿ’€
  • min-nondebug-insn-uid โ€” use uids starting at this parameter for nondebug insns. The range below the parameter is reserved exclusively for debug insns created by -fvar-tracking-assignments, but debug insns may get (non-overlapping) uids above it if the reserved range is exhausted. โœจ
  • ipa-sra-deref-prob-threshold โ€” IPA-SRA replaces a pointer which is known not be NULL with one or more new parameters only when the probability (in percent, relative to function entry) of it being dereferenced is higher than this parameter. ๐Ÿ‘‘
  • ipa-sra-ptr-growth-factor โ€” IPA-SRA replaces a pointer to an aggregate with one or more new parameters only when their cumulative size is less or equal to ipa-sra-ptr-growth-factor times the size of the original pointer parameter. ๐ŸŒธ
  • ipa-sra-ptrwrap-growth-factor โ€” additional maximum allowed growth of total size of new parameters that ipa-sra replaces a pointer to an aggregate with, if it points to a local variable that the caller only writes to and passes it as an argument to other functions. ๐ŸŽ€
  • ipa-sra-max-replacements โ€” maximum pieces of an aggregate that IPA-SRA tracks. As a consequence, it is also the maximum number of replacements of a formal parameter. ๐Ÿฆ‹
  • sra-max-scalarization-size-Ospeed, sra-max-scalarization-size-Osize โ€” the two Scalar Reduction of Aggregates passes (SRA and IPA-SRA) aim to replace scalar parts of aggregates with uses of independent scalar variables. These parameters control the maximum size, in storage units, of aggregate which is considered for replacement when compiling for speed (sra-max-scalarization-size-Ospeed) or size (sra-max-scalarization-size-Osize) respectively. โšก
  • sra-max-propagations โ€” the maximum number of artificial accesses that Scalar Replacement of Aggregates (SRA) will track, per one local variable, in order to facilitate copy propagation. ๐Ÿ”„
  • tm-max-aggregate-size โ€” when making copies of thread-local variables in a transaction, this parameter specifies the size in bytes after which variables are saved with the logging functions as opposed to save/restore code sequence pairs. This option only applies when using -fgnu-tm. ๐Ÿ’พ
  • graphite-max-nb-scop-params โ€” to avoid exponential effects in the Graphite loop transforms, the number of parameters in a Static Control Part (SCoP) is bounded. A value of zero can be used to lift the bound. A variable whose value is unknown at compilation time and defined outside a SCoP is a parameter of the SCoP. ๐Ÿ“Š
  • loop-block-tile-size โ€” loop blocking or strip mining transforms, enabled with -floop-block or -floop-strip-mine, strip mine each loop in the loop nest by a given number of iterations. The strip length can be changed using the loop-block-tile-size parameter. ๐Ÿงฑ
  • ipa-jump-function-lookups โ€” specifies number of statements visited during jump function offset discovery. ๐Ÿ•ต๏ธ
  • ipa-cp-value-list-size โ€” IPA-CP attempts to track all possible values and types passed to a function's parameter in order to propagate them and perform devirtualization. ipa-cp-value-list-size is the maximum number of values and types it stores per one formal parameter of a function. ๐Ÿ“
  • ipa-cp-eval-threshold โ€” IPA-CP calculates its own score of cloning profitability heuristics and performs those cloning opportunities with scores that exceed ipa-cp-eval-threshold. ๐ŸŽฏ
  • ipa-cp-max-recursive-depth โ€” maximum depth of recursive cloning for self-recursive function. ๐Ÿ”
  • ipa-cp-min-recursive-probability โ€” recursive cloning only when the probability of call being executed exceeds the parameter. ๐ŸŽฒ
  • ipa-cp-profile-count-base โ€” when using -fprofile-use option, IPA-CP will consider the measured execution count of a call graph edge at this percentage position in their histogram as the basis for its heuristics calculation. ๐Ÿ“ˆ
  • ipa-cp-recursive-freq-factor โ€” the number of times interprocedural copy propagation expects recursive functions to call themselves. โ™ป๏ธ
  • ipa-cp-recursion-penalty โ€” percentage penalty the recursive functions will receive when they are evaluated for cloning. ๐Ÿ“‰
  • ipa-cp-single-call-penalty โ€” percentage penalty functions containing a single call to another function will receive when they are evaluated for cloning. ๐Ÿ“‰
  • ipa-max-agg-items โ€” IPA-CP is also capable to propagate a number of scalar values passed in an aggregate. ipa-max-agg-items controls the maximum number of such values per one parameter. ๐Ÿ“ฆ
  • ipa-cp-loop-hint-bonus โ€” when IPA-CP determines 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 the profitability score of the candidate. ๐ŸŽ
  • 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 โ€” during its analysis of function bodies, IPA-CP employs alias analysis in order to track values pointed to by function parameters. In order not spend too much time analyzing huge functions, it gives up and consider all memory clobbered after examining ipa-max-aa-steps statements modifying memory. ๐Ÿ›‘
  • ipa-max-switch-predicate-bounds โ€” maximal number of boundary endpoints of case ranges of switch statement. For switch exceeding this limit, IPA-CP will not construct cloning cost predicate, which is used to estimate cloning benefit, for default case of the switch statement. ๐Ÿ”€
  • ipa-max-param-expr-ops โ€” IPA-CP will analyze conditional statement that references some function parameter to estimate benefit for cloning upon certain constant value. But if number of operations in a parameter expression exceeds ipa-max-param-expr-ops, the expression is treated as complicated one, and is not handled by IPA analysis. ๐Ÿคฏ
  • lto-partitions โ€” specify desired number of partitions produced during WHOPR compilation. The number of partitions should exceed the number of CPUs used for compilation. ๐Ÿ–ฅ๏ธ
  • lto-min-partition โ€” size of minimal partition for WHOPR (in estimated instructions). This prevents expenses of splitting very small programs into too many partitions. โœ‚๏ธ
  • lto-max-partition โ€” size of max partition for WHOPR (in estimated instructions). to provide an upper bound for individual size of partition. Meant to be used only with balanced partitioning. ๐Ÿ“
  • lto-max-streaming-parallelism โ€” maximal number of parallel processes used for LTO streaming. ๐Ÿš€
  • cxx-max-namespaces-for-diagnostic-help โ€” the maximum number of namespaces to consult for suggestions when C++ name lookup fails for an identifier. ๐Ÿง
  • sink-frequency-threshold โ€” the maximum relative execution frequency (in percents) of the target block relative to a statement's original block to allow statement sinking of a statement. Larger numbers result in more aggressive statement sinking. A small positive adjustment is applied for statements with memory operands as those are even more profitable so sink. โฌ‡๏ธ
  • max-stores-to-sink โ€” the maximum number of conditional store pairs that can be sunk. Set 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 is 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). The parameter is used when optimizing for size. ๐Ÿ“
  • jump-table-max-growth-ratio-for-speed โ€” the maximum code size growth ratio when expanding into a jump table (in percent). The parameter is used when optimizing for speed. ๐ŸŽ๏ธ
  • tree-reassoc-width โ€” set the maximum number of instructions executed in parallel in reassociated tree. This parameter overrides target dependent heuristics used by default if has non zero value. ๐ŸŒณ
  • sched-pressure-algorithm โ€” picks which of the two implementations of -fsched-pressure you want, bestie. Algorithm 1 is the OG one and it's the one more likely to stop instructions from getting reordered. Algorithm 2 was built as a compromise between algorithm 1's relatively conservative vibe and the honestly-kind-of-aggressive approach the default scheduler takes. It leans way harder on having a regular register file and accurate register pressure classes. Peep haifa-sched.cc in the GCC sources for the full lore. The default choice depends on the target. ๐Ÿ’…
  • max-slsr-cand-scan โ€” sets the max number of existing candidates we look at when hunting for a basis for a new straight-line strength reduction candidate.
  • asan-globals โ€” turns on buffer overflow detection for global objects. This kind of protection is on by default if you're using -fsanitize=address. To turn off global objects protection, use --param asan-globals=0.
  • asan-stack โ€” turns on buffer overflow detection for stack objects. On by default when using -fsanitize=address. To turn off stack protection, use --param asan-stack=0.
  • asan-instrument-reads โ€” turns on buffer overflow detection for memory reads. On by default when using -fsanitize=address. To turn off memory reads protection, use --param asan-instrument-reads=0.
  • asan-instrument-writes โ€” turns on buffer overflow detection for memory writes. On by default when using -fsanitize=address. To turn off memory writes protection, use --param asan-instrument-writes=0.
  • asan-memintrin โ€” turns on detection for built-in functions. On by default when using -fsanitize=address. To turn off built-in functions protection, use --param asan-memintrin=0.
  • asan-use-after-return โ€” turns on detection of use-after-return. On by default when using the -fsanitize=address option. To turn it off, use --param asan-use-after-return=0.
Note: by default this 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 the function being instrumented is greater than or equal to this number, use callbacks instead of inline checks. Like, to disable inline code, use --param asan-instrumentation-with-call-threshold=0.
  • asan-kernel-mem-intrinsic-prefix โ€” if nonzero, prefix calls to "memcpy", "memset" and "memmove" with __asan_ or __hwasan_ for -fsanitize=kernel-address or -fsanitize=kernel-hwaddress, respectively.
  • hwasan-instrument-stack โ€” turns on hwasan instrumentation of statically sized stack-allocated variables. This is on by default when using -fsanitize=hwaddress and off 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, decides tags for stack variables using a deterministic sequence that begins at a random tag for each frame. With this parameter unset, tags are chosen using the same sequence but beginning from 1. Enabled by default for -fsanitize=hwaddress and unavailable for -fsanitize=kernel-hwaddress. To disable it use --param hwasan-random-frame-tag=0.
  • hwasan-instrument-allocas โ€” turns on hwasan instrumentation of dynamically sized stack-allocated variables. On by default when using -fsanitize=hwaddress, off by default when using -fsanitize=kernel-hwaddress. To disable instrumentation of those variables use --param hwasan-instrument-allocas=0, and to enable it use --param hwasan-instrument-allocas=1.
  • hwasan-instrument-reads โ€” turns on hwasan checks on memory reads. Instrumentation of reads is on 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 on memory writes. Instrumentation of writes is on by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. To disable checking memory writes use --param hwasan-instrument-writes=0.
  • hwasan-instrument-mem-intrinsics โ€” turns on hwasan instrumentation of builtin functions. Instrumentation of these builtin functions is on by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. To disable instrumentation of builtin functions use --param hwasan-instrument-mem-intrinsics=0.
  • use-after-scope-direct-emission-threshold โ€” if the size of a local variable in bytes is smaller than or equal to this number, directly poison (or unpoison) shadow memory instead of using run-time callbacks.
  • tsan-distinguish-volatile โ€” emits special instrumentation for accesses to volatiles.
  • tsan-instrument-func-entry-exit โ€” emits instrumentation calls to __tsan_func_entry() and __tsan_func_exit().
  • max-fsm-thread-path-insns โ€” max number of instructions to copy when duplicating blocks on a finite state automaton jump thread path.
  • threader-debug โ€” threader-debug=[none|all] enables verbose dumping of the threader solver.
  • parloops-chunk-size โ€” the chunk size of 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).
  • parloops-min-per-thread โ€” the minimum number of iterations per thread of an innermost parallelized loop for which the parallelized variant is preferred over the single threaded one. 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 โ€” max depth of recursion when querying properties of SSA names in things like fold routines. One level of recursion = following a use-def chain.
  • max-speculative-devirt-maydefs โ€” the max number of may-defs we analyze when we're looking for a must-def that specifies the dynamic type of an object that invokes a virtual call we might be able to devirtualize speculatively.
  • evrp-sparse-threshold โ€” max number of basic blocks before EVRP uses a sparse cache.
  • ranger-debug โ€” specifies the type of debug output to be issued for ranges.
  • evrp-switch-limit โ€” specifies the max number of switch cases before EVRP ignores a switch.
  • unroll-jam-min-percent โ€” the minimum percentage of memory references that must be optimized away for the unroll-and-jam transformation to be considered profitable.
  • unroll-jam-max-unroll โ€” the max number of times the outer loop should be unrolled by the unroll-and-jam transformation.
  • max-rtl-if-conversion-unpredictable-cost โ€” max permissible cost for the sequence that would be generated by the RTL if-conversion pass for a branch that's considered unpredictable.
  • max-variable-expansions-in-unroller โ€” if -fvariable-expansion-in-unroller is used, the max number of times that an individual variable will be expanded during loop unrolling.
  • partial-inlining-entry-probability โ€” max probability of the entry BB of a split region (in percent, relative to the entry BB of the function) to make partial inlining happen.
  • max-tracked-strlens โ€” max number of strings for which the strlen optimization pass will track string lengths.
  • gcse-after-reload-partial-fraction โ€” the threshold ratio for performing partial redundancy elimination after reload.
  • gcse-after-reload-critical-fraction โ€” the threshold ratio of critical edges execution count that permits performing redundancy elimination after reload.
  • max-loop-header-insns โ€” the max number of insns in a loop header duplicated by the copy loop headers pass.
  • vect-epilogues-nomask โ€” enables loop epilogue vectorization using a smaller vector size.
  • vect-partial-vector-usage โ€” controls when the loop vectorizer considers using partial vector loads and stores as an alternative to falling back to scalar code. 0 stops the vectorizer from ever using partial vector loads and stores. 1 allows partial vector loads and stores if vectorization removes the need for the code to iterate. 2 allows partial vector loads and stores in all loops. This parameter only has an effect on targets that support partial vector loads and stores.
  • vect-inner-loop-cost-factor โ€” the max factor which the loop vectorizer applies to the cost of statements in an inner loop relative to the loop being vectorized. The factor applied is the maximum of the estimated number of iterations of the inner loop and this parameter. The default value of this parameter is 50.
  • vect-induction-float โ€” enables loop vectorization of floating point inductions.
  • avoid-fma-max-bits โ€” max number of bits for which we avoid creating FMAs.
  • sms-loop-average-count-threshold โ€” a threshold on the average loop count considered by the swing modulo scheduler.
  • sms-dfa-history โ€” the number of cycles the swing modulo scheduler considers when checking conflicts using DFA.
  • graphite-allow-codegen-errors โ€” whether codegen errors should be ICEs when -fchecking.
  • sms-max-ii-factor โ€” a factor for tuning the upper bound that the swing modulo scheduler uses for scheduling a loop.
  • lra-max-considered-reload-pseudos โ€” the max number of reload pseudos we're willing to consider while spilling a non-reload pseudo. it's giving "how many backups can we juggle" energy ๐Ÿ’…
  • max-pow-sqrt-depth โ€” max depth of sqrt chains to use when synthesizing exponentiation by a real constant. nesting go brrr ๐ŸŒธ
  • max-dse-active-local-stores โ€” the maximum number of active local stores in RTL dead store elimination. bye bye dead stores ๐Ÿ’€
  • asan-instrument-allocas โ€” turns on asan allocas/VLAs protection. safety girlies rise โœจ
  • max-iterations-computation-cost โ€” a bound on the cost of an expression when we compute the number of iterations.
  • max-isl-operations โ€” maximum number of isl operations, and 0 means unlimited. no cap, fr fr ๐Ÿงš
  • graphite-max-arrays-per-scop โ€” maximum number of arrays per scop.
  • max-vartrack-reverse-op-size โ€” max size of the loc list for which reverse ops should be added.
  • fsm-scale-path-stmts โ€” the scale factor to apply to the number of statements in a threading path crossing a loop backedge when comparing to --param=max-jump-thread-duplication-stmts.
  • uninit-control-dep-attempts โ€” maximum number of nested calls used to search for control dependencies during uninitialized variable analysis.
  • uninit-max-chain-len โ€” the maximum number of predicates anded for each predicate ored in the normalized predicate chain.
  • uninit-max-num-chains โ€” the maximum number of predicates ored in the normalized predicate chain.
  • sched-autopref-queue-depth โ€” hardware autoprefetcher scheduler model control flag. it's the number of lookahead cycles the model looks into; at ' ' it only enables the instruction sorting heuristic.
  • 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. no copying oversized loops, periodt
  • 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, 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 in determining a property of a variable (like its value). this caps the number of iterations or recursive calls GCC does when optimizing certain statements, or when checking their validity before it drops diagnostics.
  • store-merging-max-size โ€” 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 โ€” 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 stops analyzing 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 before the analyzer will even 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 stops analyzing a call that would recurse deeper.
  • analyzer-max-svalue-depth โ€” the maximum depth of a symbolic value before the value gets approximated 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 which counts as hot. this parameter is used only in GIMPLE FE.
  • analyzer-bb-explosion-factor โ€” the maximum number of 'after supernode' exploded nodes within the analyzer per supernode, before it stops analyzing.
  • ranger-logical-depth โ€” maximum depth of logical expression evaluation the ranger will look through when evaluating outgoing edge ranges.
  • ranger-recompute-depth โ€” maximum depth of instruction chains to consider for recomputation in the outgoing range calculator.
  • relation-block-limit โ€” maximum number of relations the oracle will register in a basic block.
  • min-pagesize โ€” minimum page size, for warning purposes.
  • openacc-kernels โ€” specifies the mode of OpenACC kernels constructs handling. with --param=openacc-kernels=decompose, OpenACC kernels constructs get decomposed into parts โ€” a sequence of compute constructs, each then handled individually. this is work in progress, bestie, don't @ me. with --param=openacc-kernels=parloops, OpenACC kernels constructs are handled by the parloops pass, en bloc. this is the current default. ๐Ÿ‘‘
  • openacc-privatization โ€” controls whether the -fopt-info-omp-note and applicable -fdump-tree-*-details options emit OpenACC privatization diagnostics. with --param=openacc-privatization=quiet, don't diagnose โ€” this is the current default. with --param=openacc-privatization=noisy, do diagnose. pick your vibe ๐ŸŒˆ

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. also use the cost model to choose between SVE and Advanced SIMD vectorization.

using unpacked vectors includes storing smaller elements in larger containers and accessing elements with extending loads and truncating stores.

  • aarch64-float-recp-precision โ€” the number of Newton iterations for calculating the reciprocal for float type. the precision of division is proportional to this param when division approximation is enabled. the default value is 1.
  • aarch64-double-recp-precision โ€” the number of Newton iterations for calculating the reciprocal for double type. the precision of division is propotional to this param when division approximation is enabled. the default value is 2. (yes they wrote "propotional" and yes i'm keeping it, no i will not be fixing it ๐Ÿ’…)
  • aarch64-autovec-preference โ€” forces an ISA selection strategy for auto-vectorization. accepts values from 0 to 4, inclusive:
    1. 0 โ€” use the default heuristics.
    2. 1 โ€” use only Advanced SIMD for auto-vectorization.
    3. 2 โ€” use only SVE for auto-vectorization.
    4. 3 โ€” use both Advanced SIMD and SVE. prefer Advanced SIMD when the costs are deemed equal.
    5. 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.
  • aarch64-vect-unroll-limit โ€” the vectorizer will use available tuning information to determine whether it would be beneficial to unroll the main vectorized loop, and by how much. this parameter sets the upper bound of how much the vectorizer will unroll the main loop. the default value is four. slay โœจ

the following choices of name are available on i386 and x86_64 targets:

  • x86-stlf-window-ninsns โ€” instructions number above which STFL stall penalty can be compensated.
  • x86-stv-max-visits โ€” the maximum number of use and def visits when discovering a STV chain before the discovery is aborted.

๐ŸŽ€ Program Instrumentation Options ๐ŸŽ€

okay so GCC supports a whole bunch of command-line options that control adding run-time instrumentation to the code it normally generates. for example, one purpose of instrumentation is to collect profiling statistics โ€” for finding program hot spots, 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 like 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. so many vibes, so many options ๐Ÿฆ‹

  • -p<br>-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, both times ๐Ÿ”ฅ

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 get 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. chef's kiss ๐Ÿ‘‘

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

Bestie quick lil heads-up before we go any further: when a command line links source files directly, the matching .gcda files get prefixed with the unsuffixed name of the output file. So like, "gcc a.c b.c -o binary" would pop out binary-a.gcda and binary-b.gcda. Noted. ๐Ÿ’…


  • --coverage โ€” the glow-up option for compiling and linking code that's instrumented for coverage analysis. It's literally just a synonym for -fprofile-arcs -ftest-coverage (when you're compiling) and -lgcov (when you're linking). Go read those options' docs for the deets. โœจ
    • Compile the source files with -fprofile-arcs plus your optimization and code generation options. For test coverage analysis, also toss in -ftest-coverage. You do not need to profile every single source file in a program, ok? ๐Ÿซถ
    • Compile the source files additionally with -fprofile-abs-path to create absolute path names in the .gcno files. This lets gcov find the correct sources in projects where compilations happen with different working directories. iconic behavior.
    • Link your object files with -lgcov or -fprofile-arcs (the latter implies the former, she's generous like that).
    • Run the program on a representative workload to generate the arc profile information. You can do this any number of times, no cap. Concurrent instances of your program? Totally fine โ€” provided the file system supports locking, the data files will be correctly updated. And unless a strict ISO C dialect option is in effect, "fork" calls are detected and correctly handled without double counting.
    • Moreover (๐Ÿ’€ fancy word), an object file can be recompiled multiple times and the corresponding .gcda file merges, as long as the source file and the compiler options are unchanged.
    • For profile-directed optimizations, compile the source files again with the same optimization and code generation options plus -fbranch-probabilities.
    • For test coverage analysis, use gcov to produce human readable information from the .gcno and .gcda files. Refer to the gcov documentation for further information.

With -fprofile-arcs, for each function of your program GCC creates a program flow graph, then finds a spanning tree for the graph. Only arcs that are not on the spanning tree have to be instrumented: the compiler adds code to count the number of times that these arcs are executed. When an arc is the only exit or only entrance to a block, the instrumentation code can be added to the block; otherwise, a new basic block must be created to hold the instrumentation code. ๐ŸŒˆ

  • -ftest-coverage โ€” produces 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. Heads up bestie: coverage data matches the source files more closely if you do not optimize. โœจ
  • -fprofile-abs-path โ€” automatically converts relative source file names to absolute path names in the .gcno files. This allows gcov to find the correct sources in projects where compilations occur with different working directories. She's organized like that. ๐Ÿ’…
  • -fprofile-dir=path โ€” sets the directory to search for the profile data files in to path. This option affects only the profile data generated by -fprofile-generate, -ftest-coverage, -fprofile-arcs and used by -fprofile-use and -fbranch-probabilities and its related options. Both absolute and relative paths can be used. By default, GCC uses the current directory as path, so the profile data file appears in the same directory as the object file. In order to prevent the file name clashing, if the object file name is not an absolute path, we mangle the absolute path of the sourcename.gcda file and use it as the file name of a .gcda file. See details about the file naming in -fprofile-arcs. See similar option -fprofile-note. ๐Ÿฆ‹

When an executable is run in a massive parallel environment, it 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 โ€” enables options usually used for instrumenting an application to produce a profile useful for later recompilation with profile feedback based optimization. You must use -fprofile-generate both when compiling and when linking your program. no skipping steps, ok? ๐Ÿ™ˆ

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 โ€” registers 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 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 freestanding environments (for example embedded systems) with limited resources which do not support constructors/destructors or the C library file I/O. ๐Ÿ“

The linker could collect the input sections in a continuous memory block and define start and end symbols. A GNU linker script example which defines a linker output section follows:

.gcov_info      :
{
  PROVIDE (__gcov_info_start = .);
  KEEP (*(.gcov_info))
  PROVIDE (__gcov_info_end = .);
}

The program could dump the profiling information registered in this linker set for example like this:

#include <gcov.h>
#include <stdio.h>
#include <stdlib.h>

extern const struct gcov_info *const __gcov_info_start[];
extern const struct gcov_info *const __gcov_info_end[];

static void
dump (const void *d, unsigned n, void *arg)
{
  const unsigned char *c = d;

  for (unsigned i = 0; i < n; ++i)
    printf ("%02x", c[i]);
}

static void
filename (const char *f, void *arg)
{
  __gcov_filename_to_gcfn (f, dump, arg );
}

static void *
allocate (unsigned length, void *arg)
{
  return malloc (length);
}

static void
dump_gcov_info (void)
{
  const struct gcov_info *const *info = __gcov_info_start;
  const struct gcov_info *const *end = __gcov_info_end;

  /* Obfuscate variable to prevent compiler optimizations.  */
  __asm__ ("" : "+r" (info));

  while (info != end)
  {
    void *arg = NULL;
    __gcov_info_to_gcda (*info, filename, dump, allocate, arg);
    putchar ('\n');
    ++info;
  }
}

int
main (void)
{
  dump_gcov_info ();
  return 0;
}

The merge-stream subcommand of gcov-tool may be used to deserialize the data stream generated by the "__gcov_filename_to_gcfn" and "__gcov_info_to_gcda" functions and merge the profile information into .gcda files on the host filesystem. ๐Ÿงš

  • -fprofile-note=path โ€” if path is specified, GCC saves .gcno file into path location. โš ๏ธ If you combine the option with multiple source files, the .gcno file will be overwritten. be careful bestie.
  • -fprofile-prefix-path=path โ€” this option can be used in combination with profile-generate=profile_dir and profile-use=profile_dir to inform GCC where is the base directory of built source tree. By default profile_dir will contain files with mangled absolute paths of all object files in the built project. This is not desirable when the directory used to build the instrumented binary differs from the directory used to build the binary optimized with profile feedback, because the profile data will not be found during the optimized build. In such setups -fprofile-prefix-path=path with path pointing to the base directory of the build can be used to strip the irrelevant part of the path and keep all file names relative to the main build directory. ๐Ÿ’œ
  • -fprofile-prefix-map=old=new โ€” when compiling files residing in directory old, record profiling information (with --coverage) describing them as if the files resided in directory new instead. See also -ffile-prefix-map and -fcanon-prefix-map.
  • -fprofile-update=method โ€” alters the update method for an application instrumented for profile feedback based optimization. The method argument should be one of single, atomic or prefer-atomic. The first one is useful for single-threaded applications, while the second one prevents profile corruption by emitting thread-safe code. ๐Ÿ”ฅ
Warning: when an application does not properly join all threads (or creates an detached thread), a profile file can be still corrupted.

Using prefer-atomic would be transformed either to atomic, when supported by a target, or to single otherwise. The GCC driver automatically selects prefer-atomic when -pthread is present in the command line. she's got main character energy fr fr.

  • -fprofile-filter-files=regex โ€” instrument 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'. ate. ๐Ÿ’…

  • -fprofile-exclude-files=regex โ€” instrument only functions from files whose name does not match any of the regular expressions (separated by semi-colons). the inverse queen. ๐Ÿ‘‘

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] โ€” okay so this one is your โœจreproducibility control knobโœจ for profiles gathered by -fprofile-generate. The whole point: rebuild a program and get the same outcome every time, which is lowkey a big deal for distro packages. ๐Ÿ’–

With -fprofile-reproducible=serial, the profile gathered by -fprofile-generate is reproducible โ€” as long as the trained program behaves the same every single time you run the train run, it's not multi-threaded, and profile data streaming always happens in the same order. Heads up bestie: profile streaming happens at the end of the program run and also before fork is invoked. ๐Ÿซถ

Real talk though: it's pretty common that execution counts of some part of a program depend on stuff like the length of temporary file names or memory space randomization (which can affect hash-table collision rate ๐Ÿ˜ญ). You can annotate that non-reproducible part of your program with the no_instrument_function function attribute. And gcov-dump with -l will dump the gathered data so you can verify it's actually reproducible. Periodt.

With -fprofile-reproducible=parallel-runs, the collected profile stays reproducible no matter what order the data streams into the gcda files. This is the one that lets you run multiple instances of the instrumented program in parallel (think make -j). Fair warning: it reduces the quality of the gathered data, especially for indirect call profiling. ๐Ÿ™ˆ

  • -fsanitize=address โ€” turns on AddressSanitizer, a fast memory error detector. Memory access instructions get instrumented to catch out-of-bounds and use-after-free bugs. ๐Ÿ‘‘

This option also enables -fsanitize-address-use-after-scope. More deets at https://github.com/google/sanitizers/wiki/AddressSanitizer.

The run-time behavior can be influenced using the ASAN_OPTIONS environment variable โ€” when you set it to help=1, all the available options get shown at startup of the instrumented program. List of supported options here: https://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flags.

โš ๏ธ This option cannot be combined with -fsanitize=thread or -fsanitize=hwaddress.

Also ngl, the only targets -fsanitize=hwaddress is currently supported on are x86-64 (and only with the -mlam=u48 or -mlam=u57 options) and AArch64 โ€” and in both cases, only in ABIs with 64-bit pointers.

For more accurate stack traces, you can use options like -O0, -O1, or -Og (which, for instance, prevent most function inlining), -fno-optimize-sibling-calls (which stops sibling and tail recursive calls from being optimized โ€” it's implicit for -O0, -O1, or -Og anyway), or -fno-ipa-icf (which disables Identical Code Folding for functions). And since multiple runs of a program may give backtraces with different addresses because of ASLR (Address Space Layout Randomization), you might want to turn ASLR off. On Linux you do that with:

setarch `uname -m` -R ./prog
  • -fsanitize=kernel-address โ€” AddressSanitizer, but for the Linux kernel. ๐ŸŒธ More at https://github.com/google/kernel-sanitizers.
  • -fsanitize=hwaddress โ€” enables Hardware-assisted AddressSanitizer, which flexes 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 get instrumented to catch out-of-bounds and use-after-free bugs, and the option enables -fsanitize-address-use-after-scope. More at https://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html.

Run-time behavior is influenced through the HWASAN_OPTIONS environment variable โ€” set it to help=1 and the available options show up at startup of the instrumented program.

โš ๏ธ Can't be combined with -fsanitize=thread or -fsanitize=address, and it's currently only available on AArch64.

  • -fsanitize=kernel-hwaddress โ€” Hardware-assisted AddressSanitizer, but for compiling the Linux kernel. ๐Ÿฆ‹ It's similar to -fsanitize=kernel-address but uses an alternate instrumentation method, and similar to -fsanitize=hwaddress but with instrumentation differences that are 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 from -fsanitize=hwaddress. Instrumenting the stack and alloca calls are not on by default, but you can still get them by specifying the command-line options --param hwasan-instrument-stack=1 and --param hwasan-instrument-allocas=1 respectively. Using a random frame tag is not implemented for kernel instrumentation. ๐Ÿ’€
  • -fsanitize=pointer-compare โ€” instruments comparison operations (<, <=, >, >=) that have pointer operands. This one must be combined with either -fsanitize=kernel-address or -fsanitize=address, and it cannot be combined with -fsanitize=thread.
Note: by default the check is disabled at run time. To enable it, add detect_invalid_pointer_pairs=2 to the ASAN_OPTIONS environment variable. Using detect_invalid_pointer_pairs=1 detects the invalid operation only when both pointers are non-null. ๐ŸŽ€
  • -fsanitize=pointer-subtract โ€” instruments subtraction with pointer operands. Same deal: must be combined with either -fsanitize=kernel-address or -fsanitize=address, and 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 ASAN_OPTIONS environment variable. Using detect_invalid_pointer_pairs=1 detects the invalid operation only when both pointers are non-null. ๐Ÿ’…
  • -fsanitize=shadow-call-stack โ€” enables ShadowCallStack, a security enhancement mechanism that protects programs against return address overwrites (e.g. stack buffer overflows ๐Ÿ’€). The way it works: it saves a function's return address to a separately allocated shadow call stack in the function prologue, then restores the return address from the shadow call stack in the function epilogue. Instrumentation only happens in functions that actually need to save the return address to the stack. ๐ŸŒˆ

Currently it only supports the aarch64 platform, and it's specifically designed for linux kernels that enable the CONFIG_SHADOW_CALL_STACK option. For user space programs, runtime support is not currently provided in libc and libgcc โ€” if you want to use this in user space, you have to bring your own runtime support. ๐Ÿซถ And fyi, this may cause the ABI rules to be broken.

On aarch64, the instrumentation makes use of the platform register x18. This generally means any code that may run on the same thread as code compiled with ShadowCallStack must be compiled with the flag -ffixed-x18 โ€” otherwise functions compiled without -ffixed-x18 might clobber x18 and thereby corrupt the shadow stack pointer. ๐Ÿ˜ญ

Also, because there is no userspace runtime support, code compiled with ShadowCallStack cannot use exception handling. Use -fno-exceptions to turn off exceptions.

More details at https://clang.llvm.org/docs/ShadowCallStack.html.

Run-time behavior can be influenced using the TSAN_OPTIONS environment variable โ€” supported options are listed at https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags.

โš ๏ธ Cannot be combined with -fsanitize=address or -fsanitize=leak.

Note: sanitized atomic builtins cannot throw exceptions when operating on invalid memory addresses with non-call exceptions (-fnon-call-exceptions).

Run-time behavior can be influenced using the LSAN_OPTIONS environment variable. โš ๏ธ Cannot be combined with -fsanitize=thread.

  • -fsanitize=undefined โ€” enables UndefinedBehaviorSanitizer, a fast undefined behavior detector. ๐Ÿงš Various computations get instrumented so undefined behavior is detected at runtime. More at https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html. Run-time behavior can be influenced using the UBSAN_OPTIONS environment variable.

Current suboptions are, in order:

๐Ÿ’œ -fsanitize=shift

This option enables checking that the result of a shift operation is not undefined. Note that what exactly counts as undefined differs slightly between C and C++, and also 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 the 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

Detect integer division by zero. ๐Ÿšซ

๐Ÿ’œ -fsanitize=unreachable

With this option, the compiler turns the __builtin_unreachable call into a diagnostics message call instead. Heads up: 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

This option enables pointer checking. Particularly, an application built with this option turned on will issue an error message when it tries to dereference a NULL pointer, or if a reference (possibly an rvalue reference) is bound to a NULL pointer, or if a method is invoked on an object pointed to by a NULL pointer. ๐ŸŽฏ


  • -fsanitize=return โ€” bestie, this one's checking your return statements, fr. Programs built with this on will throw an error message the second you hit the end of a non-void function without actually returning a value. ๐Ÿ’€ Heads up: this works in C++ only.
  • -fsanitize=signed-integer-overflow โ€” signed integer overflow checking, let's gooo. We verify that the result of +, *, and both unary and binary - does not overflow in signed arithmetics. It also catches INT_MIN / -1 signed division (sneaky one ๐Ÿ‘€). Ngl, the integer promotion rules gotta be taken into account here. Which means the following is not an overflow:
signed char a = SCHAR_MAX;
a++;
  • -fsanitize=bounds โ€” this one instruments array bounds. Various out-of-bounds accesses get detected โœจ. Flexible array members, flexible array member-like arrays, and initializers of variables with static storage are not instrumented โ€” with the exception of flexible array member-like arrays for which -fstrict-flex-arrays or -fstrict-flex-arrays= options or strict_flex_array attributes say they shouldn't be treated like flexible array member-like arrays. iykyk.
  • -fsanitize=bounds-strict โ€” the โœจstrictโœจ sibling of array bounds instrumentation. Most out-of-bounds accesses get detected, including flexible array member-like arrays this time. Initializers of variables with static storage are still not instrumented.
  • -fsanitize=alignment โ€” checks the alignment of pointers when they're dereferenced ๐Ÿซถ, or when a reference is bound to an insufficiently aligned target, or when a method or constructor is invoked on an insufficiently aligned object.
  • -fsanitize=object-size โ€” instrumentation of memory references using the __builtin_dynamic_object_size function. Various out-of-bounds pointer accesses get detected, periodt.
  • -fsanitize=float-divide-by-zero โ€” detects floating-point division by zero. But lowkey important: 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. So it's a vibe, not always a bug ๐Ÿ’….
  • -fsanitize=float-cast-overflow โ€” floating-point type to integer conversion checking. We check that the result of the conversion does not overflow. Same tea as above: 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 such functions. Not the move ๐Ÿ˜ญ.
  • -fsanitize=bool โ€” instruments loads from bool. If a value other than 0/1 is loaded, a run-time error is issued. Simple as that ๐ŸŽ€.
  • -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. Main character energy tbh ๐Ÿ‘‘.
  • -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.
Ngl besties, note that sanitizers tend to increase the rate of false positive warnings โ€” most notably those around -Wmaybe-uninitialized. We recommend against combining -Werror and [the use of] sanitizers. ๐Ÿšซ

Also 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 disables all previously enabled sanitizers. And no, -fsanitize=all is not allowed, because some sanitizers cannot be used together. It's giving "not a group project" ๐Ÿ’€.
  • -fasan-shadow-offset=number โ€” forces GCC to use a custom shadow offset in AddressSanitizer checks. Super useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer ๐Ÿงš.
  • -fsanitize-sections=s1,s2,... โ€” sanitize global variables in selected user-defined sections. Each si may contain wildcards. Slay.
  • -fsanitize-recover[=opts] โ€” -fsanitize-recover= controls error recovery mode for 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 the program then 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 is also accepted โ€” the former enables recovery for all sanitizers that support it, the latter disables recovery for all sanitizers that support it.

Even if a recovery mode is turned on the compiler side, it needs to be also 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 โ€” enable sanitization of local variables to detect use-after-scope bugs. The option sets -fstack-reuse to none. Catch those sneaky ones ๐Ÿ”ฅ.
  • -fsanitize-trap[=opts] โ€” the -fsanitize-trap= option instructs the compiler to report for sanitizers mentioned in the comma-separated list of opts undefined behavior using __builtin_trap rather than a libubsan library routine. If this option is enabled for a certain sanitizer, it takes precedence over the -fsanitizer-recover= for that sanitizer โ€” __builtin_trap will be emitted and be fatal regardless of whether recovery is enabled or disabled using -fsanitize-recover=.

The advantage of this is that the libubsan library is not needed and is not linked in, so this is usable even in freestanding environments โœจ.

Currently this feature works with -fsanitize=undefined (and its suboptions except for -fsanitize=vptr), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero and -fsanitize=bounds-strict. -fsanitize-trap=all can be also specified, which enables it for undefined suboptions, -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero and -fsanitize=bounds-strict. If -fsanitize-trap=undefined or -fsanitize-trap=all is used and -fsanitize=vptr is enabled on the command line, the instrumentation is silently ignored, as the instrumentation always needs libubsan support โ€” -fsanitize-trap=vptr is not allowed ๐Ÿšซ.

  • -fsanitize-undefined-trap-on-error โ€” deprecated equivalent of -fsanitize-trap=all. Old news bestie, wrap it up ๐ŸŽ€.
  • -fsanitize-coverage=trace-pc โ€” enable coverage-guided fuzzing code instrumentation. Inserts a call to __sanitizer_cov_trace_pc into every basic block.
  • -fsanitize-coverage=trace-cmp โ€” enable 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. So many of them, I know ๐Ÿ˜ญ โ€” they each got a job.
  • -fcf-protection=[full|branch|return|none|check] โ€” enable 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.

Bestie, and then there's "check" ๐Ÿ’… โ€” that value is for the final link when you're doing link-time optimization (LTO). If your LTO object files got compiled with different -fcf-protection values, boom, error ๐Ÿ’€. And at compile time? "check" is just straight-up ignored, no cap.

The macro __CET__ appears the second you use -fcf-protection. First bit of __CET__ gets set to 1 for the value "branch", and the second bit of __CET__ gets set to 1 for "return". So cute ๐ŸŽ€

You can also use the "nocf_check" attribute to point at which functions and calls should get skipped from instrumentation. not invited, bye ๐Ÿ˜Œ

Currently the x86 GNU/Linux target provides an implementation based on Intel Control-flow Enforcement Technology (CET) that works for i686 processors or newer. periodt โœจ

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. ๐Ÿ‘‘

  • -fharden-compares โ€” for every logical test that survives gimple optimizations and isn't the condition in a conditional branch (think: conditions tested for conditional moves, or ones being stored in boolean variables), it emits extra code to compute and verify the reversed condition, and to call __builtin_trap if the results don't match ๐Ÿ˜ค. Team it up with -fharden-conditional-branches to cover all conditionals.
  • -fharden-conditional-branches โ€” same energy ๐Ÿ’… but for every non-vectorized conditional branch that survives gimple optimizations: extra code gets emitted to compute and verify the reversed condition, and to call __builtin_trap if the result is unexpected. Use it with -fharden-compares to cover all conditionals.
  • -fstack-protector โ€” emits extra code that checks for buffer overflows, like stack smashing attacks ๐Ÿ›ก๏ธ. How though? It adds a guard variable to functions with vulnerable objects โ€” and that means functions that call alloca, plus 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. Guard check fails? An error message gets printed and the program exits, goodbye ๐Ÿ’€. Also important: only variables that are actually allocated on the stack are considered โ€” optimized-away variables or variables allocated in registers do not count, sorry ๐Ÿซถ
  • -fstack-protector-all โ€” literally -fstack-protector except that ALL functions are protected. every single one ๐Ÿ‘‘
  • -fstack-protector-strong โ€” like -fstack-protector but it also includes additional functions to be protected: the ones that have local array definitions, or that have references to local frame addresses ๐Ÿฆ‹. And same rule as its siblings โ€” only variables actually allocated on the stack are considered; optimized-away variables or variables allocated in registers don't count.
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. โœจ
  • -fstack-protector-explicit โ€” like -fstack-protector but it only protects those functions which have the stack_protect attribute. so picky, so iconic ๐ŸŽ€
  • -fstack-check โ€” generates code to verify that you don't go beyond the boundary of the stack. You should defo specify this flag if you're running in an environment with multiple threads ๐Ÿงต, but you only rarely need to specify it in a single-threaded environment, since stack overflow is automatically detected on nearly all systems if there's only one stack.

Okay real talk though โ€” this switch does not actually cause checking to be done. The operating system or the language runtime has to do that part, fr fr. What the switch does is generate code so that they see the stack being extended. ๐Ÿ™ˆ

You can additionally specify a string parameter: no means no checking, generic means force the use of old-style checking, and specific means use the best checking method โ€” which is equivalent to bare -fstack-check.

Old-style checking is a generic mechanism that requires no specific target support in the compiler, but bestie, it comes with the following drawbacks:

  1. Modified allocation strategy for large objects: they're always allocated dynamically if their size exceeds a fixed threshold. Heads up that 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. sad but true ๐Ÿ’”

Note that old-style stack checking is also the fallback method for specific if no target support has been added in the compiler.

-fstack-check= is designed for Ada's needs to detect infinite recursion and stack overflows. specific is an excellent choice when compiling Ada code. But it is not generally sufficient to protect against stack-clash attacks. Wanna 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 gets accessed immediately after allocation. So yeah, it stops allocations from jumping over any stack guard page provided by the operating system. elite behaviour ๐Ÿ‘‘

Most targets do not fully support stack clash protection. However, on those targets -fstack-clash-protection will still protect dynamic stack allocations. And it 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 โ€” generates code to make sure the stack doesn't grow beyond a certain value, either the value of a register or the address of a symbol. Need a bigger stack than that? A signal is raised at run time โš ๏ธ. For most targets, the signal is raised before the stack overruns the boundary, so it's possible to catch the signal without taking special precautions, which is lowkey a relief.

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 that automatically splits the stack before it overflows. The resulting program has a discontiguous stack which can only overflow if the program is unable to allocate any more memory ๐Ÿ˜ณ. This is most useful when running threaded programs, since it's no longer necessary to calculate a good stack size to use for each thread. Right now it's 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. And if compiling all code โ€” including library code โ€” with -fsplit-stack isn't an option, then the linker can fix up these calls so that the code compiled without -fsplit-stack always has a large stack. Support for this is implemented in the gold linker in GNU binutils release 2.21 and later. ๐Ÿ’…

  • -fvtable-verify=[std|preinit|none] โ€” only available when you're compiling C++ code, iykyk. It turns on (or off, if you're using -fvtable-verify=none) the security feature that verifies at run time, for every virtual call, that the vtable pointer through which the call is made is valid for the type of the object, and that it hasn't been corrupted or overwritten ๐Ÿ‘‘. If an invalid vtable pointer is detected at run time, an error is reported and execution of the program is immediately halted. ๐Ÿ’€

This option causes run-time data structures to be built at program startup, and those get used for verifying the vtable pointers. The options std and preinit control the timing of when those data structures get built. In both cases the data structures are built before execution reaches main. Using -fvtable-verify=std causes the data structures to be built after shared libraries have been loaded and initialized. -fvtable-verify=preinit causes them to be built before shared libraries have been loaded and initialized. ๐ŸŽ€

If this option shows up multiple times on the command line with different values specified: none takes highest priority over both std and preinit; preinit takes priority over std. rules are rules โœจ

  • -fvtv-debug โ€” when used together 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 makes the compiler log information about which vtable pointers it finds for each class. That info gets written to a file named vtv_set_ptr_data.log in the directory named by the environment variable VTV_LOGS_DIR if that's defined, or the current working directory otherwise.

Note: this feature appends data to the log file. If you want a fresh log file, be sure to delete any existing one first, bestie ๐Ÿ—‘๏ธ

  • -fvtv-counts โ€” this one's a debugging flag ๐Ÿ›. When used in conjunction with -fvtable-verify=std or -fvtable-verify=preinit, it makes the compiler 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 info to a file named vtv_count_data.log in the directory named by the environment variable VTV_LOGS_DIR if that's defined, or the current working directory otherwise. It also counts the size of the vtable pointer sets for each class and writes that info 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 โœจ โ€” bestie, this one sprinkles instrumentation calls for entry and exit to functions. Like, right after a function gets entered and right before it exits, these profiling functions get called with the address of the current function and its call site. (Heads up though ๐Ÿ’€: on some platforms __builtin_return_address does not work beyond the current function, so the call site info might just... 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);

That first argument? It's the address of the start of the current function, which you can look up exactly in the symbol table. ๐Ÿ‘‘

This instrumentation also happens for functions expanded inline in other functions. The profiling calls show, conceptually, where the inline function is entered and exited. Which means โ€” plot twist โ€” addressable versions of such functions must be available. If all your uses of a function are expanded inline, this may mean an extra code-size expansion, no cap. And 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 can also be given the attribute no_instrument_function, and then this instrumentation just doesn't happen. Very much used for, say, the profiling functions listed above, high-priority interrupt routines, and any functions from which the profiling functions cannot safely be called (maybe signal handlers, if the profiling routines generate output or allocate memory). safety first bb ๐Ÿซถ

  • -finstrument-functions-once โ€” similar to -finstrument-functions, but the profiling functions get called only once per instrumented function. i.e. the first profiling function fires after the first entry into the instrumented function, and the second profiling function fires before the exit corresponding to this first entry. ๐Ÿฆ‹

The definition of "once" here is a lil vague, ngl ๐Ÿ˜ญ, because the implementation is not protected against data races. So the implementation only guarantees that the profiling functions are called at least once per process and at most once per thread โ€” but the calls are always paired. Which is to say: if a thread calls the first function, then it will call the second function, unless it never reaches the exit of the instrumented function. ๐Ÿ’…

  • -finstrument-functions-exclude-file-list=file,file,... โ€” sets the list of functions that are excluded from instrumentation (see the description of -finstrument-functions above, bestie ๐Ÿ‘€). If the file that contains a function definition matches with one of file, then that function is not instrumented. The match is done on substrings: if the file parameter is a substring of the file name, it counts as a match. ๐Ÿ”

For example:

-finstrument-functions-exclude-file-list=/bits/stl,include/sys

...excludes any inline function defined in files whose pathnames contain /bits/stl or include/sys.

If, for some reason, you want to include letter , in one of sym, write ,. For example, -finstrument-functions-exclude-file-list=',,tmp' (note the single quote surrounding the option ๐ŸŽ€).

  • -finstrument-functions-exclude-function-list=sym,sym,... โ€” 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 being matched is its user-visible name, like vector<int> blah(const vector<int> &), not the internal mangled name (e.g., _Z4blahRSt6vectorIiSaIiEE). Match is on substrings: if the sym parameter is a substring of the function name, it's a match. And for C99 and C++ extended identifiers, the function name must be given in UTF-8, not using universal character names. ๐ŸŒธ
  • -fpatchable-function-entry=N[,M] โ€” generates N NOPs right at the beginning of each function, with the function entry point before the Mth NOP. If M is omitted, it defaults to 0, so the function entry points to the address just at the first NOP. These NOP instructions reserve extra space โ€” which you can use to patch in any instrumentation you want 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 the command-line option -fpatchable-function-entry=N,M. You can use this to increase the area size or to remove it completely on a single function. And 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. On PowerPC with the ELFv2 ABI, for a function with dual entry points, the local entry point is this function entry address. ๐Ÿ’…

The maximum value of N and M is 65535. On PowerPC with the ELFv2 ABI, for a function with dual entry points, the supported values for M are 0, 2, 6 and 14.


โœจ Options Controlling the Preprocessor โœจ

These options control the C preprocessor, which โ€” bestie, listen โ€” is run on each C source file before actual compilation. ๐Ÿฆ‹

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

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. ๐Ÿ’…
  • -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's searched for in the remainder of the #include "..." search chain as normal. ๐Ÿ”

If multiple -include options are given, the files are included in the order they appear on the command line.

  • -imacros file โ€” exactly like -include, except that any output produced by scanning file is thrown away. ๐Ÿ—‘๏ธ Macros it defines remain defined. This lets you acquire all the macros from a header without also processing its declarations. Iconic, honestly.

All files specified by -imacros are processed before all files specified by -include.

  • -undef โ€” do not predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined. โœจ
  • -pthread โ€” 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. ๐Ÿ“

okay so this bit is the continuation of the -MF saga, no re-intro needed, we're just sliding right in ๐Ÿ’…

When you use it alongside the driver options -MD or -MMD, -MF overrides whatever the default dependency output file would've been.

If file is -, then the dependencies get written to stdout. yes, straight to your terminal, iconic behaviour honestly.


  • -MG โ€” When you're using this together with an option like -M that's asking for dependency generation, -MG justโ€ฆ assumes any missing header files are generated files, and adds them to the dependency list without throwing an error at you. The dependency filename is taken directly from the #include directive, no path prepended, none of that. -MG also suppresses preprocessed output, because bestie, a missing header file makes that output useless anyway.

This feature gets used for automatic updating of makefiles. slay.

  • -Mno-modules โ€” Disable dependency generation for compiled module interfaces. that's it, that's the whole vibe.
  • -MP โ€” This one tells CPP to add a phony target for each dependency other than the main file, so each one depends on nothing. These dummy rules work around the errors make throws at you when you delete header files without updating the Makefile to match. classic.

This is the typical output you get:

test.o: test.c test.h

test.h:
  • -MT target โ€” Changes 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 like .c, and appends the platform's usual object suffix. boom, that's your target.

An -MT option sets the target to be exactly the string you specify. Want multiple targets? You can pass them as a single argument to -MT, or just use multiple -MT options. your call, queen.

For example, -MT '$(objpfx)foo.o' might give you

$(objpfx)foo.o: foo.c
  • -MQ target โ€” Same as -MT, except it quotes any characters that are special to Make. So -MQ '$(objpfx)foo.o' gives
$$(objpfx)foo.o: foo.c

The default target gets automatically quoted, as if you'd given it with -MQ. the compiler did it for you, no notes.

  • -MD โ€” -MD is equivalent to -M -MF file, except that -E is not implied. The driver figures out file based on whether an -o option was given. If it was, the driver uses its argument but with a suffix of .d. Otherwise it takes the name of the input file, strips any directory components and suffix, and slaps a .d suffix on there.

If -MD is used with -E, any -o switch is understood to specify the dependency output file โ€” but if it's used without -E, each -o is understood to specify a target object file. subtle but important, iykyk.

Since -E is not implied, -MD can be used to generate a dependency output file as a side effect of the compilation process. multitasking queen.

  • -MMD โ€” Like -MD except it only mentions user header files, not system header files. we're keeping it selective ๐Ÿ’…
  • -fpreprocessed โ€” Indicate to the preprocessor that the input file has already been preprocessed. This suppresses things like macro expansion, trigraph conversion, escaped newline splicing, and processing of most directives. The preprocessor still recognizes and removes comments, so you can pass a file preprocessed with -C to the compiler without problems. In this mode the integrated preprocessor is little more than a tokenizer for the front ends. glorified tokenizer era.

-fpreprocessed is implicit if the input file has one of the extensions .i, .ii or .mi. These are the extensions that GCC uses for preprocessed files created by -save-temps.

  • -fdirectives-only โ€” When preprocessing, handle directives, but do not expand macros.

The behaviour of this option depends on the -E and -fpreprocessed options. it's giving conditional energy.

With -E, preprocessing is limited to the handling of directives such as #define, #ifdef, and #error. Other preprocessor operations, like macro expansion and trigraph conversion, are not performed. On top of that, the -dD option is implicitly enabled.

With -fpreprocessed, predefinition of command line and most builtin macros is disabled. Macros such as __LINE__, which are contextually dependent, are handled normally. This enables compilation of files previously preprocessed with -E -fdirectives-only.

With both -E and -fpreprocessed, the rules for -fpreprocessed take precedence. This enables full preprocessing of files previously preprocessed with -E -fdirectives-only.

  • -fdollars-in-identifiers โ€” Accept $ in identifiers. just letting the dollar sign in, we love inclusivity โœจ
  • -fextended-identifiers โ€” Accept universal character names and extended characters in identifiers. This option is enabled by default for C99 (and later C standard versions) and C++. default behaviour, no extra work needed.
  • -fno-canonical-system-headers โ€” When preprocessing, do not shorten system header paths with canonicalization. leave those paths long, bestie.
  • -fmax-include-depth=depth โ€” Set the maximum depth of the nested #include. The default is 200.
  • -ftabstop=width โ€” Set the distance between tab stops. This helps the preprocessor report correct column numbers in warnings or errors, even if tabs appear on the line. If the value is less than 1 or greater than 100, the option is ignored. The default is 8.
  • -ftrack-macro-expansion[=level] โ€” Track locations of tokens across macro expansions. This lets the compiler emit diagnostics about the current macro expansion stack when a compilation error happens inside a macro expansion. Heads up though: using this option makes the preprocessor and the compiler consume more memory. The level parameter can be used to choose the level of precision of token location tracking, so you can dial down the memory consumption 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, and this value is the most memory hungry. When this option is given no argument, the default parameter value is 2.

Note that -ftrack-macro-expansion=2 is activated by default.

  • -fmacro-prefix-map=old=new โ€” When preprocessing files residing in directory old, expand the __FILE__ and __BASE_FILE__ macros as if the files resided in directory new instead. This can be used to change an absolute path to a relative path by using . for new, which can result in more reproducible builds that are location independent. This option also affects __builtin_FILE() during compilation. See also -ffile-prefix-map and -fcanon-prefix-map.
  • -fexec-charset=charset โ€” Set the execution character set, used for string and character constants. The default is UTF-8. charset can be any encoding supported by the system's iconv library routine. so many options, so little time.
  • -fwide-exec-charset=charset โ€” Set 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. consider yourself warned ๐Ÿ˜ญ
  • -finput-charset=charset โ€” Set the input character set, used for translation from the character set of the input file to the source character set used by GCC. If the locale does not specify, or GCC cannot get this information from the locale, the default is UTF-8. This can be overridden by either the locale or this command-line option. Currently the command-line option takes precedence if there's a conflict. charset can be any encoding supported by the system's iconv library routine.
  • -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 it's not specified, only the precompiled header gets listed and not the files that were used to create it, because those files are not consulted when a precompiled header is used. mystery files, we don't talk about them ๐Ÿซถ
  • -fpch-preprocess โ€” This option allows use of a precompiled header together with -E. It inserts a special #pragma, specifically #pragma GCC pch_preprocess "filename", in the output to mark the place where the precompiled header was found, plus its filename. When -fpreprocessed is in use, GCC recognizes this #pragma and loads the PCH.

This option is off by default, because the resulting preprocessed output is only really suitable as input to GCC. It is switched on by -save-temps.

You should not write this #pragma in your own code, but it is safe to edit the filename if the PCH file is available in a different location. The filename may be absolute or it may be relative to GCC's current directory. don't do the first thing, the second thing is fine, ok?

  • -fworking-directory โ€” Enable generation of linemarkers in the preprocessor output that let the compiler know the current working directory at the time of preprocessing. When this option is enabled, the preprocessor emits, after the initial linemarker, a second linemarker with the current working directory followed by two slashes. GCC uses this directory, when it's present in the preprocessed input, as the directory emitted as the current working directory in some debugging information formats. This option is implicitly enabled if debugging information is enabled, but this can be inhibited with the negated form -fno-working-directory. If the -P flag is present in the command line, this option has no effect, since no #line directives are emitted whatsoever. conflicting flags era ๐Ÿ’€
  • -A predicate=answer โ€” Make an assertion with the predicate predicate and answer answer. This form is preferred to the older form -A predicate(answer), which is still supported, because it does not use shell special characters. newer form ate, periodt.
  • -A -predicate=answer โ€” Cancel an assertion with the predicate predicate and answer answer. undoing the thing, we love a reversible queen.
  • -C โ€” Do not discard comments. All comments are passed through to the output file, except for comments in processed directives, which get 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 #. yeah. that's a whole thing. be ready for it.

  • -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. the extra-C really said "and I'll go further" ๐Ÿ”ฅ

okay that's the end of this chunk bestie, more incoming, don't go anywhere ๐ŸŒธ

So basically -CC rolls up to -C and does everything it does, PLUS it takes every C++-style comment (you know, the // ones) that's chillin' inside a macro and turns it into a C-style comment instead. Why tho? Because otherwise later on, when that macro gets used, it would accidentally comment out the whole rest of the source line and everything would fall apart ๐Ÿ’€. It's a whole trap, bestie.

So like, -CC is mainly there to support lint comments. That's its whole job. Periodt.

  • -P โ€” ok so this one stops linemarkers from showing up in the preprocessor output. When's that useful? When you're running the preprocessor on something that is NOT C code, and it's getting piped to a program that would be all confused by linemarkers. So you just... kill them. Simple ๐Ÿ’…
  • -traditional, -traditional-cpp โ€” these try to imitate how pre-standard C preprocessors behaved, instead of the ISO C preprocessors we have now. The GNU CPP manual has all the tea if you want details.
Heads up tho fr: GCC does NOT otherwise try to emulate a pre-standard C compiler, and these options only work with the -E switch, or when you're invoking CPP directly. Nowhere else. So don't come for me.
  • -trigraphs โ€” turn on ISO C trigraphs. A trigraph is a three-character sequence, all starting with ??, that ISO C says stands for one single character. Example: ??/ means \, so '??/n' is a character constant for a newline. Cute right? ๐Ÿฆ‹

The nine trigraphs and what they turn into:

Trigraph:       ??(  ??)  ??<  ??>  ??=  ??/  ??'  ??!  ??-
Replacement:      [    ]    {    }    #    \    ^    |    ~

By default GCC ignores trigraphs (it's giving "I don't see them"), but in standard-conforming modes it converts them. Peep the -std and -ansi options for that.

  • -remap โ€” turns on special code to work around file systems that only allow super short file names, like MS-DOS. Throwback energy fr ๐Ÿ™ˆ
  • -H โ€” prints the name of every header file used, on top of the normal stuff it's already doing. Each name gets indented so you can see how deep in the #include stack it is (nesting visualisation, iconic). Precompiled header files get printed too, even if they turn out to be invalid! And the way it tells you: an invalid precompiled header file is printed with ...x and a valid one with ...! . Noted ๐Ÿ“
  • -dletters โ€” tells GCC to make debugging dumps during compilation, specified by letters. The flags documented right here are the ones relevant to the preprocessor. Other letters get interpreted by the compiler proper, or they're being saved for future versions of GCC, so they're just silently ignored (they said "not my problem"). And if you specify letters whose behaviours conflict? The result is undefined. That's the danger zone, bestie ๐Ÿšจ
    • -dM โ€” instead of the normal output, it generates a list of #define directives for ALL the macros defined during the preprocessor's run, including predefined ones. This is literally how you find out what's predefined in your version of the preprocessor. Say you have no file foo.h, then this command:
touch foo.h; cpp -dM foo.h

...shows you all the predefined macros. Chef's kiss.

But wait โ€” if you use -dM WITHOUT the -E option, then -dM gets interpreted as a synonym for -fdump-rtl-mach. Yeah. Sneaky.

  • -dD โ€” like -dM except in two ways: 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, but it emits only the macro names, not what they expand to. Names only, no spoilers ๐Ÿ’…
  • -dI โ€” outputs #include directives in addition to the result of preprocessing.
  • -dU โ€” like -dD except only macros that get expanded, or whose definedness is tested in preprocessor directives, are output. The output is delayed until the use or test of the macro happens, and #undef directives are also output for macros that got tested but were undefined at the time.
  • -fdebug-cpp โ€” this one is ONLY useful for debugging GCC itself. When you use it from CPP or with -E, it dumps debugging info about location maps. Every token in the output gets preceded by the dump of the map its location belongs to.

When it's used from GCC without -E, it does absolutely nothing. Nada. Zero effect. ๐Ÿ˜ญ

  • -Wp,option โ€” you can use -Wp,option to bypass the compiler driver entirely and pass option straight through to the preprocessor. If option has commas in it, it gets split into multiple options at the commas. BUT โ€” and this is a big but โ€” lots of options get modified, translated, or interpreted by the compiler driver before they ever reach the preprocessor, and -Wp forcibly skips that whole phase. The preprocessor's direct interface is undocumented and subject to change, so whenever possible you should avoid -Wp and just let the driver handle the options instead. It's giving "risky shortcut" ngl.
  • -Xpreprocessor option โ€” passes option as an option to the preprocessor. Use this to supply system-specific preprocessor options that GCC doesn't recognise. And if you want to pass an option that takes an argument, you have to use -Xpreprocessor TWICE โ€” once for the option and once for the argument. Two times. Not one. โœจ
  • -no-integrated-cpp โ€” performs preprocessing as a separate pass before compilation. By default GCC does preprocessing as an integrated part of input tokenization and parsing. But if you provide this option, the appropriate language front end โ€” cc1, cc1plus, or cc1obj for C, C++, and Objective-C respectively โ€” gets invoked twice instead: once for preprocessing only, and once for the actual compilation of the preprocessed input. This may be useful alongside the -B or -wrapper options, to specify an alternate preprocessor or do extra processing of the program source between normal preprocessing and compilation. Fancy ๐ŸŽ€
  • -flarge-source-files โ€” adjusts GCC to expect large source files, at the cost of slower compilation and higher memory usage. Trade-offs, always trade-offs.

Here's the detail: GCC normally tracks both column numbers and line numbers inside source files, and normally prints both of them in diagnostics. But once it's processed a certain number of source lines, it STOPS tracking column numbers and only tracks line numbers. Which means diagnostics for later lines won't include column numbers. It also means options like -Wmisleading-indentation just stop working at that point โ€” although the compiler does print a note if this happens, so at least it tells you. Passing -flarge-source-files significantly increases the number of source lines GCC can process before it stops tracking columns. Big files, big brain ๐Ÿง 

โœจ Passing Options to the Assembler โœจ

So you can also pass options to the assembler. Yes, really.

  • -Wa,option โ€” passes option as an option to the assembler. If option contains commas, it gets split into multiple options at the commas. Same comma logic, different destination.
  • -Xassembler option โ€” passes option as an option to the assembler. Use this to supply system-specific assembler options that GCC doesn't recognise. And again, if you want to pass an option that takes an argument, you must use -Xassembler twice โ€” once for the option, once for the argument. Twice. Always twice. ๐Ÿซถ

๐Ÿ’– Options for Linking ๐Ÿ’–

These options come into play when the compiler links object files into an executable output file. And heads up โ€” they are meaningless if the compiler isn't doing a link step. Like, they just sit there. So know when they matter, bestie.

  • object-file-name โ€” a file name that doesn't end in a special recognised suffix is considered to name an object file or a library. (The linker tells object files apart from libraries by looking at the file contents, iykyk.) If linking is happening, these object files are used as input to the linker.
  • -c, -S, -E โ€” if ANY of these options is used, then the linker does NOT run, and object file names should not be used as arguments. Simple as that.
  • -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. But for debugging the compiler, or if you want incremental linking with a non-LTO object file, it might 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 lets you build shared libraries without position-independent code on architectures where that's 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 it's specified at compilation time.

If type is rel, the compiler assumes incremental linking is being done. The sections containing intermediate code for link-time optimization get merged, pre-optimized, and output to the resulting object file. Plus, 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. And at link time, the result of incremental linking also loads faster than a static library โ€” assuming the majority of objects in the library are actually used. Slay โœจ

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 get linked together, the resulting code is better optimized than with link-time optimizations disabled (cross-module inlining happens, for example), but most of the benefits of whole program optimizations are lost. RIP to those benefits ๐Ÿ˜”

During the incremental link (via -r), the linker plugin defaults to rel. With current interfaces to GNU Binutils though, it's 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 can't be used for link-time optimization, the linker plugin issues a warning and uses nolto-rel. To maintain whole program optimization, it's recommended to link such objects into a static library instead. Alternatively, you can use H.J. Lu's binutils, which has support for mixed objects. Options, options ๐Ÿ“š

  • -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. Modern, as the name suggests ๐Ÿ’…
  • -llibrary, -l library โ€” search the library named library when linking. (The second form, with the library as a separate argument, is only there for POSIX compliance and is not recommended.) The -l option is passed directly to the linker by GCC, so go read your linker documentation for the exact details. The general description below applies to the GNU linker.

and that's where this part wraps, but we are SO not done โ€” more coming ๐Ÿซถ

The linker goes sniffing through a standard list of directories looking for the library, and that list is like several standard system directories plus whatever extra ones you told it about with -L.

Static libraries are basically archives of object files, and their names look like liblibrary.a. Some targets are also out here supporting shared libraries, which usually have names like liblibrary.so. If the linker finds both, bestie, it gives preference to the shared one โ€” unless you used -static. That's just how it is. ๐Ÿ’…

And okay, the position where you write this option in the command matters, no cap. The linker searches and processes libraries and object files in the order they're specified. So foo.o -lz bar.o searches library z after foo.o but before bar.o. And if bar.o refers to functions in z... those functions may not be loaded. ๐Ÿซ  Order is the whole plot.

  • -lobjc โ€” this is the special-case edition of -l, and you need it to link an Objective-C or Objective-C++ program. Very specific, very necessary. โœจ
  • -nostartfiles โ€” do not use the standard system startup files when linking. The standard system libraries still get used normally, unless -nostdlib, -nolibc, or -nodefaultlibs is also in the mix.
  • -nodefaultlibs โ€” do not use the standard system libraries when linking. Only the libraries you specify get passed to the linker, and any options that specify linkage of the system libraries โ€” think -static-libgcc or -shared-libgcc โ€” get ignored. The standard startup files are used normally, unless -nostartfiles is used.

Heads up though: the compiler may generate calls to memcmp, memset, memcpy and memmove. Those entries are usually resolved by entries in libc. When you use this option, you've gotta supply those entry points through some other mechanism. ๐Ÿ‘€

  • -nolibc โ€” do not use the C library or the system libraries tightly coupled with it when linking. You'll still link with the startup files, libgcc, or toolchain-provided language support libraries like libgnat, libgfortran or libstdc++ โ€” unless other options preventing their inclusion are used as well. This typically removes -lc from the link command line, plus the system libraries that normally tag along with it and become meaningless once you're assuming there's no C library โ€” for example -lpthread or -lm in some configurations. The whole point is bare-board targets where 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 get passed to the linker, and options specifying linkage of the system libraries, such as -static-libgcc or -shared-libgcc, are ignored.

Same warning as before, bestie: the compiler may generate calls to memcmp, memset, memcpy and memmove. These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified.

Now, one of the standard libraries bypassed by -nostdlib and -nodefaultlibs is libgcc.a โ€” a library of internal subroutines which GCC uses to overcome shortcomings of particular machines, or special needs for some languages. ๐Ÿ‘‘

In most cases, you need libgcc.a even when you want to avoid other standard libraries. In other words, when you specify -nostdlib or -nodefaultlibs you should usually specify -lgcc as well. This ensures that you have no unresolved references to internal GCC library subroutines. (An example of such an internal subroutine is __main, used to ensure C++ constructors are called.) ๐Ÿซถ

  • -nostdlib++ โ€” do not implicitly link with standard C++ libraries. That's it, that's the whole vibe.
  • -e entry<br> *--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. Your call. ๐ŸŒธ
  • -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. Matchy matchy, or chaos. ๐ŸŽ€
  • -no-pie โ€” don't produce a dynamically linked position independent executable. Simple as.
  • -static-pie โ€” produce a static position independent executable on targets that support it. A static position independent executable is similar to a static executable, but can be loaded at any address without a dynamic linker. For predictable results, you must also specify the same set of options used for compilation (-fpie, -fPIE, or model suboptions) when you specify this linker option. ๐Ÿ”ฅ
  • -pthread โ€” link with the POSIX threads library. This option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets. On some targets this option also sets flags for the preprocessor, so it should be used consistently for both compilation and linking. Don't do half the vibe, do the whole vibe. ๐Ÿ’œ
  • -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. You need this for some uses of dlopen, or to allow obtaining backtraces from within a program. Very main character of it. โœจ
  • -s โ€” remove all symbol table and relocation information from the executable. Poof. Gone. ๐Ÿ’€
  • -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. Literally nothing. ๐Ÿ™ˆ
  • -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<br> *-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. Slay. ๐Ÿ’…

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. No shortcuts on that one. ๐Ÿซถ

  • -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. Just libasan, being special. โญ
  • -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. Commitment issues? Solved. ๐ŸŽ€
  • -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. Fancy, niche, iconic. ๐Ÿ’œ
  • -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. Required, bestie. Not optional. ๐Ÿ˜ญ
  • -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. Sneaking stuff past GCC's vibe check. ๐ŸŒˆ

If you wanna pass an option that takes its own separate argument, bestie, you have to use -Xlinker twice โ€” once for the option itself and once for the argument. Like fr, to pass -assert definitions you write -Xlinker -assert -Xlinker definitions. And it does NOT work to write -Xlinker "-assert definitions" because that shoves the whole string through as one single argument and the linker is just sitting there like ??? that's not what I asked for ๐Ÿ™ˆ

When you're using the GNU linker it's usually way comfier to pass arguments to linker options using the option=value syntax instead of as separate arguments. For example you can specify -Xlinker -Map=output.map rather than -Xlinker -Map -Xlinker output.map. Other linkers might not support this syntax for command-line options though, so iykyk ๐Ÿ’…


  • -Wl,option โ€” passes option as an option to the linker. If option contains commas, it gets split into multiple options at the commas. You can use this syntax to hand an argument to the option. For example, -Wl,-Map,output.map passes -Map output.map to the linker. When you're using the GNU linker, you can also get the exact 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, so it forces linking of library modules to define it. You can use -u multiple times with different symbols to force loading of additional library modules. no cap ๐Ÿซถ
  • -z keyword โ€” -z gets passed directly on to the linker along with the keyword keyword. Go check the section in your linker's documentation for the permitted values and what they actually mean ๐Ÿ‘‘

These options tell GCC which directories to go rummaging through for header files, for libraries, and for parts of the compiler itself. the way she searches, obsessed ๐ŸŒธ

  • *-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 gets swapped out for 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. periodt ๐Ÿ’…

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:

  1. For the quote form of the include directive, the directory of the current file is searched first.
  2. For the quote form of the include directive, the directories specified by -iquote options are searched in left-to-right order, as they appear on the command line.
  3. Directories specified with -I options are scanned in left-to-right order.
  4. Directories specified with -isystem options are scanned in left-to-right order.
  5. Standard system directories are scanned.
  6. Directories specified with -idirafter options are scanned in left-to-right order.

You can use -I to override a system header file, substituting your own version, since these directories get searched before the standard system header file directories. But bestie, please don't use this option to add directories that contain vendor-supplied system header files โ€” use -isystem for that, okay? ๐ŸŽ€

The -isystem and -idirafter options also mark the directory as a system directory, so it gets the same special treatment that's applied to the standard system directories. main character treatment fr ๐ŸŒŸ

If a standard system include directory, or a directory specified 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. This is all to make sure that 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. ๐Ÿ’€

  • -I- โ€” split the include path. This option has been deprecated. Please use -iquote instead for -I directories before the -I- and then just remove the -I- option entirely. she's over, retired, no more ๐Ÿ’…

Any directories specified with -I options before -I- are searched only for headers requested with #include "file"; they are not searched for #include <file>. If additional directories are specified with -I options after the -I-, those directories 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 no way to override this effect of -I-. sorry not sorry ๐Ÿ˜ญ

  • -iprefix prefix โ€” specify prefix as the prefix for subsequent -iwithprefix options. If the prefix represents a directory, you should include the final / in there, don't forget it ๐ŸŽ€
  • *-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. cute little placement rules, we love a system โœจ
  • -isysroot dir โ€” this one is like the --sysroot option, but it applies only to header files (except for Darwin targets, where it applies to both header files and libraries). See the --sysroot option for more info ๐Ÿฆ‹
  • -imultilib dir โ€” 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) get searched.
  • -nostdinc++ โ€” do not search for header files in the C++-specific standard directories, but 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 โ€” it's only passed by the driver. lowkey internal business, mind yours ๐Ÿ™ˆ
  • -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. iconic housekeeping ๐Ÿ’…

The compiler driver program runs one or more of the subprograms cpp, cc1, as and ld. It tries prefix as a prefix for each program it tries to run, both with and without machine/version/ for the corresponding target machine and compiler version.

For each subprogram to be run, the compiler driver first tries the -B prefix, if any. If that name isn't found, or if -B isn't specified, the driver tries two standard prefixes: /usr/lib/gcc/ and /usr/local/lib/gcc/. If neither of those results in a file name that's found, the unmodified program name is searched for using the directories specified in your PATH environment variable. the search order is so thorough, she does not skip steps ๐ŸŒˆ

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's not found there, the two standard prefixes above are tried, and that is all. The file is left out of the link if it's not found by those means. so like, keep that in mind ๐Ÿ‘€

Another way to specify a prefix much like the -B prefix is to use the environment variable GCC_EXEC_PREFIX.

As a special kludge, if the path provided by -B is [dir/]stageN/, where N is a number in the range 0 to 9, then it's replaced by [dir/]include. This is to help with boot-strapping the compiler. a lil niche hack, we stan ๐ŸŽ€

  • -no-canonical-prefixes โ€” don't expand any symbolic links, don't resolve references to /../ or /./, and don't make the path absolute when generating a relative prefix. leave it as is, bestie โœจ
  • --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. everything shifts under the new root, slay ๐Ÿ 

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. splitting duties, very organized ๐Ÿ’…

The GNU linker (beginning with version 2.16) has the necessary support for this option. If your linker doesn't support this option, the header file aspect of --sysroot still works, but the library aspect does not. half a win is still a win ๐Ÿซถ

  • --no-sysroot-suffix โ€” for some targets, a suffix gets 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. bye suffix, not today ๐Ÿ‘‹

๐Ÿ› ๏ธ Options for Code Generation Conventions ๐Ÿ› ๏ธ

These machine-independent options control the interface conventions used in code generation. the ~vibes~ of the generated code, essentially ๐ŸŒธ

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. it's giving mirror energy, you got this ๐Ÿ’–

  • *-fstack-reuse=reuse-level*** โ€” okay so this one is literally the boss of how GCC reuses stack space, both for the local/auto variables *you* declared and for the temporaries the compiler made behind the scenes ๐Ÿ‘€ *reuse-level* can be all, named_vars, or none`. Let me break it down bestie:
    • all โ€” stack reuse is ON for everything: all local variables and all temporaries. โœจ
    • named_vars โ€” reuse only happens for user-defined local variables that actually have names. ๐Ÿ’…
    • none โ€” stack reuse is completely off, periodt. ๐Ÿšซ

The default value is all. You need this option when your program extends the lifetime of a scoped local variable, or of a compiler-generated temporary, past the end point defined by the language โ€” like, going beyond what the language said was allowed ๐Ÿ˜ญ. Here's the tea: when a variable's lifetime ends, and that variable lives in memory, the optimizing compiler is free to reuse its stack space with other temporaries or scoped locals whose live range doesn't overlap with it. So legacy code that extends local lifetime is likely to break with the stack reuse optimization. It's giving "living on borrowed time" fr fr.

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 temporary's lifetime ends, and if that 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 doesn't overlap with it. But some legacy code lowkey relies on the behavior of older compilers where temporaries' stack space is not reused, and the aggressive stack reuse can lead to runtime errors ๐Ÿ’€. So this option is your little control knob for the temporary stack reuse optimization. iykyk.

  • -ftrapv โ€” this option generates traps for signed overflow on addition, subtraction, and multiplication operations ๐Ÿชค. And here's the messy part: -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. Not me having to read that twice ๐Ÿ˜ญ โ€” the order and the negations matter, bestie.
  • -fwrapv โ€” this one tells the compiler to assume that signed arithmetic overflow of addition, subtraction and multiplication wraps around using twos-complement representation ๐Ÿ”„. This flag enables some optimizations and disables others. Same drama as above: -ftrapv and -fwrapv override each other, so -ftrapv -fwrapv on the command line results in -fwrapv being effective. And again, only active options override โ€” so -ftrapv -fwrapv -fno-wrapv on the command line results in -ftrapv being effective. โœจ
  • -fwrapv-pointer โ€” instructs the compiler to assume that pointer arithmetic overflow on addition and subtraction wraps around using twos-complement representation ๐Ÿ‘‘. This flag disables some optimizations which assume pointer overflow is invalid. Yes, pointers get their own little wrap rule. Slay.
  • -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. Short and iconic ๐ŸŽ€.
  • -fexceptions โ€” Enable exception handling ๐Ÿšจ. It generates the extra code needed to propagate exceptions. For some targets, this implies GCC generates frame unwind information for all functions, which can produce significant data size overhead, although it does not affect execution. If you don't specify this option, GCC enables it by default for languages like C++ that normally require exception handling, and disables it for languages like C that don't normally require it. However, you may need to turn it on 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're compiling older C++ programs that don't use exception handling. Basically: know your language's default, don't get caught lacking ๐Ÿ’–.
  • -fnon-call-exceptions โ€” generates code that allows trapping instructions to throw exceptions. Heads up though: this requires platform-specific runtime support that does not exist everywhere ๐ŸŒ๐Ÿšซ. Moreover, it only allows trapping instructions to throw exceptions, i.e. memory references or floating-point instructions. It does not allow exceptions to be thrown from arbitrary signal handlers such as "SIGALRM". This enables -fexceptions.
  • -fdelete-dead-exceptions โ€” considers that instructions which may throw exceptions but don't otherwise contribute to the program's execution can be optimized away ๐Ÿ—‘๏ธ. This does not affect calls to functions except those with the "pure" or "const" attributes. This option is enabled by default for the Ada and C++ compilers, as permitted by the language specifications. Optimization passes that cause dead exceptions to be removed are enabled independently at different optimization levels.
  • -funwind-tables โ€” similar to -fexceptions, except 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. So like, not your job bestie, let the language processor handle it ๐Ÿซถ.
  • -fasynchronous-unwind-tables โ€” generate unwind table in DWARF format, if supported by the target machine ๐ŸŒˆ. The table is exact at each instruction boundary, so it can be used for stack unwinding from asynchronous events (such as debugger or garbage collector). Chef's kiss for debugging ๐Ÿ’….
  • -fno-gnu-unique โ€” okay on systems with a recent GNU assembler and C library, the C++ compiler uses the "STB_GNU_UNIQUE" binding to make sure that definitions of template static data members and static local variables in inline functions are unique even in the presence of "RTLD_LOCAL". Why tho? Because it's necessary to avoid problems with a library used by two different "RTLD_LOCAL" plugins depending on a definition in one of them and therefore disagreeing with the other one about the binding of the symbol. But โ€” and this is the plot twist โ€” this causes "dlclose" to be ignored for affected DSOs ๐Ÿ˜ญ. So if your program relies on reinitialization of a DSO via "dlclose" and "dlopen", you can use -fno-gnu-unique. Fix the vibe, break the other vibe, you know how it is.
  • -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 choice 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, tiny footprint, obsessed.
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. Rude but fair ๐Ÿ˜ญ.

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.

  • -fno-ident โ€” Ignore the "#ident" directive ๐Ÿ™ˆ. That's it. Short queen behavior.
  • -finhibit-size-directive โ€” bestie, this one tells GCC not to spit out a .size assembler directive, or literally anything else that would cause chaos if the function gets split down the middle and the two halves end up placed super far apart in memory ๐Ÿ™ˆ. It's used when compiling crtstuff.c, and that's it โ€” you should not need it for anything else, fr fr.
  • -fverbose-asm โ€” this drops extra commentary into the generated assembly so it's actually readable ๐Ÿ’…. Ngl it's generally only useful for the people who genuinely need to read the generated assembly (like, maybe while debugging the compiler itself, iykyk).

-fno-verbose-asm, which is the default, omits that extra info and is handy when you're comparing two assembler files side by side ๐ŸŽ€.

The added comments include:

  • info on the compiler version and the command-line options,
  • the source code lines tied to the assembly instructions, in the form FILENAME:LINENUMBER:CONTENT OF LINE,
  • hints about 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
Heads up bestie: these comments are meant for humans, not machines, so the precise format of the comments is subject to change ๐Ÿ‘€.
  • -frecord-gcc-switches โ€” this switch makes the command line you used to invoke the compiler get recorded straight into the object file being created ๐ŸŒธ. It's only implemented on some targets, and the exact format of the recording depends on the target and binary file format, but it usually looks like a section containing ASCII text. This switch is related to the -fverbose-asm switch, except that one only records info in the assembler output file as comments, so it never reaches the object file ๐Ÿ‘‘. See also -grecord-gcc-switches for another way of storing compiler options into the object file.
  • -fpic โ€” generates position-independent code (PIC) suitable for use in a shared library, if it's supported for the target machine โœจ. Code like this accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts (and btw, the dynamic loader is not part of GCC โ€” it's part of the operating system). If the GOT size for the linked executable blows past a machine-specific maximum size, you get an error message from the linker saying -fpic does not work; in that case, recompile with -fPIC instead ๐Ÿ’€. (These maximums are 8k on the SPARC, 28k on AArch64 and 32k on the m68k and RS/6000. The x86 has no such limit, iconic.)

Position-independent code requires special support, so it only works on certain machines. For the x86, GCC supports PIC for System V but not for the Sun 386i. Code generated for the IBM RS/6000 is always position-independent, periodt.

When this flag is set, the macros "__pic__" and "__PIC__" are defined to 1.

  • -fPIC โ€” if 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 and
  • -fPIE โ€” these are similar to -fpic and -fPIC, but the generated position-independent code can be only linked into executables ๐Ÿซถ. Usually these options are used 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, so don't stress ๐ŸŽ€.
  • -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, fr fr.

  • *-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, no cap.

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.

And 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 bestie: 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, just so you know ๐Ÿซถ.
  • *-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 โ€” okay so, for targets that normally need trampolines for nested functions, this makes them always generate them instead of using descriptors. And for targets that don't need them at all (hi HP-PA, hi IA-64 ๐Ÿซถ)? It literally does nothing. Nothing. Zero. ๐Ÿ’€

So what even is a trampoline, bestie? It's a tiny lil piece of code that gets created at run time on the stack when the address of a nested function is taken, and it's what lets you call that nested function indirectly. Which means โ€” and this is the part that matters โ€” it requires the stack to be made executable for the program to work properly. ๐Ÿ™ˆ Executable stack. Yeah. That's the vibe.

-fno-trampolines is enabled by default on a language-by-language basis, so the compiler can dodge generating them when it computes that it's safe, and swap in descriptors instead. Descriptors are made up of data only, but the generated code has to be prepared to deal with them. As of this writing, -fno-trampolines is enabled by default only for Ada.

๐Ÿšจ Also, huge heads-up: code compiled with -ftrampolines and code compiled with -fno-trampolines are not binary compatible if nested functions are present. So this option must be used on a program-wide basis and be manipulated with extreme care. Not a lil oopsie. A real one. ๐Ÿ˜ญ

And for languages other than Ada, the -ftrampolines and -fno-trampolines options currently have no effect, and trampolines are always generated on platforms that need them for nested functions. Periodt.

  • -fvisibility=[default|internal|hidden|protected] โ€” this one sets the default ELF image symbol visibility to whatever you picked, meaning all symbols get marked with it unless something overrides it inside the code. Using this can massively improve linking and load times of shared object libraries, produce more optimized code, give you near-perfect API export, and prevent symbol clashes. Use it in every shared object you distribute. That's not a suggestion, that's a whole recommendation. โœจ

Despite the fancy 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.

Ulrich Drepper's "How To Write Shared Libraries" has a good explanation of the benefits of making sure your ELF symbols have the correct visibility (you can find it at https://www.akkadia.org/drepper/) โ€” but there's a superior solution this option unlocks: instead of marking things hidden when the default is public, you make the default hidden and mark things public. That's the norm with DLLs on Windows, and with -fvisibility=hidden and __attribute__ ((visibility("default"))) instead of __declspec(dllexport) you get almost identical semantics with identical syntax. Literally a great boon to those working with cross-platform projects. ๐Ÿฆ‹

If you're adding visibility support to existing code, #pragma GCC visibility may be of use. It works by you enclosing the declarations you want to set visibility for with (for example) #pragma GCC visibility push(hidden) and #pragma GCC visibility pop. Bear in mind that symbol visibility should be viewed as part of the API interface contract, so all new code should always specify visibility when it isn't the default. Like, declarations only for use within the local DSO should always be marked explicitly as hidden, so you avoid PLT indirection overheads โ€” and making it abundantly clear also aids readability and self-documentation of the code. Note that due to ISO C++ specification requirements, operator new and operator delete must always be of default visibility. No exceptions, no cap.

Be aware that headers from outside your project โ€” in particular system headers and headers from any other library you use โ€” may not be expecting to be compiled with visibility other than the default. You might need to explicitly say #pragma GCC visibility push(default) before including any such headers.

extern declarations are not affected by -fvisibility, so a whole lot of code can be recompiled with -fvisibility=hidden with no modifications. But โ€” and you knew there was a but โ€” this means that calls to extern functions with no explicit visibility use 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.

Also note that -fvisibility does affect C++ vague linkage entities. So for instance, an exception class thrown between DSOs must be explicitly marked with default visibility so the type_info nodes get unified between the DSOs.

There's an overview of these techniques, their benefits, and how to use them at https://gcc.gnu.org/wiki/Visibility. Go read it, it slaps. ๐Ÿ“š

  • -fstrict-volatile-bitfields โ€” reach for this one if accesses to volatile bit-fields (or other structure fields, although the compiler usually honors those types anyway) should use a single access of the width of the field's type, aligned to a natural alignment if possible. Example time: targets with memory-mapped peripheral registers might require all such accesses to be 16 bits wide. With this flag you can declare all peripheral bit-fields as unsigned short (assuming short is 16 bits on these targets) to force GCC to use 16-bit accesses instead of, perhaps, a more efficient 32-bit access. ๐Ÿ’…

If this option is disabled, the compiler uses the most efficient instruction. In the previous example, that might be a 32-bit load instruction โ€” even though that accesses bytes that don't contain any portion of the bit-field, or memory-mapped registers unrelated to the one being updated. ๐Ÿ™ƒ

In some cases, such as when the packed attribute is applied to a structure field, it may not be possible to access the field with a single read or write that'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. Ate.

Note: due to restrictions of the C/C++11 memory model, write accesses are not allowed to touch non bit-field members. So it's recommended to define all bits of the field's type as bit-field members. ๐ŸŽ€

The default value of this option is determined by the application binary interface for the target processor.

  • -fsync-libcalls โ€” 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 is enabled, which means the only useful form of the option is -fno-sync-libcalls. This option is used in the implementation of the libatomic runtime library.


GCC Developer Options ๐Ÿ’ปโœจ

Okay bestie, this section is for the devs โ€” the GCC developers themselves. It covers command-line options that are primarily of interest to them, including options to support compiler testing and investigation of compiler bugs and compile-time performance problems. That includes options that produce debug dumps at various points in the compilation; options that print statistics like memory use and execution time; and options that print information about GCC's configuration, like where it searches for libraries. For ordinary compilation and linking tasks you should rarely need any of these. It's giving backstage pass energy only. ๐ŸŽŸ๏ธ

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 โ€” 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. ๐Ÿ—‚๏ธ

  • -fcallgraph-info
  • -fcallgraph-info=MARKERS โ€” makes the compiler output callgraph information for the program, on a per-object-file basis. The info is generated in the common VCG format. It can be decorated with additional, per-node and/or per-edge information if you additionally specify a list of comma-separated markers. When the su marker is specified, the callgraph is decorated with stack usage information โ€” that's equivalent to -fstack-usage. When the da marker is specified, the callgraph is decorated with information about dynamically allocated objects. ๐Ÿ•ธ๏ธ

When compiling with -flto, no callgraph information is output along with the object file. At LTO link time, -fcallgraph-info may generate multiple callgraph information files next to intermediate LTO output files.

  • -dletters
  • -fdump-rtl-pass
  • -fdump-rtl-pass=filename โ€” says to make debugging dumps during compilation at times specified by letters. This is used for debugging the RTL-based passes of the compiler.

Some -dletters switches have different meaning when -E is used for preprocessing.

Debug dumps can be enabled with a -fdump-rtl switch or some -d option letters. Here are the possible letters for use in pass and letters, and their meanings:

  • -fdump-rtl-alignments โ€” dump after branch alignments have been computed.
  • -fdump-rtl-asmcons โ€” dump after fixing rtl statements that have unsatisfied in/out constraints.
  • -fdump-rtl-auto_inc_dec โ€” dump after auto-inc-dec discovery. This pass is only run on architectures that have auto inc or auto dec instructions.
  • -fdump-rtl-barriers โ€” dump after cleaning up the barrier instructions.
  • -fdump-rtl-bbpart โ€” dump after partitioning hot and cold basic blocks.
  • -fdump-rtl-bbro โ€” dump after block reordering.
  • -fdump-rtl-btl1
  • -fdump-rtl-btl2 โ€” -fdump-rtl-btl1 and -fdump-rtl-btl2 enable dumping after the two branch target load optimization passes.
  • -fdump-rtl-bypass โ€” dump after jump bypassing and control flow optimizations.
  • -fdump-rtl-combine โ€” dump after the RTL instruction combination pass ๐Ÿ’…
  • -fdump-rtl-compgotos โ€” dump after duplicating the computed gotos โœจ
  • -fdump-rtl-ce1, -fdump-rtl-ce2, -fdump-rtl-ce3 โ€” these three turn on 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 โ€” these two turn on 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 โ€” these two turn on 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 โ€” these two turn on dumping after the two forward propagation passes ๐Ÿ’œ
  • -fdump-rtl-gcse1, -fdump-rtl-gcse2 โ€” these two turn on 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 โ€” this one turns on 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 โ€” these two turn on dumping after the basic block scheduling passes โญ
  • -fdump-rtl-ree โ€” dump after sign/zero extension elimination ๐Ÿงš
  • -fdump-rtl-seqabstr โ€” dump after common sequence discovery ๐Ÿ“
  • -fdump-rtl-shorten โ€” dump after shortening branches โœ‚๏ธ
  • -fdump-rtl-sibling โ€” dump after sibling call optimizations ๐Ÿซถ
  • -fdump-rtl-split1, -fdump-rtl-split2, -fdump-rtl-split3, -fdump-rtl-split4, -fdump-rtl-split5 โ€” these options enable dumping after five rounds of instruction splitting ๐Ÿ’€
  • -fdump-rtl-sms โ€” dump after modulo scheduling. This pass is only run on some architectures ๐Ÿ‘€
  • -fdump-rtl-stack โ€” dump after conversion from GCC's "flat register file" registers to the x87's stack-like registers. This pass is only run on x86 variants ๐Ÿ’…
  • -fdump-rtl-subreg1, -fdump-rtl-subreg2 โ€” these two turn on dumping after the two subreg expansion passes โœจ
  • -fdump-rtl-unshare โ€” dump after all rtl has been unshared ๐Ÿ”ฅ
  • -fdump-rtl-vartrack โ€” dump after variable tracking ๐ŸŒธ
  • -fdump-rtl-vregs โ€” dump after converting virtual registers to hard registers ๐ŸŽ€
  • -fdump-rtl-web โ€” dump after live range splitting ๐Ÿฆ‹
  • -fdump-rtl-regclass, -fdump-rtl-subregs_of_mode_init, -fdump-rtl-subregs_of_mode_finish, -fdump-rtl-dfinit, -fdump-rtl-dfinish โ€” bestie, these dumps are defined but they always produce empty files ๐Ÿ˜ญ like they show up to the party and contribute nothing, no cap ๐Ÿ’€
  • -da, -fdump-rtl-all โ€” produce all the dumps listed above. Every single one. Go off ๐Ÿ‘‘
  • -dA โ€” annotate the assembler output with miscellaneous debugging information ๐Ÿ’–
  • -dD โ€” dump all macro definitions at the end of preprocessing, in addition to normal output ๐Ÿ“
  • -dH โ€” produce a core dump whenever an error occurs ๐Ÿ’ฅ
  • -dp โ€” annotate the assembler output with a comment indicating which pattern and alternative is used. The length and cost of each instruction are also printed ๐Ÿ’…
  • -dP โ€” dump the RTL in the assembler output as a comment before each instruction. Also turns on -dp annotation โœจ
  • -dx โ€” just generate RTL for a function instead of compiling it. Usually used with -fdump-rtl-expand ๐Ÿงš

  • -fdump-debug โ€” dump debugging information generated during the debug generation phase ๐Ÿ›
  • -fdump-earlydebug โ€” dump debugging information generated during the early debug generation phase ๐Ÿ›โœจ
  • -fdump-noaddr โ€” when doing debugging dumps, suppress address output. This makes it more feasible to use diff on debugging dumps for compiler invocations with different compiler binaries and/or different text / bss / data / heap / stack / dso start locations ๐Ÿซถ
  • -freport-bug โ€” collect and dump debug information into a temporary file if an internal compiler error (ICE) occurs ๐ŸงŠ๐Ÿ“„
  • -fdump-unnumbered โ€” when doing debugging dumps, suppress instruction numbers and address output. This makes it more feasible to use diff on debugging dumps for compiler invocations with different options, in particular with and without -g ๐Ÿ‘‘
  • -fdump-unnumbered-links โ€” when doing debugging dumps (see the -d option above), suppress instruction numbers for the links to the previous and next instructions in a sequence ๐Ÿ”—
  • -fdump-ipa-switch, -fdump-ipa-switch-options โ€” control the dumping at various stages of inter-procedural analysis language tree to a file. The file name is generated by appending a switch specific suffix to the source file name, and the file is created in the same directory as the output file. The following dumps are possible:
    • all โ€” enables all inter-procedural analysis dumps ๐ŸŒˆ
    • cgraph โ€” dumps information about call-graph optimization, unused function removal, and inlining decisions ๐Ÿ“Š
    • inline โ€” dump after function inlining ๐Ÿซถ

Additionally, the options -optimized, -missed, -note, and -all can be provided, with the same meaning as for -fopt-info, defaulting to -optimized โœจ

For example, -fdump-ipa-inline-optimized-missed will emit information on callsites that were inlined, along with callsites that were not inlined ๐Ÿ‘€

By default, the dump will contain messages about successful optimizations (equivalent to -optimized) together with low-level details about the analysis ๐Ÿ’…

  • -fdump-ipa-clones โ€” create a dump file containing information about creation of call graph node clones and removals of call graph nodes during inter-procedural optimizations and transformations. Its main intended use is that tools that create live-patches can determine the set of functions that need to be live-patched to completely replace a particular function (see -flive-patching). The file name is generated by appending suffix "ipa-clones" to the source file name, and the file is created in the same directory as the output file. Each entry in the file is on a separate line containing semicolon separated fields ๐ŸŽ€

In the case of call graph clone creation, the individual fields are:

  1. String "Callgraph clone".
  2. Name of the function being cloned as it is presented to the assembler.
  3. A number that uniquely represents the function being cloned in the call graph. Note that the number is unique only within a compilation unit or within whole-program analysis but is likely to be different in the two phases.
  4. The file name of the source file where the function is defined.
  5. The line on which the function definition is located.
  6. The column where the function definition is located.
  7. Name of the new function clone as it is presented to the assembler.
  8. A number that uniquely represents the new function clone in the call graph. Note that the number is unique only within a compilation unit or within whole-program analysis but is likely to be different in the two phases.
  9. The file name of the source file where the source code location of the new clone points to.
  10. The line to which the source code location of the new clone points to.
  11. The column to which the source code location of the new clone points to.
  12. A string that determines the reason for cloning.

In the case of call graph clone removal, the individual fields are:

  1. String "Callgraph removal".
  2. Name of the function being removed as it would be presented to the assembler.
  3. A number that uniquely represents the function being cloned in the call graph. Note that the number is unique only within a compilation unit or within whole-program analysis but is likely to be different in the two phases.
  4. The file name of the source file where the function is defined.
  5. The line on which the function definition is located.
  6. The column where the function definition is located.
  • -fdump-lang โ€” dump language-specific information. The file name is made by appending .lang to the source file name ๐ŸŒ
  • -fdump-lang-all, -fdump-lang-switch, -fdump-lang-switch-options, -fdump-lang-switch-options=filename โ€” control the dumping of language-specific information. The options and filename portions behave as described in the -fdump-tree option. The following switch values are accepted:
    • all โ€” enable all language-specific dumps โœจ
    • class โ€” dump class hierarchy information. Virtual table information is emitted unless 'slim' is specified. This option is applicable to C++ only ๐Ÿ’œ
  • module โ€” dump the module info. Bestie, the extra options lineno (for locations), graph (reachability), blocks (clusters), uid (serialization), alias (mergeable), asmname (Elrond), eh (mapper) and vops (macros) can give you even more deets. C++ only, so don't come crying if you're on C. ๐Ÿ’…
  • raw โ€” dumps the raw internal tree data. Also C++ only. It's giving "behind the scenes" energy.

  • -fdump-passes โ€” prints the list of optimization passes that are getting turned on and off by your current command-line options, straight to stderr. Like a lil receipt of your vibe check. โœจ
  • -fdump-statistics-option โ€” enables and controls dumping of pass statistics into a separate file. The file name is made by appending a suffix that ends in .statistics to the source file name, and it lives in the same directory as your output file. If you use the -option form, then:
    • -stats โ€” counters get summed over the whole compilation unit
    • -details โ€” dumps every event as the passes generate them

The default with no option at all? Sum counters for each function compiled. Periodt. ๐Ÿซถ

  • -fdump-tree-all
  • -fdump-tree-switch
  • -fdump-tree-switch-options
  • -fdump-tree-switch-options=filename

Controls the dumping at various stages of processing the intermediate language tree into a file. If you go with the -options form, options is a list of --separated options that control the dump details. Lowkey, not every option works for every dump โ€” the ones that don't mean anything just get ignored. No hard feelings. ๐Ÿ™ˆ

The following options are available:

  • address โ€” print the address of each node. Usually this isn't super meaningful because it changes depending on the environment and source file. Its main character use is 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. Main use case: making it easier to work backwards from mangled names in the assembly file.
  • slim โ€” when dumping front-end intermediate representations, this inhibits dumping of members of a scope or the body of a function just because that scope was reached. Only dump those items when they're 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 includes info from the optimization passes. ๐Ÿ’…
  • stats โ€” enable dumping of various statistics about the pass (again, 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 that's suitable for viewing with GraphViz to file.passid.pass.dot. Every function in the file gets pretty-printed as a subgraph, so GraphViz can render them all in one single plot. Iconic behavior, honestly.

This option currently only works for RTL dumps, and the RTL is always dumped in slim form. No cap.

  • 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 โ€” turns on all options, except raw, slim, verbose and lineno.
  • optall โ€” turns 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 you actually care about, follow these steps, bestie:

  1. Invoke GCC with -fdump-passes and in the stderr output look for a code that corresponds to the pass you're 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. So for example, to enable the dump from the Early Value Range Propagation pass, invoke GCC with the -fdump-tree-evrp option. Optionally you can specify the name of the dump file. If you don't specify one, GCC creates it as described below.
  3. Find the pass dump in a file whose name is composed of three components separated by a period:
    • the name of the source file GCC was invoked to compile,
    • a numeric suffix indicating the pass number followed by the letter t for tree passes (and the letter r for RTL passes),
    • and finally the pass code.

For example, the Early VRP pass dump might be in a file named myfile.c.038t.evrp in the current working directory. Heads up though: 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 you use the -options form, options is a list of --separated option keywords used to select the dump details and optimizations.

These options split 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.

You can freely mix options from each group since they're non-overlapping. But bestie, if there's any conflict, the later options override the earlier ones on the command line. Them's the rules. ๐Ÿ’…

The following options control which kinds of messages get emitted:

  • optimized โ€” print information when an optimization is successfully applied. It's up to a pass to decide which info is relevant. For example, the vectorizer passes print the source location of loops that get successfully vectorized. โœจ
  • missed โ€” print information about missed optimizations. Individual passes control what info goes into the output.
  • note โ€” print verbose information about optimizations, like certain transformations, more detailed messages about decisions, etc.
  • all โ€” print detailed optimization information. This includes optimized, missed, and note.

The following option controls the dump verbosity:

  • internals โ€” by default only "high-level" messages are emitted. This option enables additional, more detailed messages that are likely only of interest to GCC developers.

One or more of the following option keywords can be used to describe a group of optimizations:

  • ipa โ€” enable dumps from all interprocedural optimizations.
  • loop โ€” enable dumps from all loop optimizations.
  • inline โ€” enable dumps from all inlining optimizations.
  • omp โ€” enable dumps from all OMP (Offloading and Multi Processing) optimizations.
  • vec โ€” enable dumps from all vectorization optimizations.
  • optall โ€” enable dumps from all optimizations. This is a superset of the optimization groups listed above.

If options is omitted, it defaults to optimized-optall, which means: dump messages about successful optimizations from all the passes, omitting messages that are treated as "internals".

If filename is provided, then the dumps from all the applicable optimizations get concatenated into filename. Otherwise the dump is output onto stderr. And yeah, though multiple -fopt-info options are accepted, only one of them can include a filename. If other filenames are provided, everything except the first such option is ignored. ๐Ÿ™ˆ

Watch out: the output filename gets overwritten if there are multiple translation units. If you want a combined output from multiple translation units, use stderr instead.

In the following example, the optimization info is output to stderr:

gcc -O3 -fopt-info

This example:

gcc -O3 -fopt-info-missed=missed.all

outputs the missed optimization report from all the passes into missed.all. And this one:

gcc -O2 -ftree-vectorize -fopt-info-vec-missed

prints info about missed optimization opportunities from vectorization passes on stderr. Ngl, note that -fopt-info-vec-missed is equivalent to -fopt-info-missed-vec. The order of the optimization group names and message types listed after -fopt-info does not matter. ๐Ÿฆ‹

As another example:

gcc -O3 -fopt-info-inline-optimized-missed=inline.txt

outputs info about missed optimizations as well as optimized locations from all the inlining passes into inline.txt.

And 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. So only vec.miss is produced, which contains dumps from the vectorizer about missed opportunities. ๐Ÿ’€

  • -fsave-optimization-record โ€” writes 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 inside the compressed JSON file is subject to change. Don't get too attached, bestie. ๐Ÿ˜ญ

It's roughly equivalent to a machine-readable version of -fopt-info-all, as a collection of messages with source file, line number and column number, plus the following additional data for each message:

  • the execution count of the code getting optimized, plus the lil metadata about whether that count came from actual profile data or was just a vibe-based estimate โ€” so whoever's reading can sort messages by code hotness ๐Ÿ”ฅ
  • the function name of the code being optimized, where applicable ๐Ÿ’…
  • the "inlining chain" for the code being optimized โ€” so when a function gets inlined into a bunch of different spots (which might themselves be inlined, it's giving nesting dolls fr), the reader can tell all the copies apart ๐Ÿ‘‘
  • objects that identify which parts of the message refer to expressions, statements or symbol-table nodes, which of those categories they are, and โ€” when it's available โ€” their source code location ๐Ÿ“
  • the GCC pass that emitted the message โœจ
  • and the location in GCC's own code from which the message got emitted ๐Ÿซถ

On top of all that, some messages are logically nested inside other messages, reflecting implementation details of the optimization passes. iykyk ๐Ÿ’œ


๐Ÿฆ‹ -fsched-verbose=n

On targets that actually use instruction scheduling, this one controls how much debugging output the scheduler prints into the dump files.

  • For n greater than zero, -fsched-verbose spits out the same info as -fdump-rtl-sched1 and -fdump-rtl-sched2.
  • For n greater than one, it also gives you basic block probabilities, detailed ready list info, and unit/insn info.
  • For n greater than two, it adds RTL at abort point, plus control-flow and regions info.
  • And for n over four, -fsched-verbose also includes dependence info.

โœจ -fenable-kind-pass / -fdisable-kind-pass=range-list

Okay bestie, this is a whole set of options used to explicitly disable/enable optimization passes. These are meant for debugging GCC itself, k? Regular compiler users should just use the normal options for enabling/disabling passes instead โ€” no cap.

  • -fdisable-ipa-pass โ€” Disable IPA pass pass. pass is the pass name. If that same pass gets statically invoked in the compiler more than once, you append the pass name 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 multiple times, append the pass name with a sequential number starting from 1. The range-list is a comma-separated list of function ranges or assembler names. Each range is a number pair split by a colon, and the range is inclusive on both ends. If the range is trivial, that number pair can be simplified down to a single number. If the function's call graph node's uid falls inside one of the specified ranges, the pass is disabled for that function. The uid shows up in the function header of a dump file, and you can dump the pass names with the option -fdump-passes.
  • -fdisable-tree-pass, -fdisable-tree-pass=range-list โ€” Disable tree pass pass. Peep -fdisable-rtl for the description of the option arguments.
  • -fenable-ipa-pass โ€” Enable IPA pass pass. pass is the pass name. If the same pass is statically invoked multiple times, append the pass name with a sequential number starting from 1.
  • -fenable-rtl-pass, -fenable-rtl-pass=range-list โ€” Enable RTL pass pass. Peep -fdisable-rtl for the option argument description and examples.
  • -fenable-tree-pass, -fenable-tree-pass=range-list โ€” Enable tree pass pass. Peep -fdisable-rtl for the description of the option arguments.

Here are some examples showing uses of these options โ€” icons only, periodt:

        # 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 how the compiler was configured. And -fchecking=2 turns on even further internal consistency checking that might actually affect code generation. slay but be careful ๐Ÿ’…


๐ŸŽ€ -frandom-seed=string

This option hands GCC a seed to use instead of random numbers when it's generating certain symbol names that gotta be different in every single compiled file. It's also used to drop unique stamps into coverage data files and the object files that produce them. So you can use -frandom-seed to produce reproducibly identical object files โ€” obsessed โœจ

The string can either be a number (decimal, octal or hex) or an arbitrary string โ€” in which case it gets converted to a number by computing CRC32.

The string should be different for every file you compile, bestie. fr fr.


๐ŸŒธ -save-temps

Store the usual "temporary" intermediate files permanently; name them as auxiliary output files, exactly as described under -dumpbase and -dumpdir.

When you use it together with the -x command-line option, -save-temps is sensible enough to avoid overwriting an input source file that has the same extension as an intermediate file. The corresponding intermediate file can be obtained by renaming the source file before using -save-temps.

  • -save-temps=cwd โ€” Equivalent to -save-temps -dumpdir ./.
  • -save-temps=obj โ€” Equivalent to -save-temps -dumpdir outdir/, where outdir/ is the directory of the output file specified after the -o option, including any directory separators. And if the -o option isn't used, the -save-temps=obj switch behaves like -save-temps=cwd.

โฑ๏ธ -time[=file]

Report the CPU time taken by each subprocess in the compilation sequence. For C source files, this is the compiler proper and the assembler (plus the linker if linking is done, bestie).

Without specifying an output file, the output looks like this:

        # cc1 0.12 0.01
        # as 0.00 0.01

The first number on each line is the "user time" โ€” that's time spent executing the program itself. The second number is "system time" โ€” time spent executing operating system routines on behalf of the program. Both numbers are in seconds. ๐Ÿ•

And with an output file specified, the output gets appended to that named file, and it looks like this:

        0.12 0.01 cc1 <options>
        0.00 0.01 as <options>

Here the "user time" and the "system time" move before the program name, and the options passed to the program get displayed too โ€” so you can later tell what file was being compiled, and with which options. icon behavior honestly ๐ŸŒˆ


๐Ÿ’… -fdump-final-insns[=file]

Dump the final internal representation (RTL) to file. If the optional argument is omitted (or if file is .), the name of the dump file gets determined by appending .gkd to the dump base name โ€” see -dumpbase.


๐Ÿฆ‹ -fcompare-debug[=opts]

If no error happens during compilation, run the compiler a second time, adding opts and -fcompare-debug-second to the arguments passed to that second compilation. Dump the final internal representation in both compilations, and print an error if they differ. it's giving double-checking bestie ๐Ÿ’–

If the equal sign is omitted, the default -gtoggle is used.

The environment variable GCC_COMPARE_DEBUG, if it's defined, non-empty and nonzero, implicitly enables -fcompare-debug. And if GCC_COMPARE_DEBUG is defined to a string starting with a dash, then it's used for opts โ€” otherwise the default -gtoggle is used.

-fcompare-debug=, with the equal sign but without opts, is equivalent to -fno-compare-debug, which disables the dumping of the final representation and the second compilation, preventing even GCC_COMPARE_DEBUG from taking effect.

To verify full coverage during -fcompare-debug testing, set GCC_COMPARE_DEBUG to say -fcompare-debug-not-overridden, which GCC rejects as an invalid option in any actual compilation (rather than preprocessing, assembly or linking). To get just a warning instead, setting GCC_COMPARE_DEBUG to -w%n-fcompare-debug not overridden will do.


๐Ÿ™ˆ -fcompare-debug-second

This option gets implicitly passed to the compiler for the second compilation that -fcompare-debug requested, along with options to silence warnings, and it omits other options that would cause the compiler to produce output to files or to standard output as a side effect. Dump files and preserved temporary files get renamed so they contain the .gk additional extension during the second compilation, so nothing overwrites what the first one generated. ๐Ÿ’œ

When you pass this option to the compiler driver, it makes the first compilation get skipped โ€” which makes it useful for little other than debugging the compiler proper. ngl that's its whole personality ๐Ÿ˜ญ


๐Ÿ”ฅ -gtoggle

Turn off generation of debug info, if leaving out this option generates it, or turn it on at level 2 otherwise. The position of this argument in the command line does not matter โ€” it takes effect after all other options are processed, and it does so only once, no matter how many times it's given. This is mainly intended to be used with -fcompare-debug. โœจ


โญ -fvar-tracking-assignments-toggle

Toggle -fvar-tracking-assignments, in the same way that -gtoggle toggles -g. simple as that bestie ๐Ÿ’…


๐Ÿ‘‘ -Q

Makes the compiler print out each function name as it's compiled, and print some statistics about each pass when it finishes. satisfying fr ๐ŸŒˆ


๐Ÿ• -ftime-report

Makes the compiler print some statistics about the time consumed by each pass when it finishes.

๐Ÿ• -ftime-report-details

Record the time consumed by infrastructure parts separately for each pass.


๐Ÿงš -fira-verbose=n

Control the verbosity of the dump file for the integrated register allocator. The default value is 5. And 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. slay ๐Ÿ’…

  • -flto-report โ€” bestie, this prints a lil report with the internal deets on how the link-time optimizer is doing its thing. Heads up tho: what's inside this report changes from version to version, so don't get attached. It's meant to be useful to GCC devs when they're processing object files in LTO mode (that's via -flto). ๐Ÿ’…

Disabled by default. (sad but true ๐Ÿซ )

  • -flto-report-wpa โ€” literally -flto-report's sibling, except it only prints for the WPA phase of link-time optimization. picky king behavior โœจ
  • -fmem-report โ€” makes the compiler spill some statistics about permanent memory allocation when it finishes. it's giving receipts at the end of the party ๐Ÿ“Š
  • -fmem-report-wpa โ€” same energy as -fmem-report, except it prints those permanent-memory-allocation stats for the WPA phase only. no notes ๐ŸŽ€
  • -fpre-ipa-mem-report, -fpost-ipa-mem-report โ€” makes the compiler print some permanent memory allocation statistics before or after interprocedural optimization. before and after pics, but for memory ๐Ÿ˜Œ
  • -fmultiflags โ€” okay so this one enables multilib-aware "TFLAGS" to be used to build target libraries with options that are different from the ones the compiler is configured to use by default, and it does it through the use of specs. yes, specs. we love a technical queen ๐Ÿ’œ

So, like "TFLAGS", this lets the target libraries get built for portable baseline environments while the compiler itself defaults to more demanding ones. And that's actually useful because users can easily override the defaults the compiler is configured to use when building their own programs (say the defaults aren't ideal for their target environment), whereas rebuilding the runtime libraries is usually not as easy or desirable. no cap.

But unlike "TFLAGS", using specs lets different flags be selected for different multilibs. the way u do that: build with make TFLAGS=-fmultiflags, after configuring --with-specs=%{fmultiflags:...}.

This option is discarded by the driver once it's done processing driver self spec. bye felicia ๐Ÿ‘‹

It's also useful for checking that "TFLAGS" are being used to build all target libraries, by configuring a non-bootstrap compiler --with-specs='%{!fmultiflags:%emissing TFLAGS}' and building the compiler and target libraries. chef's kiss ๐Ÿ”ฅ

  • -fprofile-report โ€” makes the compiler print some statistics about how consistent the (estimated) profile is and the effect of individual passes. gossip about ur own code's behavior, honestly iconic ๐Ÿ’…
  • -fstack-usage โ€” makes the compiler output stack usage info for the program, per-function, bestie. the filename for the dump is made by appending .su to the auxname. and auxname? it's generated from the name of the output file (if it's explicitly specified and it's not an executable), otherwise it's the basename of the source file. okay so an entry is made up of three fields:
    • the name of the function.
    • a number of bytes.
    • one or more qualifiers: "static", "dynamic", "bounded".

So 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 in the function. in that case the second field is this fixed number of bytes. cute and predictable ๐ŸŽ€

The qualifier "dynamic" means the function manipulates the stack dynamically: in addition to the static allocation described above, stack adjustments get made in the body of the function, like to push/pop arguments around function calls. If the qualifier "bounded" is also present, then the amount of these adjustments is bounded at compile time, and the second field is an upper bound of the total amount of stack used by the function. If "bounded" is not present, then the amount of these adjustments is not bounded at compile time, and the second field only represents the bounded part. so like, partial info, don't be fooled ๐Ÿ™ˆ

  • -fstats โ€” emit statistics about front-end processing at the end of the compilation. ngl this option is supported only by the C++ front end, and the info is generally only useful to the G++ development team. so it's giving internal-scoop-only ๐Ÿ”
  • -fdbg-cnt-list โ€” print the name and the counter upper bound for all debug counters. the full roster, no crumbs left behind ๐Ÿ‘‘
  • *-fdbg-cnt=counter-value-list* โ€” set the internal debug counter lower and upper bound. so 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. math queen behavior fr fr โœจ
  • -print-file-name=library โ€” print the *full absolute name of the library file *library that would be used when linking---and don't do anything else. With this option, GCC does not compile or link anything; it just prints the file name. one job and it SLAYs at it ๐Ÿ’…
  • -print-multi-directory โ€” print the directory name corresponding to the multilib selected by any other switches present in the command line. this directory is supposed to exist in GCC_EXEC_PREFIX.
  • -print-multi-lib โ€” print the mapping from multilib directory names to compiler switches that enable them. the directory name is separated from the switches by ;, and each switch starts with an @ instead of the -, with no spaces between multiple switches. this is supposed to ease shell processing. very considerate of them actually ๐Ÿซถ
  • -print-multi-os-directory โ€” print the path to OS libraries for the selected multilib, relative to some lib subdirectory. If OS libraries are present in the lib subdirectory and no multilibs are used, this is usually just ., if OS libraries are present in libsuffix sibling directories then 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. it's giving choose-your-own-adventure with paths ๐Ÿ“
  • -print-multiarch โ€” print the path to OS libraries for the selected multiarch, relative to some lib subdirectory. short, sweet, iconic.
  • *-print-prog-name=program* โ€” like -print-file-name, but it searches for a program such as cpp. different hunt, same energy ๐Ÿ”
  • -print-libgcc-file-name โ€” same as -print-file-name=libgcc.a.

This is useful when you use -nostdlib or -nodefaultlibs but you do want to link with libgcc.a. u can do:

gcc -nostdlib <files>... `gcc -print-libgcc-file-name`

look at that backtick moment, we love a shell substitution โœจ

  • -print-search-dirs โ€” print the name of the configured installation directory and a list of program and library directories gcc searches---and don't do anything else.

This is 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 /. like actually don't, bestie, it will not work ๐Ÿ˜ญ

  • -print-sysroot โ€” print the target sysroot directory that's used during compilation. This is the target sysroot specified either at configure time or using the --sysroot option, possibly with an extra suffix that depends on compilation options. If no target sysroot is specified, the option prints nothing. silence. crickets. ๐Ÿฆ—
  • -print-sysroot-headers-suffix โ€” print the suffix added to the target sysroot when searching for headers, or give an error if the compiler is not configured with such a suffix---and don't do anything else. it's giving all-or-nothing ๐Ÿ™ˆ
  • -dumpmachine โ€” print the compiler's target machine (for example, i686-pc-linux-gnu)---and don't do anything else. identity reveal moment ๐Ÿ’…
  • -dumpversion โ€” print the compiler version (for example, 3.0, 6.3.0 or 7)---and don't do anything else. This is the compiler version used in filesystem paths and specs. Depending on how the compiler has been configured, it can be just a single number (major version), two numbers separated by a dot (major and minor version) or three numbers separated by dots (major, minor and patchlevel version). so basically it might give u 1, 2, or 3 numbers, depends on the vibe check of the config ๐ŸŽ€
  • -dumpfullversion โ€” print the full compiler version---and don't do anything else. The output is always three numbers separated by dots, major, minor and patchlevel version. no ambiguity, no crumbs, we love consistency โœจ
  • -dumpspecs โ€” print the compiler's built-in specs---and don't do anything else. (This is used when GCC itself is being built.) behind-the-scenes tea โ˜•

Machine-Dependent Options ๐Ÿ› ๏ธ

Okay so here's the thing bestie: each target machine supported by GCC can have its own options---like, to let u compile for a particular processor variant or ABI, or to control optimizations specific to that machine. By convention, the names of machine-specific options start with -m. iykyk ๐Ÿ’…

Some configurations of the compiler also support additional target-specific options, usually for compatibility with other compilers on the same platform. friendly like that ๐Ÿซถ

AArch64 Options ๐ŸŒˆ

These options are defined for AArch64 implementations:

  • *-mabi=name* โ€” generate code for the specified data model. 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. no mixing, bestie, that's a crime fr ๐Ÿ’€

  • -mbig-endian โ€” generate big-endian code. This is the default when GCC is configured for an aarch64_be-*-* target. big endian bestie ๐Ÿ’œ
  • -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. so the compiler chills but the assembler does whatever it wants ๐Ÿ˜ญ
  • -mlittle-endian โ€” generate little-endian code. This is the default when GCC is configured for an aarch64-*-* but not an aarch64_be-*-* target. the lil endian icon ๐ŸŽ€
  • -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. smol but mighty ๐Ÿฃ
  • -mcmodel=small โ€” generate code for the small code model. The program and its statically defined symbols must be within 4GB of each other. Programs can be statically or dynamically linked. This is the default code model. the main character of code models ๐Ÿ‘‘
  • -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. big model, big rules, and some of those combos? absolutely not bestie ๐Ÿšซ
  • -mstrict-align
  • -mno-strict-align โ€” okay so this is the alignment vibe check ๐Ÿ’… -mstrict-align says no ma'am to generating memory accesses that aren't lined up on a natural object boundary like the architecture spec describes, and -mno-strict-align is like "eh, go off, do whatever." Pick your fighter.
  • -momit-leaf-frame-pointer
  • -mno-omit-leaf-frame-pointer โ€” do we keep the frame pointer in leaf functions or not? ๐Ÿซถ -momit-leaf-frame-pointer yeets it, -mno-omit-leaf-frame-pointer keeps it around. And the yeeting one? That's literally the default. periodt.
  • *-mstack-protector-guard=guard*
  • *-mstack-protector-guard-reg=reg*
  • *-mstack-protector-guard-offset=offset* โ€” stack protection code time, bestie ๐Ÿ›ก๏ธ what this does is generate the stack protection using a canary at guard. The supported locations are global for a global canary, or sysreg for a canary living in an appropriate system register.

If you pick that second one, then -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset come in and specify which system register to use as the base register for reading the canary, plus what offset from that base register to read from. Heads up tho: there's no default register or offset, because this is entirely for use inside the Linux kernel. ikyk. ๐Ÿ”ฅ

  • -mtls-dialect=desc โ€” use TLS descriptors as the thread-local storage mechanism for dynamic accesses of TLS variables โœจ and yeah, this one's the default.
  • -mtls-dialect=traditional โ€” use traditional TLS as the thread-local storage mechanism for dynamic accesses of TLS variables. old school, still slays ๐ŸŽ€
  • -mtls-size=size โ€” set the bit size of immediate TLS offsets ๐Ÿ’ซ valid values are 12, 24, 32, 48. Oh and this option **requires binutils 2.26 or newer, no cap.
  • -mfix-cortex-a53-835769
  • -mno-fix-cortex-a53-835769 โ€” turn the workaround for the ARM Cortex-A53 erratum number 835769 on or off ๐Ÿ’€ what the workaround actually does is insert a NOP instruction between memory instructions and 64-bit integer multiply-accumulate instructions. tiny little breather in the pipeline, iconic.
  • -mfix-cortex-a53-843419
  • -mno-fix-cortex-a53-843419 โ€” turn the workaround for the ARM Cortex-A53 erratum number 843419 on or off ๐ŸŒธ this erratum workaround is made at link time, and this option will only pass the corresponding flag to the linker. so it's like, not even doing the thing itself, it's delegating. main character energy fr fr.
  • -mlow-precision-recip-sqrt
  • -mno-low-precision-recip-sqrt โ€” enable or disable the reciprocal square root approximation ๐Ÿงฎ honestly? this option only has an effect if -ffast-math or -funsafe-math-optimizations is used as well. enabling it reduces the precision of reciprocal square root results to about 16 bits for single precision and to 32 bits for double precision. speed over accuracy, we love a tradeoff ๐Ÿ’…
  • -mlow-precision-sqrt
  • -mno-low-precision-sqrt โ€” enable or disable the square root approximation ๐ŸŒˆ same deal, it only has an effect if -ffast-math or -funsafe-math-optimizations is used as well. enabling it drops the precision of square root results to about 16 bits for single precision and 32 bits for double precision. Oh and plot twist โ€” if you enable it, it implies -mlow-precision-recip-sqrt. package deal bestie ๐ŸŽ
  • -mlow-precision-div
  • -mno-low-precision-div โ€” enable or disable the division approximation ๐Ÿ“ yes this one is also only doing anything if -ffast-math or -funsafe-math-optimizations is used as well. enabling it reduces the precision of division results to about 16 bits for single precision and 32 bits for double precision.
  • -mtrack-speculation
  • -mno-track-speculation โ€” enable or disable generating extra code to track speculative execution through conditional branches ๐Ÿ‘€ that tracking state can then be used by the compiler when it's expanding calls to __builtin_speculation_safe_copy, which lets it generate a more efficient code sequence. smart girl behavior ngl.
  • -moutline-atomics
  • -mno-outline-atomics โ€” enable or disable calls to out-of-line helpers that implement atomic operations โš›๏ธ these helpers will, at runtime, figure out whether the LSE instructions from ARMv8.1-A can be used; and if they can't, they'll fall back to the load/store-exclusive instructions that are present in the base ARMv8.0 ISA. adaptive queen ๐Ÿ’–

This option is only applicable when compiling for the base ARMv8.0 instruction set. If you're on a later revision โ€” like -march=armv8.1-a or -march=armv8-a+lse โ€” then the ARMv8.1-Atomics instructions get used directly. Same story when you're using -mcpu= and the selected cpu supports the lse feature. Oh, and it's 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}*.

Here's the rundown of what values for arch are allowed and what features they turn on by default:

arch value : Architecture : Includes by default
armv8-a : Armv8-A : +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.7-a : Armv8.7-A : armv8.6-a, +ls64
armv8.8-a : Armv8.8-a : armv8.7-a, +mops
armv9-a : Armv9-A : armv8.5-a, +sve, +sve2
armv9.1-a : Armv9.1-A : armv9-a, +bf16, +i8mm
armv9.2-a : Armv9.2-A : armv9.1-a, +ls64
armv9.3-a : Armv9.3-A : armv9.2-a, +mops
armv8-r : Armv8-R : armv8-r

The value native is available on native AArch64 GNU/Linux and it makes the compiler pick the architecture of the host system ๐Ÿ–ฅ๏ธ this option has no effect if the compiler can't recognize the architecture of the host system, tho.

The permissible values for feature are listed in the sub-section on aarch64-feature-modifiers, -march and -mcpu Feature Modifiers. And if you specify conflicting feature modifiers? The right-most feature wins. always the right-most, periodt ๐Ÿ’…

GCC uses name to decide what kind of instructions it can emit when generating assembly code ๐Ÿ”ฅ and if -march is specified without either -mtune or -mcpu also being specified, the code gets tuned to perform well across a range of target processors implementing the target architecture. broad appeal, honestly iconic.

  • *-mtune=name* โ€” specify the name of the target processor that GCC should tune the performance of the code for ๐ŸŒŸ the 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, cortex-x1c, cortex-x2, cortex-x3, cortex-a510, cortex-a710, cortex-a715, ampere1, ampere1a, cobalt-100 and native.

The values cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a73.cortex-a35, cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55 specify that GCC should tune for a big.LITTLE system ๐Ÿ‘‘ two moods, one chip.

The value neoverse-512tvb specifies that GCC should tune for Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits per cycle โœจ in other words, the option tells GCC to tune for Neoverse cores that can execute 4 128-bit Advanced SIMD arithmetic instructions a cycle and can execute an equivalent number of SVE arithmetic instructions per cycle (2 for 256-bit SVE, 4 for 128-bit SVE). This is more general than tuning for a specific core like Neoverse V1, but it's also more specific than the default tuning described below. she's in between, she contains multitudes ๐Ÿ’…

Also, on native AArch64 GNU/Linux systems, the value native tunes performance to the host system ๐Ÿ–ฅ๏ธ this option has no effect if the compiler can't recognize the processor of the host system.

If none of -mtune=, -mcpu= or -march= are specified, the code gets tuned to perform well across a range of target processors โœจ

And important: this option cannot be suffixed by feature modifiers. don't even try it, bestie ๐Ÿ™ˆ

  • -mcpu=name โ€” specify the name of the target processor, optionally suffixed by one or more feature modifiers ๐Ÿ’ซ this option has the form -mcpu=cpu{+[no]feature}*, where the permissible values for cpu are the same ones available for -mtune. The permissible values for feature are documented in the sub-section on aarch64-feature-modifiers, -march and -mcpu Feature Modifiers. Where conflicting feature modifiers are specified, the **right-most feature is used. (same rule as -march, consistency queen ๐Ÿ‘‘)

GCC uses name to determine what kind of instructions it can emit when generating assembly code โ€” as if by -march โ€” and also to determine the target processor to tune performance for โ€” as if by -mtune ๐ŸŽ€ but where this option is used alongside -march or -mtune, those options take precedence over the appropriate part of this option. so -mcpu is doing both jobs, but the specialists get to override. respect the hierarchy ๐Ÿ’…

-mcpu=neoverse-512tvb is special ๐ŸŒŸ because it doesn't 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 it's 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 it's overridden by -mtune, -mcpu=neoverse-512tvb tunes code in the same way as for -mtune=neoverse-512tvb. ๐Ÿค

  • -moverride=string โ€” override tuning decisions made by the back-end in response to a -mtune= switch ๐Ÿ› ๏ธ fair warning: the syntax, semantics, and accepted values for string in this option are **not guaranteed to be consistent across releases. it's giving unstable API, ngl.
This option is only intended to be useful when developing GCC. iykyk โ€” if that's not you, walk away bestie ๐Ÿšถโ€โ™€๏ธ๐Ÿ’จ
  • -mverbose-cost-dump โ€” enable verbose cost model dumping in the debug dump files ๐Ÿ“Š this option is provided for use in debugging the compiler. for the compiler girlies only ๐Ÿ’…
  • -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. That limits the maximum size of functions to 1MB โ€” yeah, keep that in mind ๐Ÿซ  and this is enabled by default for -mcmodel=tiny.
  • -msign-return-address=scope โ€” ok so this picks which functions get return address signing, bestie. The allowed values are none (signing off entirely, nada), non-leaf (pointer signing for the functions that are not leaf functions), and all (every single function gets signed, no exceptions, periodt). Default is none. ๐Ÿซถ Heads up though: this option has been deprecated by -mbranch-protection.
  • -mbranch-protection=none|standard|pac-ret[+leaf+b-key]|bti โ€” choose your branch protection features, bestie, it's giving security โœจ. none is the default and turns off every type of branch protection. standard turns on all types of branch protection features, and if a feature has extra tuning options, standard just sets it to its standard level. pac-ret[+leaf] turns on return address signing at its standard level โ€” meaning it signs functions that save the return address to memory (non-leaf functions will practically always do this), using the a-key. The optional argument leaf extends the signing to include leaf functions too. The optional argument b-key signs the functions with the B-key instead of the A-key. And bti turns on the branch target identification mechanism. ๐Ÿ’…
  • -mharden-sls=opts โ€” this one enables compiler hardening against straight line speculation, aka SLS. opts is a comma-separated list of these:
    • retbr
    • blr

Also, -mharden-sls=all enables all SLS hardening, while -mharden-sls=none disables all of it. ๐Ÿ”ฅ

  • -msve-vector-bits=bits โ€” sets how many bits live in an SVE vector register. Important: this only does anything when SVE is enabled. ๐Ÿ™ˆ

GCC supports two flavours of SVE code generation: "vector-length agnostic" output, which works with any size of vector register, and "vector-length specific" output, which lets GCC make assumptions about the vector length when that's useful for optimization reasons.

The possible values of bits are: scalable, 128, 256, 512, 1024 and 2048. Specifying scalable selects vector-length agnostic output. At present -msve-vector-bits=128 also generates vector-length agnostic output for big-endian targets. All other values generate vector-length specific code. The behavior of these values may change in future releases, and no value except scalable should be relied on for producing code that is portable across different hardware SVE vector lengths. ๐Ÿ˜ญ

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, plus their inverses nofeature:

  • crc โ€” enable the CRC extension. This is on by default for -march=armv8.1-a. ๐ŸŒธ
  • crypto โ€” enable the 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 the FP16 extension. This also enables floating-point instructions.
  • fp16fml โ€” enable the 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 enables the use of the LDAPR instructions for load-acquire atomic semantics, and passes it 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.
  • bf16 โ€” enable brain half-precision floating-point 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.
  • ls64 โ€” enable the 64-byte atomic load and store instructions for accelerators. This option is enabled by default for -march=armv8.7-a.
  • mops โ€” enable the instructions to accelerate memory operations like "memcpy", "memmove", "memset". This option is enabled by default for -march=armv8.8-a
  • flagm โ€” enable the Flag Manipulation instructions Extension.
  • pauth โ€” enable the Pointer Authentication Extension.
  • cssc โ€” enable the Common Short Sequence Compression instructions.

Okay so the vibe chain here: the feature crypto implies aes, sha2, and simd, which implies fp. And conversely, nofp implies nosimd, which implies nocrypto, noaes and nosha2. It's giving cascade ๐Ÿ’…


๐Ÿฆ‹ Adapteva Epiphany Options ๐Ÿฆ‹

These -m options are defined for Adapteva Epiphany:

  • -mhalf-reg-file โ€” don't allocate any register in the range "r32"โ€ฆ"r63". That lets code run on hardware variants that lack these registers. ๐ŸŒˆ
  • -mprefer-short-insn-regs โ€” preferentially allocate registers that allow short instruction generation. Careful bestie, this can result in increased instruction count, so it may either reduce or increase overall code size. ๐Ÿ˜ญ
  • -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. (ma'am why ๐Ÿ˜ญ)
  • -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. Also note 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 whether 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 an (otherwise direct) call. This is the default. ๐Ÿ‘‘
  • -mshort-calls โ€” unless some attribute says otherwise, just assume every direct call fits inside the range of the b / bl instructions, and use those for direct calls. default? -mlong-calls, bestie. it's giving "long haul." ๐Ÿ’…
  • -msmall16 โ€” assume addresses can be loaded as 16-bit unsigned values. โš ๏ธ this does not apply to function addresses where -mlong-calls semantics are in effect. no cap.
  • -mfp-mode=mode โ€” sets the prevailing mode of the floating-point unit. like, this decides the FP mode that gets provided and expected at function call and return time. if you match this mode to whatever mode you mostly need at function start, your programs get smaller and faster bc you're dodging unnecessary mode switches. slay. โœจ

mode can be set to one of these:

  • caller โ€” any mode at function entry is valid, and it's 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 drop into different programs that have 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 you'd need 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. so likeโ€ฆ heads up.
  • -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. ๐Ÿ˜ญ theory said one thing, reality said another.
  • -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. iconic. ๐Ÿ”ฅ

  • -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).
    • gfx908 โ€” compile for CDNA1 Instinct MI100 series devices (gfx908).
    • gfx90a โ€” compile for CDNA2 Instinct MI200 series devices (gfx90a).
  • -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. ๐Ÿ˜ค 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 only 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 let the user 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. (yes bestie, a placeholder. we're manifesting it. ๐Ÿ™ˆ)

๐Ÿฆ‹ 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.
    • hs4x โ€” compile for ARC HS4x CPU.
    • hs4xd โ€” compile for ARC HS4xD CPU.
    • hs4x_rel31 โ€” compile for ARC HS4x CPU release 3.10a.
    • 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. valid only for -mcpu=ARC700.
  • -mno-mpy โ€” do not generate "mpy"-family instructions for ARC700. โš ๏ธ this option is deprecated.
  • -mmul32x16 โ€” generate 32x16-bit multiply and multiply-accumulate instructions.
  • -mmul64 โ€” generate "mul64" and "mulu64" instructions. valid only for -mcpu=ARC600.
  • -mnorm โ€” generate "norm" instructions. this is the default if -mcpu=ARC700 is in effect.
  • -mspfp
  • -mspfp-compact โ€” generate single-precision FPX instructions, tuned for the compact implementation.
  • -mspfp-fast โ€” generate single-precision FPX instructions, tuned for the fast implementation.
  • -msimd โ€” enable generation of ARC SIMD instructions via target-specific builtins. valid only for -mcpu=ARC700.
  • -msoft-float โ€” ๐Ÿ˜ต this option is ignored; it is provided for compatibility purposes only. software floating-point code is emitted by default, and this default can be overridden by FPX options: -mspfp, -mspfp-compact, or -mspfp-fast for single precision, and -mdpfp, -mdpfp-compact, or -mdpfp-fast for double precision. so like, it's here, but it's not doing anything. ๐Ÿ’€
  • -mswap โ€” generate "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 โ€” enable "div" and "rem" instructions for ARCv2 cores.
  • -mcode-density โ€” enable code density instructions for ARC EM. this option is on by default for ARC HS.
  • -mll64 โ€” enable 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".

okay we're deep in the ARC lore now bestie, and there is so much more coming ๐Ÿ’– stay with me โœจ

  • 5, wlh4 โ€” one 16x16 multiplier, blocking, sequential ๐Ÿงฎ and the following instructions are additionally enabled: mpy, mpyu, mpym, mpymu, and mpy_s.
  • 6, wlh5 โ€” one 32x4 multiplier, blocking, sequential ๐Ÿงฎ and 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. โœจ

Bestie, listen โ€” this option is only available for ARCv2 cores. No ARCv2, no vibes. ๐Ÿ’…


  • -mfpu=fpu โ€” turns on support for specific floating-point hardware extensions for ARCv2 cores ๐Ÿงšโ€โ™€๏ธ the supported values for fpu are giving:
    • 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. 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. 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 โ€” this one spells out the general-purpose registers that the processor automatically saves and restores on interrupt entry and exit ๐Ÿ˜ฎโ€๐Ÿ’จ register-range is written as two registers with a dash between them, no cap. The register range always starts with "r0", and the upper limit is the "fp" register. blink and lp_count are optional (so slay, so optional ๐Ÿ’…). Heads up: this option is only valid for ARC EM and ARC HS cores.
  • -mrgf-banked-regs=number โ€” tells the compiler how many registers get replicated in the second register bank on entry to a fast interrupt โšก Fast interrupts are the ones with the highest priority level P0. These interrupts save only the PC and STATUS32 registers, so they avoid memory transactions during interrupt entry and exit sequences โ€” icon behaviour tbh. Use this option when you're using fast interrupts in an ARC V2 family processor. The permitted values are 4, 8, 16, and 32.
  • -mlpc-width=width โ€” sets 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's known that the "lp_count" register can hold the required loop-counter value. Depending on the width you specify, the compiler and run-time library might keep using the loop mechanism for various needs. Oh and โ€” this option defines macro "__ARC_LPC_WIDTH__" with the value of width โœจ
  • -mrf16 โ€” instructs the compiler to generate code for a 16-entry register file ๐Ÿ—‚๏ธ and it defines the "__ARC_RF16__" preprocessor macro. Periodt.
  • -mbranch-index โ€” enables 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 โ€” explains what alignment considerations led 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, which gives you access to the full 32-bit address range. ๐ŸŒˆ
  • -mmedium-calls โ€” don't use less than a 25-bit addressing range for calls, which is the offset available for an unconditional branch-and-link instruction. Conditional execution of function calls is suppressed, so we can use the 25-bit range instead of 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 โ€” put definitions of externally-visible data in a small data section if that data is no bigger than num bytes ๐Ÿ“ฆ The default value of num is 4 for any ARC configuration, or 8 when we have double load/store operations.
  • -mno-sdata โ€” do not generate sdata references ๐Ÿ™…โ€โ™€๏ธ This is the default for tool chains built for "arc-linux-uclibc" and "arceb-linux-uclibc" targets.
  • -mvolatile-cache โ€” use ordinarily cached memory accesses for volatile references. This is the default.
  • -mno-volatile-cache โ€” enable cache bypass for volatile references.

The following options fine tune code generation: ๐ŸŽ›๏ธ

  • -malign-call โ€” does nothing ๐Ÿซ  preserved for backward compatibility.
  • -mauto-modify-reg โ€” enable the use of pre/post modify with register displacement.
  • -mbbit-peephole โ€” enable bbit peephole2.
  • -mno-brcc โ€” this option 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.
  • -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 that generates conditional execution instructions.
Okay so here's the whole tea, bestie ๐Ÿต 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's 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.
  • -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.
  • -mlra โ€” turns on Local Register Allocation, bestie. It's still experimental for ARC, so by default the compiler just uses standard reload (aka -mno-lra). ๐Ÿงช
  • -mlra-priority-none โ€” don't flag any priority for target registers.
  • -mlra-priority-compact โ€” flag target register priority for r0..r3 / r12..r15.
  • -mlra-priority-noncompact โ€” dial down the target register priority for r0..r3 / r12..r15.
  • -mmillicode โ€” ok so when you're optimizing for size (with -Os), prologues and epilogues that have to save or restore a large number of registers often get shortened by calling a special function in libgcc. That's a millicode call โœจ. But these calls can pose performance issues, and/or cause linking issues when you link in a nonstandard way, so this option exists to turn millicode call generation on or off. ๐ŸŽš๏ธ
  • -mcode-density-frame โ€” lets the compiler emit "enter" and "leave" instructions. Heads up though: those instructions are only valid for CPUs with the code-density feature. ๐Ÿ’…
  • -mcode-density-frame slay, but -mmixed-code? Nope. -mmixed-code โ€” does nothing. Preserved for backward compatibility. ๐Ÿ’€
  • -mq-class โ€” this option is deprecated, friend. It enables q instruction alternatives, and it's the default for -Os. ๐Ÿ™ˆ
  • -mRcq โ€” does nothing. Preserved for backward compatibility.
  • -mRcw โ€” does nothing. Preserved for backward compatibility.
  • -msize-level=level โ€” fine-tune size optimization when it comes to instruction lengths and alignment. The recognized values for level are:
    • 0 โ€” no size optimization. This level is deprecated and gets treated like 1.
    • 1 โ€” short instructions are used opportunistically.
    • 2 โ€” on top of that, alignment of loops and of code after barriers are dropped.
    • 3 โ€” on top of that, optional data alignment is dropped, and the option Os is enabled.

This defaults to 3 when -Os is in effect. Otherwise, if this isn't set, the behavior is equivalent to level 1. ๐ŸŒธ

  • -mtune=cpu โ€” sets instruction scheduling parameters for cpu, overriding anything implied by -mcpu=. Supported values for cpu are:
    • ARC600 โ€” tune for ARC600 CPU.
    • ARC601 โ€” tune for ARC601 CPU.
    • ARC700 โ€” tune for ARC700 CPU with standard multiplier block.
    • ARC700-xmac โ€” tune for ARC700 CPU with XMAC block.
    • ARC725D โ€” tune for ARC725D CPU.
    • ARC750D โ€” tune for ARC750D CPU.
    • core3 โ€” tune for ARCv2 core3 type CPU. This option enables usage of the "dbnz" instruction.
    • release31a โ€” tune for ARC4x release 3.10a.
  • -mmultcost=num โ€” the cost to assume for a multiply instruction, where 4 is equal to a normal instruction.
  • -munalign-prob-threshold=probability โ€” does nothing. Preserved for backward compatibility.

The following options are maintained for backward compatibility, but are now deprecated and will be removed in a future release ๐Ÿ˜ญ:

  • -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.
  • -multcost=num โ€” replaced by -mmultcost.

๐ŸŒˆ ARM Options ๐ŸŒˆ

These -m options are defined for the ARM port, bestie:

  • -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's compliant with the ARM Procedure Call Standard for all functions, even if it's 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. What this gets you: 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 info can be used to locate the start of functions inside an executable piece of code. The default is -msched-prolog.
  • -mfloat-abi=name โ€” specifies which floating-point ABI to use. Permissible values are: soft, softfp and hard.
    • Specifying soft causes GCC to generate output containing library calls for floating-point operations.
    • softfp allows the generation of code using hardware floating-point instructions, but still uses the soft-float calling conventions.
    • hard allows generation of floating-point instructions and uses FPU-specific calling conventions.

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

  • -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.
  • -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...] โ€” specifies the name of the target ARM architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. This option can be used in conjunction with or instead of the -mcpu= option. ๐Ÿ’…

Permissible names are: armv4t, armv5t, armv5te, armv6, armv6j, armv6k, armv6kz, armv6t2, armv6z, armv6zk, armv7, armv7-a, armv7ve, armv8-a, armv8.1-a, armv8.2-a, armv8.3-a, armv8.4-a, armv8.5-a, armv8.6-a, armv9-a, armv7-r, armv8-r, armv6-m, armv6s-m, armv7-m, armv7e-m, armv8-m.base, armv8-m.main, armv8.1-m.main, armv9-a, iwmmxt and iwmmxt2.

Additionally, the following architectures, which lack support for the Thumb execution state, are recognized but support is deprecated: armv4.

Many of the architectures support extensions. These can be added by appending +extension to the architecture name. Extension options are processed in order and capabilities accumulate. An extension will also enable any necessary base extensions upon which it depends. For example, the +crypto extension will always enable the +simd extension. The exception to the additive construction is for extensions that are prefixed with +no...: these extensions disable the specified option and any other extensions that may depend on the presence of that extension. โœจ

For example, -march=armv7-a+simd+nofp+vfpv4 is equivalent to writing -march=armv7-a+vfpv4 since the +simd option is entirely disabled by the +nofp option that follows it.

Most extension names are generically named, but have an effect that is dependent upon the architecture to which it is applied. For example, the +simd option can be applied to both armv7-a and armv8-a architectures, but will enable the original ARMv7-A Advanced SIMD (Neon) extensions for armv7-a and the ARMv8-A variant for armv8-a. ๐Ÿ‘‘

The table below lists the supported extensions for each architecture. Architectures not mentioned do not support any extensions.

armv5te / armv6 / armv6j / armv6k / armv6kz / armv6t2 / armv6z / armv6zk

  • +fp โ€” the VFPv2 floating-point instructions. The extension +vfpv2 can be used as an alias for this extension.
  • +nofp โ€” disable the floating-point instructions.

armv7

The common subset of the ARMv7-A, ARMv7-R and ARMv7-M architectures.

  • +fp โ€” the VFPv3 floating-point instructions, with 16 double-precision registers. The extension +vfpv3-d16 can be used as an alias for this extension. Note that floating-point is not supported by the base ARMv7-M architecture, but is compatible with both the ARMv7-A and ARMv7-R architectures.
  • +nofp โ€” disable the floating-point instructions.

armv7-a

  • +mp โ€” the multiprocessing extension.
  • +sec โ€” the security extension.
  • +fp โ€” the VFPv3 floating-point instructions, with 16 double-precision registers. The extension +vfpv3-d16 can be used as an alias for this extension.
  • +simd โ€” the Advanced SIMD (Neon) v1 plus the VFPv3 floating-point instructions, bestie. and the extensions +neon and +neon-vfpv3 can be used as aliases for this extension ๐Ÿ’ซ
  • +vfpv3 โ€” the VFPv3 floating-point instructions, but with 32 double-precision registers ๐ŸŽ€
  • +vfpv3-d16-fp16 โ€” VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations โœจ
  • +vfpv3-fp16 โ€” 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 โ€” Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, plus the half-precision floating-point conversion operations ๐ŸŒธ
  • +neon-vfpv4 โ€” Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions ๐Ÿ”ฅ
  • +nosimd โ€” turns off the Advanced SIMD instructions. note that it does not disable floating point, okay? ๐Ÿซถ
  • +nofp โ€” turns off both the floating-point and the Advanced SIMD instructions. all the way off ๐Ÿ’€
  • armv7ve โ€” the extended version of the ARMv7-A architecture, and yes it comes 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 one ๐Ÿ’–
    • +simd โ€” Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions. the extension +neon-vfpv4 can be used as an alias for this one โœจ
    • +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 โ€” VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations ๐ŸŒธ
    • +vfpv3-fp16 โ€” 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 โ€” Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. the extension +neon-vfpv3 can be used as an alias for this one ๐Ÿ’œ
    • +neon-fp16 โ€” Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations ๐ŸŒˆ
    • +nosimd โ€” disables the Advanced SIMD instructions (and nope, it does not disable floating point) ๐Ÿ™ˆ
    • +nofp โ€” disables the floating-point and Advanced SIMD instructions ๐Ÿ’€
  • armv8-a โ€” the moment ๐Ÿ‘‘
    • +crc โ€” the Cyclic Redundancy Check (CRC) instructions โญ
    • +simd โ€” the ARMv8-A Advanced SIMD and floating-point instructions โœจ
    • +crypto โ€” the cryptographic instructions ๐Ÿ”
    • +nocrypto โ€” disables the cryptographic instructions ๐Ÿšซ
    • +nofp โ€” disables the floating-point, Advanced SIMD and cryptographic instructions ๐Ÿ’€
    • +sb โ€” Speculation Barrier Instruction ๐Ÿ›ก๏ธ
    • +predres โ€” Execution and Data Prediction Restriction Instructions ๐Ÿงฟ
  • armv8.1-a โ€” glow up edition ๐Ÿ’–
    • +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 โ€” disables the cryptographic instructions ๐Ÿšซ
    • +nofp โ€” disables 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 โ€” these two share the same extension set, so here it is ๐Ÿซถ
    • +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 โ€” enables the Dot Product extension. this also enables Advanced SIMD instructions ๐Ÿ“
    • +nocrypto โ€” disables the cryptographic extension ๐Ÿšซ
    • +nofp โ€” disables 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 โ€” okay she's iconic ๐Ÿ‘‘
    • +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 โ€” disables the cryptographic extension ๐Ÿšซ
    • +nofp โ€” disables 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 โ€” and she keeps the same energy ๐Ÿ”ฅ
    • +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 โ€” disables the cryptographic extension ๐Ÿšซ
    • +nofp โ€” disables the floating-point, Advanced SIMD and cryptographic instructions ๐Ÿ’€
    • +i8mm โ€” 8-bit Integer Matrix Multiply instructions. this also enables Advanced SIMD and floating-point instructions ๐Ÿ”ข
    • +bf16 โ€” Brain half-precision floating-point instructions. this also enables Advanced SIMD and floating-point instructions ๐Ÿง 
  • armv8.6-a โ€” same set again, no cap ๐Ÿ’œ
    • +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 โ€” disables the cryptographic extension ๐Ÿšซ
    • +nofp โ€” disables the floating-point, Advanced SIMD and cryptographic instructions ๐Ÿ’€
    • +i8mm โ€” 8-bit Integer Matrix Multiply instructions. this also enables Advanced SIMD and floating-point instructions ๐Ÿ”ข
    • +bf16 โ€” Brain half-precision floating-point instructions. this also enables Advanced SIMD and floating-point instructions ๐Ÿง 
  • armv7-r โ€” the R stands for Real, we love her ๐ŸŒˆ
    • +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 โ€” disables the floating-point extension ๐Ÿšซ
    • +idiv โ€” the ARM-state integer division instructions โž—
  • +noidiv โ€” Disables the ARM-state integer division extension. ๐Ÿ‘‘
  • armv7e-m ๐Ÿฆ‹
    • +fp โ€” The single-precision VFPv4 floating-point instructions. โœจ
    • +fpv5 โ€” The single-precision FPv5 floating-point instructions. ๐Ÿ’–
    • +fp.dp โ€” The single- and double-precision FPv5 floating-point instructions. ๐ŸŽ€
    • +nofp โ€” Disable the floating-point extensions. ๐Ÿ™ˆ
  • armv8.1-m.main ๐ŸŒธ
    • +dsp โ€” The DSP instructions. ๐ŸŽต
    • +mve โ€” The M-Profile Vector Extension (MVE) integer instructions. ๐Ÿ”ฅ
    • +mve.fp โ€” The M-Profile Vector Extension (MVE) integer and single precision floating-point instructions. ๐Ÿ’…
    • +fp โ€” The single-precision floating-point instructions. โญ
    • +fp.dp โ€” The single- and double-precision floating-point instructions. ๐ŸŒˆ
    • +nofp โ€” Disable the floating-point extension. ๐Ÿ’€
    • +cdecp0, +cdecp1, ... , +cdecp7 โ€” Enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7. ๐Ÿ‘‘
    • +pacbti โ€” Enable the Pointer Authentication and Branch Target Identification Extension. ๐Ÿ›ก๏ธ
  • armv8-m.main ๐Ÿงš
    • +dsp โ€” The DSP instructions. ๐ŸŽถ
    • +nodsp โ€” Disable the DSP extension. ๐Ÿšซ
    • +fp โ€” The single-precision floating-point instructions. โœจ
    • +fp.dp โ€” The single- and double-precision floating-point instructions. ๐Ÿ’–
    • +nofp โ€” Disable the floating-point extension. ๐Ÿ™…
    • +cdecp0, +cdecp1, ... , +cdecp7 โ€” Enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7. ๐Ÿ’…
  • armv8-r ๐ŸŽ€
    • +crc โ€” The Cyclic Redundancy Check (CRC) instructions. ๐Ÿ”„
    • +fp.sp โ€” The single-precision FPv5 floating-point instructions. ๐Ÿ’ซ
    • +simd โ€” The ARMv8-A Advanced SIMD and floating-point instructions. ๐Ÿš€
    • +crypto โ€” The cryptographic instructions. ๐Ÿ”
    • +nocrypto โ€” Disable the cryptographic instructions. ๐Ÿ”“
    • +nofp โ€” Disable the floating-point, Advanced SIMD and cryptographic instructions. ๐Ÿ’ฅ
๐Ÿ’ก -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. ๐ŸŒ
  • -mtune=name โ€” This option specifies the name of the target ARM processor for which GCC should tune the performance of the code. For some ARM implementations better performance can be obtained by using this option. ๐ŸŽฏ

Permissible names are:

arm7tdmi, arm7tdmi-s, arm710t, arm720t, arm740t, strongarm, strongarm110, strongarm1100, strongarm1110, arm8, arm810, arm9, arm9e, arm920, arm920t, arm922t, arm946e-s, arm966e-s, arm968e-s, arm926ej-s, arm940t, arm9tdmi, arm10tdmi, arm1020t, arm1026ej-s, arm10e, arm1020e, arm1022e, arm1136j-s, arm1136jf-s, mpcore, mpcorenovfp, arm1156t2-s, arm1156t2f-s, arm1176jz-s, arm1176jzf-s, generic-armv7-a, cortex-a5, cortex-a7, cortex-a8, cortex-a9, cortex-a12, cortex-a15, cortex-a17, cortex-a32, cortex-a35, cortex-a53, cortex-a55, cortex-a57, cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, cortex-a77, cortex-a78, cortex-a78ae, cortex-a78c, cortex-a710, ares, cortex-r4, cortex-r4f, cortex-r5, cortex-r7, cortex-r8, cortex-r52, cortex-r52plus, cortex-m0, cortex-m0plus, cortex-m1, cortex-m3, cortex-m4, cortex-m7, cortex-m23, cortex-m33, cortex-m35p, cortex-m55, cortex-m85, cortex-x1, cortex-x1c, 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, star-mc1, xgene1.

Additionally, this option can specify that GCC should tune the performance of the code for a big.LITTLE system. Permissible names 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 specified by -march) and the ARM processor type for which to tune for performance (as if specified by -mtune). Where this option is used in conjunction with -march or -mtune, those options take precedence over the appropriate part of this option. ๐ŸŽ›๏ธ

Many of the supported CPUs implement optional architectural extensions. Where this is so the architectural extensions are normally enabled by default. If implementations that lack the extension exist, then the extension syntax can be used to disable those extensions that have been omitted. For floating-point and Advanced SIMD (Neon) instructions, the settings of the options -mfloat-abi and -mfpu must also be considered: floating-point and Advanced SIMD instructions will only be used if -mfloat-abi is not set to soft; and any setting of -mfpu other than auto will override the available floating-point and SIMD extension instructions. ๐Ÿ’ก

For example, cortex-a9 can be found in three major configurations: integer only, with just a floating-point unit or with floating-point and Advanced SIMD. The default is to enable all the instructions, but the extensions +nosimd and +nofp can be used to disable just the SIMD or both the SIMD and floating-point instructions respectively. ๐Ÿง 

Permissible names for this option are the same as those for -mtune. ๐Ÿ“‹

The following extension options are common to the listed CPUs:

  • +nodsp โ€” Disable the DSP instructions on cortex-m33, cortex-m35p, cortex-m55 and cortex-m85. Also disable the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions on cortex-m55 and cortex-m85. ๐Ÿšซ
  • +nopacbti โ€” Disable the Pointer Authentication and Branch Target Identification Extension on cortex-m85. ๐Ÿ›‘
  • +nomve โ€” Disable the M-Profile Vector Extension (MVE) integer and single precision floating-point instructions on cortex-m55 and cortex-m85. โŒ
  • +nomve.fp โ€” Disable the M-Profile Vector Extension (MVE) single precision floating-point instructions on cortex-m55 and cortex-m85. ๐Ÿšซ
  • +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 on cortex-m55. โœ…
  • +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, cortex-m35p cortex-m4, cortex-m7, cortex-m33, cortex-m35p, cortex-m55 and cortex-m85. Disables the floating-point and SIMD instructions on generic-armv7-a, cortex-a5, cortex-a7, cortex-a8, cortex-a9, cortex-a12, cortex-a15, cortex-a17, cortex-a15.cortex-a7, cortex-a17.cortex-a7, cortex-a32, cortex-a35, cortex-a53 and cortex-a55. ๐Ÿšซ
  • +nofp.dp โ€” Disables the double-precision component of the floating-point instructions on cortex-r5, cortex-r7, cortex-r8, cortex-r52, cortex-r52plus and cortex-m7. โŒ
  • +nosimd โ€” Disables the SIMD (but not floating-point) instructions on generic-armv7-a, cortex-a5, cortex-a7 and cortex-a9. ๐Ÿšซ
  • +crypto โ€” Enables the cryptographic instructions on cortex-a32, cortex-a35, cortex-a53, cortex-a55, cortex-a57, cortex-a72, cortex-a73, cortex-a75, exynos-m1, xgene1, cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a73.cortex-a35, cortex-a73.cortex-a53 and cortex-a75.cortex-a55. ๐Ÿ”

Additionally the generic-armv7-a pseudo target defaults to VFPv3 with 16 double-precision registers. It supports the following extension options: mp, sec, vfpv3-d16, vfpv3, vfpv3-d16-fp16, vfpv3-fp16, vfpv4-d16, vfpv4, neon, neon-vfpv3, neon-fp16, neon-vfpv4. The meanings are the same as for the extensions to -march=armv7-a. ๐ŸŽฏ

-mcpu=generic-arch is also permissible, and is equivalent to -march=arch -mtune=generic-arch. See -mtune for more information. โ„น๏ธ

-mcpu=native causes the compiler to auto-detect the CPU of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect. ๐Ÿ’ป

  • -mfpu=name โ€” This specifies what floating-point hardware (or hardware emulation) is available on the target. Permissible names are: auto, vfpv2, vfpv3, vfpv3-fp16, vfpv3-d16, vfpv3-d16-fp16, vfpv3xd, vfpv3xd-fp16, neon-vfpv3, neon-fp16, vfpv4, vfpv4-d16, fpv4-sp-d16, neon-vfpv4, fpv5-d16, fpv5-sp-d16, fp-armv8, neon-fp-armv8 and crypto-neon-fp-armv8. Note that neon is an alias for neon-vfpv3 and vfp is an alias for vfpv2. ๐Ÿ’…

The setting auto is the default and is special. It causes the compiler to select the floating-point and Advanced SIMD instructions based on the settings of -mcpu and -march. ๐Ÿค–

Okay bestie, we're still deep in the ARM options and honestly this section is giving โœจ ARM lore dump โœจ โ€” but it's all important, so buckle up ๐Ÿ’–

If the selected floating-point hardware includes the NEON extension (like, say, -mfpu=neon), heads up: 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 โ€” specifically, denormal values get treated as zero โ€” so using NEON instructions may lead to a loss of precision. ๐Ÿ˜ฌ

You can also set the fpu name at function level by using the target("fpu=") function attributes or pragmas. ๐ŸŽ€

  • -mfp16-format=name โ€” specify the format of the __fp16 half-precision floating-point type. Permissible names are none, ieee, and alternative; the default is none, in which case the __fp16 type is not defined at all. ๐Ÿ™ˆ
  • -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. ๐Ÿซ 

This option is deprecated. She's retired, bestie.
  • -mabort-on-noreturn โ€” generate a call to the function abort at the end of a noreturn function. It is executed if the function tries to return. (Snitch behaviour, honestly ๐Ÿ’€)
  • -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. ๐Ÿ‘‘

This feature is not enabled by default. Specifying -mno-long-calls restores the default behavior, as does placing the function calls within the scope of a #pragma long_calls_off directive. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers. ๐Ÿฆ‹

  • -msingle-pic-base โ€” treat the register used for PIC addressing as read-only, rather than loading it in the prologue for each function. The runtime system is responsible for initializing this register with an appropriate value before execution begins. (So like, runtime's problem now ๐Ÿ’…)
  • -mpic-register=reg โ€” specify the register to be used for PIC addressing. For standard PIC base case, the default is any suitable register determined by compiler. For single PIC base case, the default is R9 if target is EABI based or stack-checking is enabled, otherwise the default is R10.
  • -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. โœจ
  • -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). ๐Ÿ”

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

  • -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. (Test-only behaviour, she's not for the general public ๐Ÿ’€)
  • -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. ๐Ÿ“
  • -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. ๐Ÿ“
  • -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. ๐Ÿšซ
  • -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. ๐Ÿšซ
  • -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. โœจ
  • -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. ๐Ÿ’–
  • -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. โš”๏ธ
  • -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. ๐Ÿ˜ญ
  • -mfix-cortex-a57-aes-1742098, -mno-fix-cortex-a57-aes-1742098, -mfix-cortex-a72-aes-1655431, -mno-fix-cortex-a72-aes-1655431 โ€” enable (disable) mitigation for an erratum on Cortex-A57 and Cortex-A72 that affects the AES cryptographic instructions. This option is enabled by default when either -mcpu=cortex-a57 or -mcpu=cortex-a72 is specified. ๐Ÿ› ๏ธ
  • -munaligned-access, -mno-unaligned-access โ€” enables (or disables) reading and writing of 16- and 32- bit values from addresses that 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. ๐Ÿข

The ARM attribute Tag_CPU_unaligned_access is set in the generated object file to either true or false, depending upon the setting of this option. If unaligned access is enabled then the preprocessor symbol __ARM_FEATURE_UNALIGNED is also defined. โœจ

  • -mneon-for-64bits โ€” this option is deprecated and has no effect. (She's literally just vibing in the manpage, doing nothing ๐Ÿ’€)
  • -mslow-flash-data โ€” assume loading data from flash is slower than fetching instruction. Therefore literal load is minimized for better performance. This option is only supported when compiling for ARMv7 M-profile and off by default. It conflicts with -mword-relocations. โš”๏ธ
  • -masm-syntax-unified โ€” assume inline assembler is using unified asm syntax. The default is currently off which implies divided syntax. This option has no impact on Thumb2. However, this may change in future releases of GCC. Divided syntax should be considered deprecated. ๐Ÿ‘€
  • -mrestrict-it โ€” restricts generation of IT blocks to conform to the rules of ARMv8-A. IT blocks can only contain a single 16-bit instruction from a select set of instructions. This option is on by default for ARMv8-A Thumb mode. ๐Ÿ’…
  • -mprint-tune-info โ€” print CPU tuning information as comment in assembler file. This is an option used only for regression testing of the compiler and not intended for ordinary use in compiling code. This option is disabled by default. ๐Ÿ”ฅ
  • -mverbose-cost-dump โ€” okay so this one makes the compiler dump its whole cost model, verbose mode, into the debug dump files ๐Ÿ“Š it's provided for use in debugging the compiler, so it's strictly for the compiler-dev girlies. If that's not you, you truly do not need it, bestie.
  • -mpure-code โ€” constant data does not get to sit in code sections, no ma'am ๐Ÿ’… and on top of that, when you're compiling for ELF object format, every text section gets the ELF processor-specific section attribute SHF_ARM_PURECODE attached to it. She's specialized though: this option is only available when generating non-pic code for M-profile targets. ๐ŸŽ€
  • -mcmse โ€” generates secure code exactly as per the "ARMv8-M Security Extensions: Requirements on Development Tools Engineering Specification" ๐Ÿ“œ which lives at https://developer.arm.com/documentation/ecm0359818/latest/.
  • -mfix-cmse-cve-2021-35465 โ€” patches up a potential security issue with the VLLDM instruction in some M-profile devices when you're using CMSE (CVE-2021-365465) ๐Ÿ˜ญ security girlies stay winning fr fr. It's enabled by default when the option -mcpu= is used with cortex-m33, cortex-m35p, cortex-m55, cortex-m85 or star-mc1. And if you wanna rawdog it, -mno-fix-cmse-cve-2021-35465 disables the mitigation. ๐Ÿ™ˆ
  • -mstack-protector-guard=guard, -mstack-protector-guard-offset=offset โ€” generates stack protection code with the canary sitting at guard ๐Ÿค the supported locations are global for a global canary, or tls for a canary you reach through the TLS register. Now listen carefully: -mstack-protector-guard-offset= is for use with -fstack-protector-guard=tls and not for use in user-land code. periodt. ๐Ÿ‘‘
  • -mfdpic, -mno-fdpic โ€” selects the FDPIC ABI, which uses 64-bit function descriptors to represent pointers to functions โœจ when the compiler is configured for arm-*-uclinuxfdpiceabi targets, this option is on by default and implies -fPIE if none of the PIC/PIE-related options is provided. On other targets, it only enables the FDPIC-specific code generation features, and you should explicitly provide the PIC/PIE-related options as needed.

Heads up bestie: static linking is not supported, because it would still involve the dynamic linker when the program self-relocates ๐Ÿ’€ if that behavior is acceptable, use -static and -Wl,-dynamic-linker options.

The opposite -mno-fdpic option is useful (and required) to build the Linux kernel using the same (arm-*-uclinuxfdpiceabi) toolchain as the one used to build the userland programs.

  • -mbranch-protection=none|standard|pac-ret[+leaf][+bti]|bti[+pac-ret[+leaf]] โ€” turns on branch protection features (armv8.1-m.main only, so check yourself before you wreck yourself ๐Ÿ‘€). The flavors go like this:
    • none โ€” generates code without branch protection or return address signing. literally nothing, no vibes.
    • standard[+leaf] โ€” generates code with all branch protection features enabled at their standard level.
    • pac-ret[+leaf] โ€” generates code with return address signing set to its standard level, which is to sign all functions that save the return address to memory.
    • leaf โ€” when return address signing is enabled, also sign leaf functions even if they do not write the return address to memory. ๐Ÿƒ
    • +bti โ€” add landing-pad instructions at the permitted targets of indirect branch instructions. ๐Ÿ›ฌ

If the +pacbti architecture extension is not enabled, then all branch protection and return address signing operations are constrained to use only the instructions defined in the architectural-NOP space. The generated code will remain backwards-compatible with earlier versions of the architecture, but the additional security can be enabled at run time on processors that support the PACBTI extension. ๐Ÿงš

Branch target enforcement using BTI can only be enabled at runtime if all code in the application has been compiled with at least -mbranch-protection=bti. every last bit of it, no skipping.

Any setting other than none is supported only on armv8-m.main or later.

The default is to generate code without branch protection or return address signing. (iconic, unbothered, moisturized ๐ŸŒธ)


๐ŸŒˆ AVR Options ๐ŸŒˆ

These options are defined for AVR implementations, so if you're out here programming microcontrollers, this section is your main character era:

  • -mmcu=mcu โ€” specify the AVR instruction set architecture (ISA) or device type. The default for this option is avr2.

Quick note before we dive in ๐Ÿ“ a complete device support consists of startup code crtmcu.o, a device header avr/io*.h, a device library libmcu.a and a device-specs file specs-mcu (see https://gcc.gnu.org/wiki/avr-gcc#spec-files). Only the latter is provided by the compiler, according to the supported mcus below. The rest is supported by AVR-LibC (https://www.nongnu.org/avr-libc/), or by means of atpack files from the hardware manufacturer (https://gcc.gnu.org/wiki/avr-gcc#atpack).

The following AVR devices and ISAs are supported ๐Ÿซถ:

  • 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, ata5795, 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, atmega324pb, atmega325, atmega325a, atmega325p, atmega325pa, atmega328, atmega328p, atmega328pb, atmega329, atmega329a, atmega329p, atmega329pa, atmega3250, atmega3250a, atmega3250p, atmega3250pa, atmega3290, atmega3290a, atmega3290p, atmega3290pa, atmega406, atmega64, atmega64a, atmega64c1, atmega64hve, atmega64hve2, atmega64m1, atmega64rfr2, atmega640, atmega644, atmega644a, atmega644p, atmega644pa, atmega644rfr2, atmega645, atmega645a, atmega645p, atmega649, atmega649a, atmega649p, atmega6450, atmega6450a, atmega6450p, atmega6490, atmega6490a, atmega6490p, ata5790, ata5790n, ata5791, ata6613c, ata6614q, ata5782, ata5831, ata8210, ata8510, ata5787, ata5835, ata5700m322, ata5702m322, at90pwm161, at90pwm216, at90pwm316, at90can32, at90can64, at90scr100, at90usb646, at90usb647, at94k, m3000. (yes bestie, that's the whole roster, I counted ๐Ÿ’…)
  • 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, avr64da28, avr64da28s, avr64da32, avr64da32s, avr64da48, avr64da48s, avr64da64, avr64da64s, avr64db28, avr64db32, avr64db48, avr64db64, avr64dd14, avr64dd20, avr64dd28, avr64dd32, avr64du28, avr64du32, avr64ea28, avr64ea32, avr64ea48, avr64sd28, avr64sd32, avr64sd48.
  • avrxmega3 โ€” okay this one is a whole vibe ๐Ÿ’… "XMEGA" devices with up to 64 KiB of combined program memory and RAM, and with program memory visible in the RAM address space. The mcu = list here is absolutely enormous, buckle up bestie: "attiny202", "attiny204", "attiny212", "attiny214", "attiny402", "attiny404", "attiny406", "attiny412", "attiny414", "attiny416", "attiny416auto", "attiny417", "attiny424", "attiny426", "attiny427", "attiny804", "attiny806", "attiny807", "attiny814", "attiny816", "attiny817", "attiny824", "attiny826", "attiny827", "attiny1604", "attiny1606", "attiny1607", "attiny1614", "attiny1616", "attiny1617", "attiny1624", "attiny1626", "attiny1627", "attiny3214", "attiny3216", "attiny3217", "attiny3224", "attiny3226", "attiny3227", "atmega808", "atmega809", "atmega1608", "atmega1609", "atmega3208", "atmega3209", "atmega4808", "atmega4809", "avr16dd14", "avr16dd20", "avr16dd28", "avr16dd32", "avr16du14", "avr16du20", "avr16du28", "avr16du32", "avr16ea28", "avr16ea32", "avr16ea48", "avr16eb14", "avr16eb20", "avr16eb28", "avr16eb32", "avr16la14", "avr16la20", "avr16la28", "avr16la32", "avr32da28", "avr32da28s", "avr32da32", "avr32da32s", "avr32da48", "avr32da48s", "avr32db28", "avr32db32", "avr32db48", "avr32dd14", "avr32dd20", "avr32dd28", "avr32dd32", "avr32du14", "avr32du20", "avr32du28", "avr32du32", "avr32ea28", "avr32ea32", "avr32ea48", "avr32eb14", "avr32eb20", "avr32eb28", "avr32eb32", "avr32la14", "avr32la20", "avr32la28", "avr32la32", "avr32sd20", "avr32sd28", "avr32sd32". likeโ€ฆ that's the whole roster, we ate โœจ
    • 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", "avr128da28", "avr128da28s", "avr128da32", "avr128da32s", "avr128da48", "avr128da48s", "avr128da64", "avr128da64s", "avr128db28", "avr128db32", "avr128db48", "avr128db64".
    • 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". tiny list, big power ๐Ÿซถ
    • 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", "attiny102", "attiny104", "attiny20", "attiny40". smol but mighty ๐Ÿ“
    • avr1 โ€” This ISA is implemented by the minimal AVR core and supported for assembler only. mcu = "attiny11", "attiny12", "attiny15", "attiny28", "at90s1200".

Now the option tea โ˜•๏ธ back at the top level:

  • -mabsdata โ€” Assume that all data in static storage can be accessed by LDS / STS instructions. Heads up bestie, 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 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 that 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.

  • -mbranch-cost=cost โ€” Set the branch costs for conditional branch instructions to cost. Reasonable values for cost are small, non-negative integers. The default branch cost is 0.
  • -mcall-prologues โ€” Function prologues/epilogues are expanded as calls to appropriate subroutines. Code size is smaller. slay ๐Ÿ’…
  • -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, @pxref{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.
  • -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.

  • -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. iykyk ๐Ÿ˜Œ

  • -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. she's looking out for you fr fr ๐Ÿซถ

๐Ÿ”ฅ "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 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. ๐Ÿ’€ not the silent abort bestie
  • 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. Ngl, startup code is a whole collab between libgcc and AVR-LibC, so if you wanna know what AVR-LibC does to EIND, go read the AVR-LibC user manual (https://www.nongnu.org/avr-libc/user-manual/). ๐Ÿ’…
  • It is legit for your own user-specific startup code to set up EIND early โ€” like, super early โ€” for example with init code chilling in section .init3. That code runs before the general startup code that inits RAM and calls constructors, but after the lil bit of AVR-LibC startup code that sets EIND to the segment where the vector table lives. ๐Ÿซถ
#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. periodt.

  • Stubs get generated automatically by the linker if and only if these two conditions are met:
    • The address of a label is taken by means of the gs modifier (short for generate stubs, iykyk) 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 those gs modifiers for code labels in these situations, bestie:
    • 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. And if you do not want such dispatch tables, you can pass the -fno-jump-tables command-line option. no cap.
    • C and C++ constructors/destructors called during startup/shutdown.
    • If the tools hit a gs() modifier explained above.
  • Jumping to non-symbolic addresses like this is not supported, so don't even try it:
int main (void)
{
    /* Call function at word address 0x2 */
    return ((int(*)(void)) 0x2)();
}

Instead, a stub has to be set up โ€” meaning 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 then the application gets linked with -Wl,--defsym,func_4=0x4. Alternatively, func_4 can be defined in the linker script. two paths, same slay. โœจ


๐Ÿ’– Handling of the RAMPD, RAMPX, RAMPY and RAMPZ Special Function Registers ๐Ÿ’–

Some AVR devices support memories bigger than the 64 KiB range that 16-bit pointers can reach. To access memory outside that 64 KiB range, the content of a RAMP register is used as the high part of the address: the X, Y, Z address register gets concatenated with the RAMPX, RAMPY, RAMPZ special function register, respectively, to get a wide address. Similarly, RAMPD is used together with direct addressing. it's giving address glow-up ๐ŸŒˆ

  • The startup code initializes the RAMP special function registers with zero.
  • If an 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. like, mandatory mandatory. ๐Ÿ˜ญ

๐ŸŒธ AVR Built-in Macros ๐ŸŒธ

GCC defines several built-in macros so your 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.
  • __AVR_HAVE_ADIW__ โ€” The device has the ADIW and SBIW instructions.
  • __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_LPMX__ โ€” The device has the LPM Rn,Z and LPM Rn,Z+ instructions.
  • __AVR_HAVE_MOVW__ โ€” The device has the MOVW instruction to perform 16-bit register-register moves.
  • __AVR_HAVE_MUL__ โ€” The device has a hardware multiplier. ๐Ÿ”ฅ
  • __AVR_HAVE_JMP_CALL__ โ€” The device has the JMP and CALL instructions. This is the case for devices with more than 8 KiB of program memory.
  • __AVR_HAVE_EIJMP_EICALL__, __AVR_3_BYTE_PC__ โ€” The device has the EIJMP and EICALL instructions. This is the case for devices with more than 128 KiB of program memory. This also means 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_*. iconic, honestly. ๐Ÿ‘‘
  • __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). ๐Ÿฆ‹

๐ŸŽ€ AVR Internal Options ๐ŸŽ€

The following options are used internally by the compiler and to communicate between device specs files and the compiler proper. You don't need to set these options by hand, in particular they are not optimization options. Using these options in the wrong way may lead to sub-optimal or wrong code. They are documented for completeness, and in order to get a better understanding of device specs (https://gcc.gnu.org/wiki/avr-gcc#spec-files) files.

bestie these are internals okay ๐Ÿ˜ญ you are NOT supposed to be hand-setting them, they're literally the compiler talking to itself. They are not optimization options. Do them wrong and you get sub-optimal or straight-up wrong code ๐Ÿ’€ they're here for completeness and so you can actually understand device specs files. iykyk.
  • -mn-flash=num โ€” Assume that the flash memory has a size of num times 64 KiB. This determines which __flashN address spaces are available.
  • -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 for multilib generation and selection for the devices from architecture avrxmega3.
  • -mskip-bug โ€” Generate code without skips (CPSE, SBRS, SBRC, SBIS, SBIC) over 32-bit instructions.
  • -msp8 โ€” Treat the stack pointer register as an 8-bit register, i.e. assume the high byte of the stack pointer is zero. This option is used by the compiler to select and build multilibs for architectures avr2 and avr25. These architectures mix devices with and without SPH.

๐Ÿฆ‹ 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. that's the whole vibe.
  • -msim โ€” Specifies that the program will be run on the simulator. This causes the simulator BSP provided by libgloss to be linked in. This option has effect only for bfin-elf toolchain. Certain other options, such as -mid-shared-library and -mfdpic, imply -msim.
  • -momit-leaf-frame-pointer โ€” Don't keep the frame pointer in a register for leaf functions. This avoids the instructions to save, set up and restore frame pointers and makes an extra register available in leaf functions.
  • -mspecld-anomaly โ€” When enabled, the compiler ensures that the generated code does not contain speculative loads after jump instructions. If this option is used, __WORKAROUND_SPECULATIVE_LOADS is defined.
  • -mno-specld-anomaly โ€” Don't generate extra code to prevent speculative loads from occurring.
  • -mcsync-anomaly โ€” When enabled, the compiler ensures that the generated code does not contain CSYNC or SSYNC instructions too soon after conditional branches. If this option is used, __WORKAROUND_SPECULATIVE_SYNCS is defined.
  • -mno-csync-anomaly โ€” Don't generate extra code to prevent CSYNC or SSYNC instructions from occurring too soon after a conditional branch.
  • -mlow64k โ€” When enabled, the compiler is free to take advantage of the knowledge that the entire program fits into the low 64k of memory.
  • -mno-low64k โ€” Assume that the program is arbitrarily large. This is the default.
  • -mstack-check-l1 โ€” Do stack checking using information placed into L1 scratchpad memory by the uClinux kernel.
  • -mid-shared-library โ€” Generate code that supports shared libraries via the library ID method. This allows for execute in place and shared libraries in an environment without virtual memory management. This option implies -fPIC. With a bfin-elf target, this option implies -msim.
  • -mno-id-shared-library โ€” Generate code that doesn't assume ID-based shared libraries are being used. This is the default.
  • -mleaf-id-shared-library โ€” Generate code that supports shared libraries via the library ID method, but assumes that this library or executable won't link against any other ID shared libraries. That allows the compiler to use faster code for jumps and calls.
  • -mno-leaf-id-shared-library โ€” Do not assume that the code being compiled won't link against any ID shared libraries. Slower code is generated for jump and call insns.
  • -mshared-library-id=n โ€” Specifies the identification number of the ID-based shared library being compiled. Specifying a value of 0 generates more compact code; specifying other values forces the allocation of that number to the current library but is no more space- or time-efficient than omitting this option.
  • -msep-data โ€” Generate code that allows the data segment to be located in a different area of memory from the text segment. This allows for execute in place in an environment without virtual memory management by eliminating relocations against the text section.
  • -mno-sep-data โ€” Generate code that assumes that the data segment follows the text segment. This is the default.
  • -mlong-calls, -mno-long-calls โ€” Tells the compiler to perform function calls by first loading the address of the function into a register and then performing a subroutine call on this register. This switch is needed if the target function lies outside of the 24-bit addressing range of the offset-based version of subroutine call instruction.

This feature is not enabled by default. Specifying -mno-long-calls restores the default behavior. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers.

  • -mfast-fp โ€” Link with the fast floating-point library. This library relaxes some of the IEEE floating-point standard's rules for checking inputs against Not-a-Number (NAN), in the interest of performance.
  • -minline-plt โ€” Enable inlining of PLT entries in function calls to functions that are not known to bind locally. It has no effect without -mfdpic.
  • -mmulticore โ€” Build a standalone application for multicore Blackfin processors. This option causes proper start files and link scripts supporting multicore to be used, and defines the macro __BFIN_MULTICORE. It can only be used with -mcpu=bf561[-sirevision].

This option can be used with -mcorea or -mcoreb, which selects the one-application-per-core programming model. Without -mcorea or -mcoreb, the single-application/dual-core programming model is used. In this model, the main function of Core B should be named as coreb_main.

If this option is not used, the single-core application programming model is used.

  • -mcorea โ€” Build a standalone application for Core A of BF561 when using the one-application-per-core programming model. Proper start files and link scripts are used to support Core A, and the macro __BFIN_COREA is defined. This option can only be used in conjunction with -mmulticore.
  • -mcoreb โ€” Build a standalone application for Core B of BF561 when using the one-application-per-core programming model. Proper start files and link scripts are used to support Core B, and the macro __BFIN_COREB is defined. When this option is used, coreb_main should be used instead of main. This option can only be used in conjunction with -mmulticore.
  • -msdram โ€” Build a standalone application for SDRAM. Proper start files and link scripts are used to put the application into SDRAM, and the macro __BFIN_SDRAM is defined. The loader should initialize SDRAM before loading the application.
  • -micplb โ€” Assume 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.
  • -mbig-endian โ€” Generate code for a big-endian target.
  • -mlittle-endian โ€” Generate code for a little-endian target. This is the default.
  • -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.
  • -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.
  • -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.

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

okay that's all for this lil chunk, more coming, stay tuned bestie ๐Ÿ’–

  • -mtune=architecture-type โ€” okay so this one tunes everything applicable about the code it spits out to architecture-type, except the ABI and the set of available instructions ๐Ÿ’…. The choices for architecture-type? Same as for -march=architecture-type, no cap ๐Ÿซถ
  • -mmax-stack-frame=n โ€” warns you when a function's stack frame goes over n bytes. like a lil vibe check on your stack frame ๐Ÿ“
  • -metrax4, -metrax100 โ€” bestie these are just synonyms โœจ -metrax4 means -march=v3 and -metrax100 means -march=v8, that's the whole thing.
  • -mmul-bug-workaround, -mno-mul-bug-workaround โ€” works around a bug in the muls and mulu instructions for the CPU models where it actually applies. It is disabled by default, so if you need it you gotta ask for it ๐Ÿ™ˆ
  • -mpdebug โ€” turns on CRIS-specific verbose, debug-related info in the assembly code ๐Ÿ‘‘. Bonus effect: it also turns off the #NO_APP formatted-code indicator to the assembler at the beginning of the assembly file.
  • -mcc-init โ€” do not use condition-code results from a previous instruction. Always emit compare and test instructions before you use condition codes. fresh start energy, 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 (and their no- twins) arrange โ€” or eliminate the arrangements โ€” for the stack frame, individual data and constants to be aligned for the maximum single data access size of the chosen CPU model. The default is to arrange for 32-bit alignment. Important: ABI details like structure layout are not affected by these, bestie ๐ŸŽ€
  • -m32-bit, -m16-bit, -m8-bit โ€” similar vibe to the stack-, data- and const-align options above, but these arrange for the stack frame, writable data and constants to all be 32-bit, 16-bit or 8-bit aligned. Default is 32-bit alignment โญ
  • -mno-prologue-epilogue, -mprologue-epilogue โ€” with -mno-prologue-epilogue, the normal function prologue and epilogue that set up the stack frame are omitted, and no return instructions or return sequences get 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. like it will just. not tell you. ๐Ÿ’€
  • -melf โ€” legacy no-op option. iconic in its uselessness tbh ๐Ÿฆ‹
  • -sim โ€” arranges to link with input-output functions from a simulator library. Code, initialized data and zero-initialized data are all allocated consecutively ๐ŸŒธ
  • -sim2 โ€” like -sim, but it passes linker options to locate initialized data at 0x40000000 and zero-initialized data at 0x80000000 ๐Ÿ“

C-SKY Options ๐Ÿงš

GCC supports these options when compiling for C-SKY V2 processors โœจ

  • -march=arch โ€” specifies the C-SKY target architecture. The valid values for arch are: ck801, ck802, ck803, ck807, and ck810. The default is ck810 ๐Ÿ‘‘
  • -mcpu=cpu โ€” specifies the C-SKY target processor. The valid values for cpu are: ck801, ck801t, ck802, ck802t, ck802j, ck803, ck803h, ck803t, ck803ht, ck803f, ck803fh, ck803e, ck803eh, ck803et, ck803eht, ck803ef, ck803efh, ck803ft, ck803eft, ck803efht, ck803r1, ck803hr1, ck803tr1, ck803htr1, ck803fr1, ck803fhr1, ck803er1, ck803ehr1, ck803etr1, ck803ehtr1, ck803efr1, ck803efhr1, ck803ftr1, ck803eftr1, ck803efhtr1, ck803s, ck803st, ck803se, ck803sf, ck803sef, ck803seft, ck807e, ck807ef, ck807, ck807f, ck810e, ck810et, ck810ef, ck810eft, ck810, ck810v, ck810f, ck810t, ck810fv, ck810tv, ck810ft, and ck810ftv. yes that is a lot of them. the list ate, fr fr ๐Ÿ”ฅ
  • -mbig-endian, -EB, -mlittle-endian, -EL โ€” select big- or little-endian code. The default is little-endian ๐Ÿ’ซ (and yes, -EB and -EL are the short lil nicknames for those).
  • -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. And bestie, listen: 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 โ€” select the floating-point processor. This option can only be used with -mhard-float (so don't try it solo, it won't work ๐Ÿ’…). The values for fpu are:
    • fpv2_sf, which is equivalent to -mno-double-float -mno-fdivdu
    • fpv2, which is -mdouble-float -mno-divdu
    • fpv2_divd, which is -mdouble-float -mdivdu
  • -melrw, -mno-elrw โ€” enable the extended lrw instruction. This option defaults to on for CK801 and off otherwise ๐ŸŽš๏ธ
  • -mistack, -mno-istack โ€” enable interrupt stack instructions; the default is off. Heads up: the -mistack option is required to handle the interrupt and isr function attributes โšก
  • -mmp โ€” enable multiprocessor instructions; the default is off ๐Ÿงฉ
  • -mcp โ€” enable coprocessor instructions; the default is off ๐Ÿ”ง
  • -mcache โ€” enable coprocessor instructions; the default is off (yes, the original says coprocessor here too โ€” iconic copy energy, keeping it exactly as it is ๐ŸŽ€)
  • -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 is 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.
Using this option 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 in compatible with 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 ๐Ÿ“‚

Like, a framework directory is just a directory that has frameworks in it, bestie ๐Ÿ’– A framework is a directory with a Headers and/or PrivateHeaders directory sitting directly inside it that ends in .framework. The name of the framework is the name of that directory minus the .framework. The headers that belong to the framework live in one of those two directories, and Headers gets searched first. โœจ

A subframework is a framework directory that lives inside a framework's Frameworks directory. Includes of subframework headers can only show up 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 โ€” if you break that rule you get a warning. And currently a subframework cannot have subframeworks; in the future the mechanism may be extended to support this. The standard frameworks live in /System/Library/Frameworks and /Library/Frameworks. An example include looks like "#include <Framework/header.h>", where Framework denotes the name of the framework and header.h is found in the PrivateHeaders or Headers directory. ๐ŸŽ€

  • -iframework dir โ€” Like -F except the directory is treated as a system directory. The main difference between -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. all of them. every single one. ๐Ÿ‘‘
  • -fconstant-cfstrings โ€” This one is literally just 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. ๐Ÿ’€
  • -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 โ€” Causes the output file to be marked such that the dynamic linker will bind all undefined references when the file is loaded or launched.
  • -bundle โ€” Produce a Mach-o bundle format file. See man ld(1) for more information.
  • -bundle_loader executable โ€” This option specifies the executable that will load the build output file being linked. See man ld(1) for more information.
  • -dynamiclib โ€” When passed this option, GCC produces a dynamic library instead of an executable when linking, using the Darwin libtool command.
  • -force_cpusubtype_ALL โ€” This causes GCC's output file to have the ALL subtype, instead of one controlled by the -mcpu or -march option.

And here comes the big ol' guest list ๐Ÿ‘‘ all of these get passed to the Darwin linker, and the Darwin linker man page describes them in detail:

  • -allowable_client client_name
  • -client_name
  • -compatibility_version
  • -current_version
  • -dead_strip
  • -dependency-file
  • -dylib_file
  • -dylinker_install_name
  • -dynamic
  • -exported_symbols_list
  • -filelist
  • -flat_namespace
  • -force_flat_namespace
  • -headerpad_max_install_names
  • -image_base
  • -init
  • -install_name
  • -keep_private_externs
  • -multi_module
  • -multiply_defined
  • -multiply_defined_unused
  • -noall_load
  • -no_dead_strip_inits_and_terms
  • -nofixprebinding
  • -nomultidefs
  • -noprebind
  • -noseglinkedit
  • -pagezero_size
  • -prebind
  • -prebind_all_twolevel_modules
  • -private_bundle
  • -read_only_relocs
  • -sectalign
  • -sectobjectsymbols
  • -whyload
  • -seg1addr
  • -sectcreate
  • -sectobjectsymbols
  • -sectorder
  • -segaddr
  • -segs_read_only_addr
  • -segs_read_write_addr
  • -seg_addr_table
  • -seg_addr_table_filename
  • -seglinkedit
  • -segprot
  • -segs_read_only_addr
  • -segs_read_write_addr
  • -single_module
  • -static
  • -sub_library
  • -sub_umbrella
  • -twolevel_namespace
  • -umbrella
  • -undefined
  • -unexported_symbols_list
  • -weak_reference_mismatches
  • -whatsloaded

(yes bestie, some of them are listed twice in the original, no I'm not fixing that, that's just how it ate ๐Ÿ’…)


๐Ÿงš DEC Alpha Options ๐Ÿงš

These -m options are defined for the DEC Alpha implementations:

  • -mno-soft-float, -msoft-float โ€” Use (do not use) the hardware floating-point instructions for floating-point operations. When -msoft-float is specified, functions in libgcc.a are used to perform floating-point operations. Unless they are replaced by routines that emulate the floating-point operations, or compiled in such a way as to call such emulation routines, these routines issue floating-point operations. If you are compiling for an Alpha without floating-point operations, you must ensure that the library is built so as not to call them.

Note that Alpha implementations without floating-point operations are required to have floating-point registers. ๐Ÿ™ˆ

  • -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 is not used, floating-point operands are passed in integer registers as if they were integers and floating-point results are passed in $0 instead of $f0. This is a non-standard calling sequence, so any function with a floating-point argument or return value called by code compiled with -mno-fp-regs must also be compiled with that option. โš ๏ธ

A typical use of this option is building a kernel that does not use, and hence need not save and restore, any floating-point registers. ๐Ÿงš

  • -mieee โ€” The Alpha architecture implements floating-point hardware optimized for maximum performance. It is mostly compliant with the IEEE floating-point standard. However, for full compliance, software assistance is required. This option generates code fully IEEE-compliant code except that the inexact-flag is not maintained (see below). If this option is turned on, the preprocessor macro "_IEEE_FP" is defined during compilation. The resulting code is less efficient but is able to correctly support denormalized numbers and exceptional IEEE values such as not-a-number and plus/minus infinity. Other Alpha compilers call this option -ieee_with_no_inexact.

DEBIAN SPECIFIC:</> This option is on by default for alpha-linux-gnu, unless -ffinite-math-only (which is part of the -ffast-math set) is specified, because the software functions in the GNU libc math libraries generate denormalized numbers, NaNs, and infs (all of which will cause a program to SIGFPE when it attempts to use the results without -mieee). ๐Ÿ˜ญ

  • -mieee-with-inexact โ€” This is like -mieee except the generated code also maintains the IEEE inexact-flag. Turning on this option causes the generated code to implement fully-compliant IEEE math. In addition to "_IEEE_FP", "_IEEE_FP_EXACT" is defined as a preprocessor macro. On some Alpha implementations the resulting code may execute significantly slower than the code generated by default. Since there is very little code that depends on the inexact-flag, you should normally not specify this option. Other Alpha compilers call this option -ieee_with_inexact.
  • -mfp-trap-mode= trap-mode โ€” This option controls what floating-point related traps are enabled. Other Alpha compilers call this option -fptm trap-mode. The trap mode can be set to one of four values:
    • n โ€” This is the default (normal) setting. The only traps that are enabled are the ones that cannot 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 details).
    • 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. There's this field chilling in the floating-point control register (fpcr, peek the Alpha architecture reference manual for the deets) and it controls which rounding mode is actually in effect. The C library sets this register up for rounding towards plus infinity, so unless your program goes in and messes with the fpcr directly, d = round towards plus infinity. Simple as that bestie ๐Ÿ’…
  • -mtrap-precision=trap-precision` โ€” ok so on the Alpha architecture, floating-point traps are imprecise ๐Ÿ˜ญ which is basically the worst. It means that without some software help, there is literally no way to recover from a floating trap, and program execution normally just has to be terminated. GCC can spit out code that helps operating system trap handlers figure out the exact location that caused the floating-point trap though ๐Ÿฆ‹ Depending on what your application actually needs, you can pick different levels of precision:
    • p โ€” Program precision. This one's the default, and it means a trap handler can only identify which program caused a floating-point exception. That's it, that's all you get.
    • f โ€” Function precision. Now the trap handler can determine the function that caused the floating-point exception. Glow up โœจ
    • i โ€” Instruction precision. The trap handler can determine the exact instruction that caused the floating-point exception. Main character precision honestly ๐Ÿ‘‘

Other Alpha compilers ship the equivalent options but they're named -scope_safe and -resumption_safe.

  • -mieee-conformant โ€” this marks the generated code as IEEE conformant. ๐Ÿšจ Do 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 the whole entire job fr fr.
  • -mbuild-constants โ€” normally GCC looks at a 32- or 64-bit integer constant and asks itself "can I build this out of smaller constants in two or three instructions?" If it can't, it just outputs the constant as a literal and generates code to load it from the data segment at run time.

Use this option to force GCC to construct all integer constants using code, even if that takes more instructions (the maximum is six). The classic use case: building a shared library dynamic loader. It's itself a shared library, so it has to relocate itself in memory before it can even find the variables and constants in its own data segment. Iconic recursion moment ๐ŸŒ€

  • -mbwx
  • -mno-bwx
  • -mcix
  • -mno-cix
  • -mfix
  • -mno-fix
  • -mmax
  • -mno-max

These tell GCC whether it should generate code that uses the optional BWX, CIX, FIX and MAX instruction sets. The default is to use whatever instruction sets are supported by the CPU type you specified via the -mcpu= option โ€” or, if you didn't specify one, by the CPU that GCC was built on.

  • -mfloat-vax
  • -mfloat-ieee

Generate code that uses (or 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 had literally no way to generate symbol relocations except through assembler macros, and using those macros means you can't get optimal instruction scheduling ๐Ÿ˜” GNU binutils as of version 2.12 supports a new syntax that lets the compiler explicitly mark which relocations 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 gets accessed via gp-relative relocations. With -msmall-data, objects that are 8 bytes long or smaller get placed in a small data area (the ".sdata" and ".sbss" sections) and accessed via 16-bit relocations off of the $gp register. This caps the small data area at 64KB, but the payoff is that those variables are directly accessible via a single instruction. Tiny but mighty ๐ŸŽ€

The default is -mlarge-data. With that one, the data area is limited to just below 2GB. Programs that need more than 2GB of data have to use malloc or mmap to allocate the data in the heap instead of in the program's data segment.

When generating code for shared libraries, -fpic implies -msmall-data and -fPIC implies -mlarge-data.

  • -msmall-text
  • -mlarge-text

With -msmall-text, the compiler assumes that the code of the entire program (or shared library) fits in 4MB, and is therefore reachable with a branch instruction. When -msmall-data is used, the compiler can assume that all local symbols share the same $gp value, and thus it can reduce the number of instructions required for a function call from 4 to 1. Efficiency slay ๐Ÿ’…

The default is -mlarge-text.

  • -mcpu=cpu_type` โ€” sets the instruction set and the instruction scheduling parameters for machine type cpu_type. You can specify either the EV style name or the corresponding chip number. GCC supports scheduling parameters for the EV4, EV5 and EV6 family of processors and picks the default values for the instruction set from the processor you specify. If you don't specify a processor type, GCC defaults to the processor on which the compiler was built.

Supported values for cpu_type are:

  • ev4
  • ev45
  • 21064

Schedules as an EV4 and has no instruction set extensions.

  • ev5
  • 21164

Schedules as an EV5 and has no instruction set extensions.

  • ev56
  • 21164a

Schedules as an EV5 and supports the BWX extension.

  • pca56
  • 21164pc
  • 21164PC

Schedules as an EV5 and supports the BWX and MAX extensions.

  • ev6
  • 21264

Schedules as an EV6 and supports the BWX, FIX, and MAX extensions.

  • ev67
  • 21264a

Schedules as an EV6 and supports the BWX, CIX, FIX, and MAX extensions.

Native toolchains also support the value native, which selects the best architecture option for the host processor. -mcpu=native has no effect if GCC does not recognize the processor. ๐Ÿ’€

  • -mtune=cpu_type` โ€” sets only the instruction scheduling parameters for machine type cpu_type. The instruction set is not changed. Just vibes, not architecture, yk?

Native toolchains also support the value native, which selects the best architecture option for the host processor. -mtune=native has no effect if GCC does not recognize the processor.

  • -mmemory-latency=time` โ€” sets the latency the scheduler should assume for typical memory references as seen by the application. This number is highly dependent on the memory access patterns used by the application and the size of the external cache on the machine. So like, it's giving "it depends" energy.

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*** โ€” this specifies the hard limit for frame sizes, in bytes. Currently, the value that can be specified should be less than or equal to 32767`. Defaults to whatever limit is imposed by the version of the Linux kernel targeted.
  • *-mkernel=version*** โ€” this specifies the minimum version of the kernel that will run the compiled program. GCC uses this version to determine 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, latestandnative`. yes bestie that really is a whole list ๐ŸŒธ
  • -mbig-endian โ€” generate code for a big-endian target.
  • -mlittle-endian โ€” generate code for a little-endian target. This is the default.
  • -mjmpext โ€” enable generation of extra conditional-branch instructions. Enabled for CPU v2 and above.
  • -mjmp32 โ€” enable 32-bit jump instructions. Enabled for CPU v3 and above.
  • -malu32 โ€” enable 32-bit ALU instructions. Enabled for CPU v3 and above.
  • *-mcpu=version*** โ€” this specifies which version of the eBPF ISA to target. Newer versions may not be supported by all kernels. The default is v3`.

Supported values for version are:

  • v1 โ€” The first stable eBPF ISA with no special features or extensions.
  • v2 โ€” Supports the jump extensions, as in -mjmpext.
  • v3 โ€” All features of v2, plus:
    • 32-bit jump operations, as in -mjmp32
    • 32-bit ALU operations, as in -malu32
  • -mco-re โ€” enable BPF Compile Once - Run Everywhere (CO-RE) support. Requires and is implied by -gbtf. โœจ
  • -mno-co-re โ€” disable BPF Compile Once - Run Everywhere (CO-RE) support. BPF CO-RE support is enabled by default when generating BTF debug information for the BPF target.
  • -mxbpf โ€” generate code for an expanded version of BPF, which relaxes some of the restrictions imposed by the BPF architecture:
    • Save and restore callee-saved registers at function entry and exit, respectively.

๐ŸŽ€ FR30 Options ๐ŸŽ€

These options are defined specifically for the FR30 port.

  • -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 like, cute and compact but only if everything actually fits ๐Ÿซถ
  • -mno-lsim โ€” assume that runtime support has been provided and so there's 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.
  • -mlra โ€” enable Local Register Allocation. This is still experimental for FT32, so by default the compiler uses standard reload. (Experimental!! be careful bestie ๐Ÿ™ˆ)
  • -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 โ€” only use the first 32 floating-point registers, bestie. That's it, that's the whole vibe. ๐Ÿ’…
  • -mfpr-64 โ€” use all 64 floating-point registers. Go big or go home, fr fr.
  • -mhard-float โ€” do your floating-point math with actual hardware instructions, like nature intended. โšก
  • -msoft-float โ€” do that same floating-point math with library routines instead. Slower but softer, like a cozy blanket for your FPU. ๐Ÿงธ
  • -malloc-cc โ€” dynamically allocate condition code registers. Fancy and flexible โœจ
  • -mfixed-cc โ€” nope, don't dynamically allocate condition code registers. Just use "icc0" and "fcc0" and that's it. Simple living. ๐Ÿƒ
  • -mdword โ€” change the ABI to use double word insns. We're doing things double now.
  • -mno-dword โ€” do not use double word instructions. Put those back.
  • -mdouble โ€” use floating-point double instructions. Two times the float, two times the fun. ๐ŸŽ€
  • -mno-double โ€” do not use floating-point double instructions. Single float only, no cap.
  • -mmedia โ€” use media instructions. It's giving multimedia main character energy. ๐ŸŽฌ
  • -mno-media โ€” do not use media instructions. The media era is over, bestie.
  • -mmuladd โ€” use multiply and add/subtract instructions. Math girlies, this one's for you. ๐Ÿงฎโœจ
  • -mno-muladd โ€” do not use multiply and add/subtract instructions. We're on a math break.
  • -mfdpic โ€” select the FDPIC ABI, which uses function descriptors to represent pointers to functions. Okay so here's the tea: without any PIC/PIE-related options, it implies -fPIE. With -fpic or -fpie, it assumes GOT entries and small data are within a 12-bit range from the GOT base address. With -fPIC or -fPIE, GOT offsets are computed with 32 bits. And with a bfin-elf target, this option implies -msim. That's the whole rundown, iykyk. ๐Ÿ’–
  • -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. It's giving "free real estate" for your PLT entries. ๐Ÿ 
  • -mTLS โ€” assume a large TLS segment when generating thread-local code. Big TLS energy. ๐Ÿ’ช
  • -mtls โ€” do not assume a large TLS segment when generating thread-local code. Keep it smol. ๐Ÿฃ
  • -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. Math queen behavior, honestly. ๐Ÿ‘‘
  • -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. It's the option that uses you, not the other way around. ๐Ÿ™ˆ
  • -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. Frame pointers stay winning. ๐Ÿ†
  • -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. Long-distance relationship with your functions, and it's working. ๐Ÿ’ž
  • -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. Not me adding NOPs to the group chat ๐Ÿ’€
  • -mlibrary-pic โ€” generate position-independent EABI code. PIC but make it EABI. โœจ
  • -macc-4 โ€” use only the first four media accumulator registers. Keep it to a quartet. ๐ŸŽถ
  • -macc-8 โ€” use all eight media accumulator registers. Full octet, no holding back. ๐ŸŽค
  • -mpack โ€” pack VLIW instructions. Tetris but for instructions. ๐Ÿงฉ
  • -mno-pack โ€” do not pack VLIW instructions. Leave them spread out like your laundry. ๐Ÿงบ
  • -mno-eflags โ€” do not mark ABI switches in e_flags. We're keeping secrets from the 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. So like, don't get too attached, bestie. ๐Ÿ’”

  • -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. Also on the chopping block, rip. ๐Ÿ˜ญ

  • -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. Enjoy it while it lasts. ๐ŸŒธ

  • -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. Another one destined for the archives. ๐Ÿ“ฆ

  • -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. Live in the moment, okay? โœจ

  • -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. Gone too soon, probably. ๐Ÿฅ€

  • -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. It's giving "limited edition" energy. โณ

  • -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. Same energy, different day.

  • -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. The "&&" girlies are thriving rn. ๐Ÿ’…

  • -mno-multi-cond-exec โ€” disable optimization of "&&" and "||" in conditional execution.

This switch is mainly for debugging the compiler and will likely be removed in a future version. "&&" and "||" are on their own now, bestie.

  • -mnested-cond-exec โ€” enable nested conditional execution optimizations (default).

This switch is mainly for debugging the compiler and will likely be removed in a future version. Nested, like your feelings about deprecated flags. ๐Ÿช†

  • -mno-nested-cond-exec โ€” disable nested conditional execution optimizations.

This switch is mainly for debugging the compiler and will likely be removed in a future version. Unnested, unbothered, unproblematic. ๐Ÿง˜

  • -moptimize-membar โ€” this switch removes redundant "membar" instructions from the compiler-generated code. It is enabled by default. Marie Kondo-ing those membar instructions. โœจ๐Ÿงน
  • -mno-optimize-membar โ€” this switch disables the automatic removal of redundant "membar" instructions from the generated code. Keep all your membars, even the redundant ones. You're a collector. ๐Ÿ—ƒ๏ธ
  • -mtomcat-stats โ€” cause gas to print out tomcat statistics. Meow. ๐Ÿฑ
  • *-mcpu=cpu* โ€” select the processor type for which to generate code. Possible values are frv, fr550, tomcat, fr500, fr450, fr405, fr400, fr300 and simple. Pick your fighter. ๐ŸŽ€

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. The classic, the icon, the glibc. ๐Ÿ‘‘
  • -muclibc โ€” use uClibc C library. This is the default on *-*-linux-*uclibc* targets. uClibc stans, rise up. ๐Ÿซถ
  • -mmusl โ€” use the musl C library. This is the default on *-*-linux-*musl* targets. musl hive, this one's for you. ๐ŸŒธ
  • -mbionic โ€” use Bionic C library. This is the default on *-*-linux-*android* targets. Android's very own libc, living its best life. ๐Ÿค–
  • -mandroid โ€” compile code compatible with Android platform. This is the default on *-*-linux-*android* targets.

When compiling, this option enables -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default. When linking, this option makes the GCC driver pass Android-specific options to the linker. Finally, this option causes the preprocessor macro "__ANDROID__" to be defined. It's giving "I contain multitudes." ๐Ÿ’–

  • -tno-android-cc โ€” disable compilation effects of -mandroid, i.e., do not enable -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default. Turning off the Android compiler vibes specifically. ๐Ÿšซ
  • -tno-android-ld โ€” disable linking effects of -mandroid, i.e., pass standard Linux linking options to the linker. Turning off the Android linker vibes specifically. Standard Linux gang, we're back. ๐Ÿง

H8/300 Options ๐ŸŽ›๏ธ

These -m options are defined for the H8/300 implementations:

  • -mrelax โ€” shorten some address references at link time, when possible; uses the linker option -relax. Shortening like a good lil' crop top. โœ‚๏ธ
  • -mh โ€” generate code for the H8/300H. H is for "hot." ๐Ÿ”ฅ
  • -ms โ€” generate code for the H8S. S is for "slay." ๐Ÿ’…
  • -mn โ€” generate code for the H8S and H8/300H in the normal mode. This switch must be used either with -mh or -ms. It doesn't go anywhere alone, it needs a buddy. ๐Ÿซถ
  • -ms2600 โ€” generate code for the H8S/2600. This switch must be used with -ms. It's a -ms exclusive, no gatecrashing. ๐ŸŽŸ๏ธ
  • -mexr โ€” extended registers are stored on stack before execution of function with monitor attribute. Default option is -mexr. This option is valid only for H8S targets. Stack 'em up. ๐Ÿ“š
  • -mno-exr โ€” extended registers are not stored on stack before execution of function with monitor attribute. Default option is -mno-exr. This option is valid only for H8S targets. Keeping those registers out of the stack, respectfully. ๐Ÿ™…
  • -mint32 โ€” make "int" data 32 bits by default. int got a lil' upgrade, good for them. โฌ†๏ธ
  • -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. Alignment consistency, we love to see it. ๐Ÿ“

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. Forward compatible only, bestie, no time travel backwards. โฉ
  • -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. Just different names for the same slay. โœจ

  • -matomic-libcalls โ€” generate libcalls for atomic loads and stores when sync libcalls are disabled. This option is enabled by default. It only affects the generation of atomic libcalls by the HPPA backend.

Both the sync and libatomic libcall implementations use locking. As a result, processor stores are not atomic with respect to other atomic operations. Processor loads up to DImode are atomic with respect to other atomic operations provided they are implemented as a single access.

The PA-RISC architecture does not support any atomic operations in hardware except for the "ldcw" instruction. Thus, all atomic support is implemented using sync and atomic libcalls. Sync libcall support is in libgcc.a. Atomic libcall support is in libatomic.

This option generates "__atomic_exchange" calls for atomic stores. It also provides special handling for atomic DImode accesses on 32-bit targets. Atomicity is complicated, okay? But this option's got you. ๐Ÿ’–

  • -mbig-switch โ€” does nothing. Preserved for backward compatibility. It's the NPC of compiler options. ๐Ÿง
  • -mcaller-copies โ€” the caller does the copying of function arguments that get passed by hidden reference. Lowkey powerful, highkey risky: it is not compatible with the default 32-bit runtime, so use with care. That said, only aggregates bigger than eight bytes go by hidden reference anyway, and this option gives you better compatibility with OpenMP. ๐Ÿซถ
  • -mcoherent-ldcw โ€” use the ldcw/ldcd coherent cache-control hint.
  • -mdisable-fpregs โ€” floating-point registers? Gone. Off. Not invited. Equivalent to -msoft-float.
  • -mdisable-indexing โ€” stops the compiler from using indexing address modes. Why would you want this? It dodges some rather obscure problems when you're compiling MIG generated code under MACH. niche but real. ๐Ÿ’…
  • -mfast-indirect-calls โ€” generates code that assumes calls never cross space boundaries, which lets GCC emit faster indirect calls. Slay. But it does not work in the presence of shared libraries or nested functions. periodt.
  • *-mfixed-range=register-range* โ€” generate code that treats the given register range as fixed registers. A fixed register is one the register allocator cannot touch, which is exactly the vibe you want when compiling kernel code. ๐Ÿ“Œ A register range is two registers separated by a dash, and you can list multiple ranges separated by commas.
  • -mgas โ€” turn on the use of assembler directives that only GAS understands.
  • -mgnu-ld โ€” use options specific to GNU ld. This passes -shared to ld when building a shared library, and it's the default when GCC is configured (explicitly or implicitly) with the GNU linker. Important: this does not change which ld gets called, it only changes what parameters get handed to that ld. The ld that gets called is decided by the --with-ld configure option, then GCC's program search path, and finally by the user's PATH. Wanna see which linker GCC is using? Print it with gcc -print-prog-name=ld. Heads up bestie: 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's the default when GCC is configured (explicitly or implicitly) with the HP linker. Same deal as above: it does not affect which ld is called, only what parameters get passed to it. Which ld gets called = --with-ld configure option, GCC's program search path, and finally your PATH. Peep it with gcc -print-prog-name=ld. Only available on the 64-bit HP-UX GCC, i.e. configured with hppa*64*-*-hpux*. โญ
  • -mlinker-opt โ€” enables the optimization pass in the HP-UX linker. Big caveat: this makes symbolic debugging impossible. ๐Ÿ˜ญ It also triggers a bug in the HP-UX 8 and HP-UX 9 linkers where they throw bogus error messages when linking some programs.
  • -mlong-calls โ€” generate code that uses long call sequences, so a call can always reach linker generated stubs. By default, long calls only get generated when the distance from the call site to the beginning of the function or translation unit (whichever applies) exceeds a predefined limit set by the branch type in use. Normal calls are limited at 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 you're using the -ffunction-sections option, or when using -mgas and -mno-portable-runtime together under HP-UX with the SOM linker.

Normally you do not want this option because it degrades performance. However, it can be useful in large applications, especially when partial linking is used to build the application.

What types of long calls get used depends on the capabilities of the assembler and linker, plus the type of code being generated. On systems that support long absolute calls, and long pic symbol-difference or pc-relative calls, the impact should be relatively small. But on 32-bit ELF systems in pic code, an indirect call is used โ€” and it is quite long. ๐Ÿ’€

  • -mlong-load-store โ€” generate 3-instruction load and store sequences, as the HP-UX 10 linker sometimes requires. Equivalent to the +k option to the HP compilers.
  • -mjump-in-delay โ€” this option is ignored and provided for compatibility purposes only. it's giving ghost option ๐Ÿ‘ป
  • -mno-space-regs โ€” generate code that assumes the target has no space registers. That lets GCC generate faster indirect calls and use unscaled index address modes. Such code is suitable for level 0 PA systems and kernels. ๐ŸŒˆ
  • -mordered โ€” assume memory references are ordered and barriers aren't needed.
  • -mportable-runtime โ€” use the portable calling conventions proposed by HP for ELF systems.
  • *-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. Go check /usr/lib/sched.models on an HP-UX system to figure out the proper scheduling option for your machine. Default scheduling is 8000. ๐Ÿ‘‘
  • -msio โ€” generate the predefine _SIO for server IO. The default is -mwsio, which generates the predefines __hp9000s700, __hp9000s700__ and _WSIO for workstation IO. These options are available under HP-UX and HI-UX.
  • -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 get used, but that can't be done directly in cross-compilation โ€” you have to make your own arrangements to provide suitable library functions for cross-compilation.

Also, -msoft-float changes the calling convention in the output file, so it's only useful if you compile all of a program with it. Specifically, you need to compile libgcc.a (the library that comes with GCC) with -msoft-float for this to work. no skipping that step bestie ๐Ÿšจ

  • -msoft-mult โ€” use software integer multiplication. This disables the use of the xmpyu instruction. ๐Ÿงฎ
  • *-munix=unix-std* โ€” generate compiler predefines and select a startfile for the specified UNIX standard. The choices for unix-std are 93, 95 and 98. 93 is supported on all HP-UX versions, 95 is available on HP-UX 10.10 and later, and 98 is available on HP-UX 11.11 and later. The default values are 93 for HP-UX 10.00, 95 for HP-UX 10.10 through to 11.00, and 98 for HP-UX 11.11 and later.

-munix=93 provides the same predefines as GCC 3.3 and 3.4. -munix=95 provides additional predefines for XOPEN_UNIX and _XOPEN_SOURCE_EXTENDED, plus the startfile unix95.o. -munix=98 provides additional predefines for _XOPEN_UNIX, _XOPEN_SOURCE_EXTENDED, _INCLUDE__STDC_A1_SOURCE and _INCLUDE_XOPEN_SOURCE_500, plus the startfile unix98.o.

It's important to note that this option changes the interfaces for various library routines. It also affects the operational behavior of the C library. So extreme care is needed when using this option. ๐Ÿ˜ณ

Library code that's meant to operate with more than one UNIX standard must test, set and restore the variable __xpg4_extended_mask as appropriate. Most GNU software doesn't provide this capability.

  • -nolibdld โ€” suppress the generation of link options to search libdld.sl when the -static option is specified on HP-UX 10 and later.
  • -static โ€” the HP-UX implementation of setlocale in libc has a dependency on libdld.sl, and there isn't an archive version of libdld.sl. So when -static is specified, special link options are needed to resolve that dependency.

On HP-UX 10 and later, the GCC driver adds the necessary options to link with libdld.sl when -static is specified โ€” which causes the resulting binary to be dynamic. On the 64-bit port, the linkers generate dynamic binaries by default in any case. The -nolibdld option can be used to stop the GCC driver from adding these link options. ๐ŸŒ€

  • -threads โ€” add support for multithreading with the dce thread library under HP-UX. This option sets flags for both the preprocessor and the linker.

โœจ IA-64 Options โœจ

These are the -m options defined for the Intel IA-64 architecture. buckle up ๐Ÿฆ‹

  • -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. Useful when compiling kernel code.
  • -mauto-pic โ€” generate code that is self-relocatable. This implies -mconstant-gp. 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 โ€” bestie, this one makes inline square roots use the minimum latency algorithm. Fast fast fast ๐ŸŽ๏ธโœจ
  • -minline-sqrt-max-throughput โ€” same inline square roots but with the maximum throughput algorithm instead. Different flavor, same sqrt ๐Ÿ’…
  • -mno-inline-sqrt โ€” okay so do NOT generate inline code for sqrt. Leave it out, we don't want it ๐Ÿšซ
  • -mfused-madd, -mno-fused-madd โ€” do (or don't ๐Ÿ™ˆ) generate code that uses the fused multiply/add or multiply/subtract instructions. The default is to use these instructions, so by default -mfused-madd is the vibe.
  • -mno-dwarf2-asm, -mdwarf2-asm โ€” don't (or do) generate assembler code for the DWARF line number debugging info. This is lowkey useful when you're not using the GNU assembler ๐Ÿ› ๏ธ
  • -mearly-stop-bits, -mno-early-stop-bits โ€” lets stop bits be placed earlier than immediately preceding the instruction that triggered the stop bit. This can improve instruction scheduling, but ngl it doesn't always do so. it's giving "sometimes slay, sometimes meh" ๐Ÿ’€
  • -mfixed-range=register-range โ€” generate code treating the given register range as fixed registers. A fixed register is one the register allocator just cannot use, periodt. Super useful when you're compiling kernel code ๐Ÿ‘‘ A register range is two registers separated by a dash, and you can stack multiple ranges separated by a comma.
  • -mtls-size=tls-size โ€” specify the bit size of immediate TLS offsets. Valid values are 14, 22, and 64. That's the whole menu bestie ๐Ÿ“‹
  • -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, iykyk ๐Ÿ’…
  • -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. Same deal: generates ld.a instructions and the matching check instructions (ld.c / chk.a). The default setting is enabled ๐Ÿซถ
  • -mno-sched-control-spec, -msched-control-spec โ€” (dis/en)able control speculative scheduling. Heads up, this feature is available only during region scheduling (i.e. before reload). It 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 depend on the data speculative loads before reload. This is only effective 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 depend on the data speculative loads after reload. Only effective 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 depend on the control speculative loads. Only effective 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 only chosen for a schedule if there are literally no other choices at that moment. This makes the use of data speculation way 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 only chosen for a schedule when there's no other choice. Makes 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 get considered while computing the instruction priorities. Makes the speculation a little 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 they're 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 โ€” limit on the number of memory insns per instruction group, which gives lower priority to subsequent memory insns trying to schedule into that same instruction group. Frequently useful for preventing cache bank conflicts ๐Ÿ’€ The default value is 1.
  • -msched-max-memory-insns-hard-limit โ€” makes the limit from 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, bestie:

  • -mbarrel-shift-enabled โ€” enable barrel-shift instructions โœจ
  • -mdivide-enabled โ€” enable divide and modulus instructions ๐Ÿ’…
  • -mmultiply-enabled โ€” enable multiply instructions ๐Ÿ”ฅ
  • -msign-extend-enabled โ€” enable sign extend instructions โญ
  • -muser-enabled โ€” enable user-defined instructions ๐Ÿ‘‘

๐ŸŒˆ LoongArch Options ๐ŸŒˆ

These command-line options are defined for LoongArch targets, no cap:

  • -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 lets GCC generate code that may not run at all on processors other than the one indicated ๐Ÿ˜ญ Specifying -march=cpu-type implies -mtune=cpu-type, except where noted otherwise.

The choices for cpu-type are:

  • native โ€” this selects the CPU to generate code for at compilation time by determining the processor type of the compiling machine. Using -march=native enables all instruction subsets supported by the local machine (hence the result might not run on different machines ๐Ÿซ ). Using -mtune=native produces code optimized for the local machine under the constraints of the selected instruction set.
  • loongarch64 โ€” a generic CPU with 64-bit extensions ๐Ÿ’…
  • la464 โ€” LoongArch LA464 CPU with LBT, LSX, LASX, LVZ โœจ
  • -mtune=cpu-type โ€” optimize the output for the given processor, specified by microarchitecture name ๐ŸŽ€
  • -mabi=base-abi-type โ€” generate code for the specified calling convention. base-abi-type can be one of:
    • lp64d โ€” uses 64-bit general purpose registers and 32/64-bit floating-point registers for parameter passing. Data model is LP64, where int is 32 bits, while long int and pointers are 64 bits ๐Ÿ’œ
    • lp64f โ€” uses 64-bit general purpose registers and 32-bit floating-point registers for parameter passing. Data model is LP64, where int is 32 bits, while long int and pointers are 64 bits ๐ŸŒธ
    • lp64s โ€” uses 64-bit general purpose registers and no floating-point registers for parameter passing. Data model is LP64, where int is 32 bits, while long int and pointers are 64 bits ๐Ÿ™ˆ
  • -mfpu=fpu-type โ€” generate code for the specified FPU type, which can be one of:
    • 64 โ€” allow the use of hardware floating-point instructions for 32-bit and 64-bit operations โญ
    • 32 โ€” allow the use of hardware floating-point instructions for 32-bit operations โœจ
    • none, 0 โ€” prevent the use of hardware floating-point instructions ๐Ÿšซ
  • -msoft-float โ€” force -mfpu=none and prevents the use of floating-point registers for parameter passing. Heads up: this option may change the target ABI ๐Ÿ˜ณ
  • -msingle-float โ€” force -mfpu=32 and allow the use of 32-bit floating-point registers for parameter passing. This option may change the target ABI too ๐Ÿ’…
  • -mdouble-float โ€” force -mfpu=64 and allow the use of 32/64-bit floating-point registers for parameter passing. And yep, this option may change the target ABI as well ๐Ÿซถ
  • -mbranch-cost=n โ€” set the cost of branches to roughly n instructions ๐Ÿ”ฅ
  • -mcheck-zero-division, -mno-check-zero-divison โ€” trap (or do not trap) on integer division by zero. The default is -mcheck-zero-division for -O0 or -Og, and -mno-check-zero-division for other optimization levels. (And yes, bestie, the original really does spell the negative one -mno-check-zero-divison โ€” that missing i is iconic and we respect it ๐Ÿ’€)
  • -mcond-move-int, -mno-cond-move-int โ€” conditional moves for integral data in general-purpose registers are enabled (disabled). The default is -mcond-move-int ๐Ÿ’–
  • -mcond-move-float, -mno-cond-move-float โ€” conditional moves for floating-point registers are enabled (disabled). The default is -mcond-move-float ๐ŸŒธ
  • -mmemcpy, -mno-memcpy โ€” force (or do not force) the use of memcpy for non-trivial block moves. The default is -mno-memcpy, which lets GCC inline most constant-sized copies โœจ Setting the optimization level to -Os also forces the use of memcpy, but -mno-memcpy may override this behavior if it's explicitly specified, regardless of the order these options appear on the command line ๐Ÿ‘‘
  • -mstrict-align, -mno-strict-align โ€” avoid or allow generating memory accesses that may not be aligned on a natural object boundary as described in the architecture specification. The default is -mno-strict-align ๐Ÿฆ‹
  • -msmall-data-limit=number โ€” put global and static data smaller than number bytes into a special section (on some targets). The default value is 0 ๐Ÿ’…
  • -mmax-inline-memcpy-size=n โ€” inline all block moves (such as calls to memcpy or structure copies) less than or equal to n bytes. The default value of n is 1024 ๐Ÿ”ฅ
  • -mcmodel=code-model โ€” ok so this one sets the code model, and your choices are:
    • tiny-static โ€” bestieโ€ฆ not implemented yet ๐Ÿ˜ญ
    • tiny โ€” also not implemented yet ๐Ÿ’€
    • normal โ€” the text segment has to live inside a 128MB addressing space, and the data segment has to live inside a 2GB addressing space.
    • medium โ€” now both the text segment and the data segment need to be within 2GB addressing space.
    • large โ€” not implemented yet ๐Ÿ™ˆ
    • extreme โ€” this one does not limit the size of the code segment and data segment at all โœจ. Lowkey important: -mcmodel=extreme is incompatible with -fplt and -mno-explicit-relocs.

The default code model is normal, periodt.

  • -mexplicit-relocs, -mno-explicit-relocs โ€” so this is a choose-your-fighter between using or not using assembler relocation operators when dealing with symbolic addresses. The alternative vibe is to use assembler macros instead, which may limit instruction scheduling but allows linker relaxation ๐Ÿซถ. What's the default, you ask? It gets determined by the assembler capability detected during GCC build-time, plus whatever -mrelax is set to: it's -mexplicit-relocs if the assembler supports relocation operators but -mrelax is not enabled, and -mno-explicit-relocs otherwise. iykyk.
  • -mdirect-extern-access, -mno-direct-extern-access โ€” do not use or use GOT to access external symbols. The default is -mno-direct-extern-access: GOT is used for external symbols with default visibility, but not used for other external symbols.

With -mdirect-extern-access, GOT is not used and all external symbols are PC-relatively addressed ๐ŸŽฏ. Heads up though, it's only suitable for environments where no dynamic link is performed, like firmwares, OS kernels, executables linked with -static or -static-pie. And -mdirect-extern-access is not compatible with -fPIC or -fpic. No cap.

  • -mrelax, -mno-relax โ€” take (or do not take ๐Ÿ‘€) advantage of linker relaxations. If -mpass-mrelax-to-as is enabled, this option is also passed to the assembler. The default is figured out during GCC build-time by detecting corresponding assembler support: -mrelax if the assembler supports both the -mrelax option and the conditional branch relaxation, and -mno-relax otherwise. And bestie, that conditional branch relaxation is required, or else the .align directives and conditional branch instructions in the assembly code outputted by GCC may get rejected by the assembler because of a relocation overflow ๐Ÿ˜ญ.
  • -mpass-mrelax-to-as, -mno-pass-mrelax-to-as โ€” pass (or do not pass) the -mrelax or -mno-relax option to the assembler. The default is determined during GCC build-time by detecting corresponding assembler support: -mpass-mrelax-to-as if the assembler supports the -mrelax option, and -mno-pass-mrelax-to-as otherwise. This option is mostly useful for debugging, or for interoperation with assemblers different from the build-time one ๐Ÿ”ง.

โœจ M32C Options โœจ

  • -mcpu=name โ€” pick the CPU you're generating code for, bestie. name may be one of 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 ๐Ÿ’….
  • -msim โ€” says that the program is gonna be run on the simulator ๐ŸŽฎ. This causes an alternate runtime library to be linked in, which supports stuff like file I/O. You must not use this option when generating programs that will run on real hardware โ€” instead you must provide your own runtime library for whatever I/O functions are needed. Fr fr, respect the boundary.
  • -memregs=number โ€” specifies how many memory-based pseudo-registers GCC uses during code generation. These pseudo-registers get used like real registers, so there's a whole tradeoff between GCC's ability to fit the code into available registers and 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. And because of that, you must not use this option with GCC's default runtime libraries ๐Ÿ‘‘.

๐ŸŒˆ M32R/D Options ๐ŸŒˆ

These -m options are defined for Renesas M32R/D architectures:

  • -m32r2 โ€” generate code for the M32R/2.
  • -m32rx โ€” generate code for the M32R/X.
  • -m32r โ€” generate code for the M32R. This is the default โญ.
  • -mmodel=small โ€” assume all objects live in the lower 16MB of memory (so that 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 ๐ŸŒ).
  • -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 โ€” and thank goodness, because incorrect code is not generated ๐Ÿ™.

  • -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's 1 then branches are preferred over conditional code; if it's 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 ๐Ÿ‘‡.

  • -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 cpus are: 68000, 68010, 68020, 68030, 68040, 68060, 68302, 68332 and cpu32. The ColdFire cpus are given by the table below, which also classifies the CPUs into families ๐Ÿ‘‘:
    • Family 51 : 51 51ac 51ag 51cn 51em 51je 51jf 51jg 51jm 51mm 51qe 51qm
    • Family 5206 : 5202 5204 5206
    • Family 5206e : 5206e
    • Family 5208 : 5207 5208
    • Family 5211a : 5210a 5211a
    • Family 5213 : 5211 5212 5213
    • Family 5216 : 5214 5216
    • Family 52235 : 52230 52231 52232 52233 52234 52235
    • Family 5225 : 5224 5225
    • Family 52259 : 52252 52254 52255 52256 52258 52259
    • Family 5235 : 5232 5233 5234 5235 523x
    • Family 5249 : 5249
    • Family 5250 : 5250
    • Family 5271 : 5270 5271
    • Family 5272 : 5272
    • Family 5275 : 5274 5275
    • Family 5282 : 5280 5281 5282 528x
    • Family 53017 : 53011 53012 53013 53014 53015 53016 53017
    • Family 5307 : 5307
    • Family 5329 : 5327 5328 5329 532x
    • Family 5373 : 5372 5373 537x
    • Family 5407 : 5407
    • Family 5475 : 5470 5471 5472 5473 5474 5475 547x 5480 5481 5482 5483 5484 5485

-mcpu=cpu overrides -march=arch if arch is compatible with cpu. Other combinations of -mcpu and -march are rejected ๐Ÿšซ.

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 โ€” bestie, this makes output for a 68000. It's the default when the compiler was configured for 68000-based systems, and it's literally equivalent to -march=68000.

Reach for this one for microcontrollers with a 68000 or EC000 core โ€” that's the 68008, 68302, 68306, 68307, 68322, 68328 and 68356. โœจ

  • -m68010 โ€” output for a 68010. Default when the compiler is configured for 68010-based systems. Equivalent to -march=68010. ๐ŸŽ€
  • -m68020, -mc68020 โ€” output for a 68020. Default when the compiler is configured for 68020-based systems. Equivalent to -march=68020. ๐Ÿฆ‹
  • -m68030 โ€” output for a 68030. Default when the compiler is configured for 68030-based systems. Equivalent to -march=68030. ๐ŸŒธ
  • -m68040 โ€” output for a 68040. Default when the compiler is configured for 68040-based systems. Equivalent to -march=68040.

Heads up: this option inhibits the use of 68881/68882 instructions that have to be emulated by software on the 68040. So use it if your 68040 doesn't have code to emulate those instructions. ๐Ÿ’…

  • -m68060 โ€” output for a 68060. Default when the compiler is configured for 68060-based systems. Equivalent to -march=68060.

This one inhibits the use of 68020 and 68881/68882 instructions that have to be emulated by software on the 68060. Use it if your 68060 doesn't have code to emulate those instructions. ๐Ÿซถ

  • -mcpu32 โ€” output for a CPU32. Default when the compiler is configured for CPU32-based systems. Equivalent to -march=cpu32.

Use this for microcontrollers with a CPU32 or CPU32+ core, which includes the 68330, 68331, 68332, 68333, 68334, 68336, 68340, 68341, 68349 and 68360. ๐Ÿ˜Œ

  • -m5200 โ€” output for a 520X ColdFire CPU. Default when the compiler is configured for 520X-based systems. It's equivalent to -mcpu=5206, and ngl it's now deprecated in favor of that option. ๐Ÿ’€

Use it for microcontrollers with a 5200 core, including the MCF5202, MCF5203, MCF5204 and MCF5206.

  • -m5206e โ€” output for a 5206e ColdFire CPU. The option is now deprecated in favor of the equivalent -mcpu=5206e.
  • -m528x โ€” output for a member of the ColdFire 528X family. The option is now deprecated in favor of the equivalent -mcpu=528x.
  • -m5307 โ€” output for a ColdFire 5307 CPU. The option is now deprecated in favor of the equivalent -mcpu=5307.
  • -m5407 โ€” output for a ColdFire 5407 CPU. The option is now deprecated in favor of the equivalent -mcpu=5407.
  • -mcfv4e โ€” output for a ColdFire V4e family CPU (e.g. 547x/548x). This includes use of hardware floating-point instructions. The option is equivalent to -mcpu=547x, and is now deprecated in favor of that option. ๐ŸŒˆ
  • -m68020-40 โ€” output for a 68040, but without using any of the new instructions. The result is code that can run relatively efficiently on either a 68020/68881 or a 68030 or a 68040. The generated code does use the 68881 instructions that are emulated on the 68040.

The option is equivalent to -march=68020 -mtune=68020-40. โœจ

  • -m68020-60 โ€” output for a 68060, without using any of the new instructions. Same deal: code that runs relatively efficiently on either a 68020/68881 or a 68030 or a 68040. The generated code does use the 68881 instructions that are emulated on the 68060.

The 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 that have 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 is taken from the target CPU (either the default CPU, or the one specified by -mcpu). Case in point: the default is off for -mcpu=5206 and on for -mcpu=5206e.

GCC defines the macro __mcfhwdiv__ when this option is enabled. ๐Ÿ”ฅ

  • -mshort โ€” treat type int as being 16 bits wide, like short int. On top of that, 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 type int as 16 bits wide. This is the default.
  • -mnobitfield, -mno-bitfield โ€” do not use the bit-field instructions. The -m68000, -mcpu32 and -m5200 options imply -mnobitfield. ๐Ÿ’…
  • -mbitfield โ€” do use the bit-field instructions. The -m68020 option implies -mbitfield. This is the default if you use a configuration designed for a 68020.
  • -mrtd โ€” use a different function-calling convention, in which functions that take a fixed number of arguments return with the rtd instruction, which pops their arguments while returning. This saves one instruction in the caller, since there's no need to pop the arguments there. โœจ

Okay so 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.)

The rtd instruction is supported by the 68010, 68020, 68030, 68040, 68060 and CPU32 processors, but not by the 68000 or 5200.

The default is -mno-rtd. ๐Ÿซถ

  • -malign-int, -mno-align-int โ€” control whether GCC aligns int, long, long long, float, double, and long double variables on a 32-bit boundary (-malign-int) or a 16-bit boundary (-mno-align-int). Aligning variables on 32-bit boundaries produces code that runs somewhat faster on processors with 32-bit busses, at the expense of more memory. ๐ŸŒธ
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 โ€” generate code that allows the data segment to be located in a different area of memory from the text segment. This allows for execute-in-place in an environment without virtual memory management. This option implies -fPIC. โญ
  • -mno-sep-data โ€” generate code that assumes that the data segment follows the text segment. This is the default.
  • -mid-shared-library โ€” generate code that supports shared libraries via the library ID method. This allows for execute-in-place and shared libraries in an environment without virtual memory management. This option implies -fPIC. ๐Ÿ’–
  • -mno-id-shared-library โ€” generate code that doesn't assume ID-based shared libraries are being used. This is the default.
  • -mshared-library-id=n โ€” specifies the identification number of the ID-based shared library being compiled. Specifying a value of 0 generates more compact code; specifying other values forces the allocation of that number to the current library, but is no more space- or time-efficient than omitting this option. ๐ŸŽ€
  • -mxgot, -mno-xgot โ€” when generating position-independent code for ColdFire, generate code that works if the GOT has more than 8192 entries. This code is larger and slower than code generated without this option. On M680x0 processors, this option is not needed; -fPIC suffices.

GCC normally uses a single instruction to load values from the GOT. While this is relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger causes the linker to report an error such as:

relocation truncated to fit: R_68K_GOT16O foobar

If this happens, you should recompile your code with -mxgot. It should then work with very large GOTs. However, code generated with -mxgot is less efficient, since it takes 4 instructions to fetch the value of a global symbol. ๐Ÿ’€

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. Let's get into it ๐Ÿซถ

  • -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 โ€” turn on (or off) emitting callgraph info. the receipts of who called whom ๐Ÿ’…
  • -mslow-bytes, -mno-slow-bytes โ€” prefer grabbing whole words when you're reading byte-sized quantities. lowkey a glow-up for speed ๐Ÿฆ‹
  • -mlittle-endian, -mbig-endian โ€” generate code for a little-endian target. โœจ
  • -m210, -m340 โ€” generate code for the 210 processor. ๐Ÿ‘‘
  • -mno-lsim โ€” assume somebody already handed you the runtime support, so leave the simulator library (libsim.a) off the linker command line. not your problem anymore, bestie ๐Ÿ™ˆ
  • -mstack-increment=size โ€” set the max amount for a single stack increment operation. Big values can make programs with functions that gobble a huge amount of stack space run faster, but they can also absolutely trigger a segmentation fault if the stack gets extended too much ๐Ÿ˜ญ. Default is 0x1000.

๐Ÿงš MicroBlaze Options ๐Ÿงš

  • -msoft-float โ€” use software emulation for floating point (this is the default). ๐Ÿ’œ
  • -mhard-float โ€” use hardware floating-point instructions. slay, actual silicon ๐ŸŽ€
  • -mmemcpy โ€” don't optimize block moves, just use "memcpy". let the library girl handle it ๐Ÿ’…
  • -mno-clearbss โ€” > this option is deprecated. use -fno-zero-initialized-in-bss instead. currently not the vibe โœ‹
  • -mcpu=cpu-type โ€” use the features of, and schedule code for, the given CPU. Supported values look like vX.YY.Z, where X is a major version, YY is the minor version, and Z is compatibility code. Example values: 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. iconic bit-wrangling energy ๐ŸŒ€
  • -mxl-pattern-compare โ€” use pattern compare instructions. โœจ
  • -msmall-divides โ€” use table lookup optimization for small signed integer divisions. ๐Ÿ’…
  • -mxl-stack-check โ€” > deprecated. use -fstack-check instead. ๐Ÿ™ˆ
  • -mxl-gp-opt โ€” use GP-relative ".sdata"/".sbss" sections. ๐ŸŽ€
  • -mxl-multiply-high โ€” use multiply high instructions for the high part of a 32x32 multiply. ๐Ÿ”ฅ
  • -mxl-float-convert โ€” use hardware floating-point conversion instructions. โญ
  • -mxl-float-sqrt โ€” use the hardware floating-point square root instruction. ๐Ÿฆ‹
  • -mbig-endian โ€” generate code for a big-endian target. ๐Ÿ‘‘
  • -mlittle-endian โ€” generate code for a little-endian target. ๐Ÿ’–
  • -mxl-reorder โ€” use reorder instructions (swap and byte reversed load/store). ๐ŸŒˆ
  • -mxl-mode-app-model โ€” select application model app-model. The valid models are:
    • executable โ€” normal executable (default), uses startup code crt0.o. ๐Ÿผ
    • xmdstub โ€” for use with 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. This is suitable for transferring control on a processor reset to the bootloader rather than the application. ๐Ÿฅพ
    • novectors โ€” for applications that do not require any of the MicroBlaze vectors. This option may be useful for applications running within a monitoring application. This model uses crt3.o as a startup file. ๐Ÿ‘€
Option -xl-mode-app-model is a deprecated alias for -mxl-mode-app-model. (ya, the m got added later ๐Ÿ’€)
  • -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. ๐ŸŽฏ

๐ŸŒˆ 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). ๐Ÿ˜ฎโ€๐Ÿ’จ that's a lot of names, bestie.

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. literally shortening it for the aesthetic ๐Ÿ’…

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 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. main character treatment for one sibling ๐Ÿ‘‘

-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 (or don't 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. > bestie, this is a lab experiment, not a flex ๐Ÿงช
  • -minterlink-compressed, -mno-interlink-compressed โ€” require (or don't 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. vintage but valid ๐Ÿ‘‘๐Ÿ’…
  • -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 <https://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 remain the same, but each scalar value is passed in a single 64-bit register rather than a pair of 32-bit registers. For example, scalar floating-point values are returned in $f0 only, not a $f0/$f1 pair. The set of call-saved registers also remains the same in that the even-numbered double-precision registers are saved. ๐Ÿ’–

Okay bestie, we're still deep in MIPS land and honestly? It's giving โœจarchitecture loreโœจ. Buckle up, there's a LOT here. ๐ŸŽ€

Two extra variants of the o32 ABI exist so the world can transition from 32-bit to 64-bit registers without everything catching fire. Meet FPXX (-mfpxx) and FP64A (-mfp64 -mno-odd-spreg). The FPXX extension is a whole rules-girl: it mandates that all code must execute correctly whether it's run using 32-bit or 64-bit registers. You can interlink that code with either FP32 or FP64 โ€” but not both, pick a lane. The FP64A extension is like FP64's cousin who refuses odd numbers: it forbids the use of odd-numbered single-precision registers. You'd use it together with the "FRE" mode of FPUs in MIPS32R5 processors, and it lets both FP32 and FP64A code interlink and run in the same process without switching FPU modes. Teamwork! ๐Ÿซถ

  • -mabicalls, -mno-abicalls โ€” generate (or don't generate) code that plays nice with SVR4-style dynamic objects. -mabicalls is the default on SVR4-based systems. ๐Ÿ’…
  • -mshared, -mno-shared โ€” generate (or don't generate) code that is fully position-independent and can therefore be linked into shared libraries. Heads up: this option only affects -mabicalls.

So like, all -mabicalls code has traditionally been position-independent, no matter what -fPIC and -fpic are doing. 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. That whole mode gets selected by -mno-shared.

Also -mno-shared depends on binutils 2.16 or higher and generates objects that can only be linked by the GNU linker. But don't panic โ€” 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. Win-win. ๐Ÿ”ฅ

-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. And for the n64 ABI, this option has no effect without -msym32.

You can make -mplt the default by configuring GCC with --with-mips-plt. Otherwise the default is -mno-plt.

  • -mxgot, -mno-xgot โ€” lift (or don't lift) the usual restrictions on the size of the global offset table.

Normally GCC uses a single instruction to load values from the GOT. Relatively efficient, sure, but it only works if the GOT is smaller than about 64k. Anything bigger and the linker starts yelling at you with an error like this:

relocation truncated to fit: R_MIPS_GOT16 foobar

If that happens, recompile your code with -mxgot. It works with very large GOTs, though the code is also less efficient โ€” because now it takes three instructions to fetch the value of a global symbol. ๐Ÿ˜ญ

Note that some linkers can create multiple GOTs. If you've got one of those fancy linkers, you should only need -mxgot when a single object file accesses more than 64k's worth of GOT entries. Very few do, bestie.

And these options have no effect unless GCC is generating position independent code. Periodt.

  • -mgp32 โ€” assume general-purpose registers are 32 bits wide.
  • -mgp64 โ€” assume general-purpose registers are 64 bits wide.
  • -mfp32 โ€” assume floating-point registers are 32 bits wide.
  • -mfp64 โ€” assume floating-point registers are 64 bits wide.
  • -mfpxx โ€” do not assume the width of floating-point registers. Mystery girl energy. ๐Ÿฆ‹
  • -mhard-float โ€” use floating-point coprocessor instructions. Real hardware, no pretending.
  • -msoft-float โ€” do not use floating-point coprocessor instructions. Implement floating-point calculations using library calls instead.
  • -mno-float โ€” equivalent to -msoft-float, but additionally asserts that the program being compiled does not perform any floating-point operations at all. 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. Not a vibe. ๐Ÿ’€
  • -msingle-float โ€” assume the floating-point coprocessor only supports single-precision operations.
  • -mdouble-float โ€” assume the floating-point coprocessor supports double-precision operations. This is the default. ๐Ÿ‘‘
  • -modd-spreg, -mno-odd-spreg โ€” enable the use of odd-numbered single-precision floating-point registers for the o32 ABI. This is the default for processors that are known to support these registers. But when you're using the o32 FPXX ABI, -mno-odd-spreg is set by default.
  • -mabs=2008, -mabs=legacy โ€” these control how the special not-a-number (NaN) IEEE 754 floating-point data gets treated with the "abs.fmt" and "neg.fmt" machine instructions.

By default, or when -mabs=legacy is used, the legacy treatment is selected. In that case these instructions are considered arithmetic and avoided wherever correct operation is required and the input operand might be a NaN. Instead, a longer sequence of instructions that manipulate the sign bit of the floating-point datum manually gets used โ€” unless the -ffinite-math-only option has also been specified.

The -mabs=2008 option selects the IEEE 754-2008 treatment. Here these instructions are considered non-arithmetic and therefore operating correctly in all cases, including in particular where the input operand is a NaN. So these instructions are therefore always used for the respective operations. Slay. โœจ

  • -mnan=2008, -mnan=legacy โ€” these control the encoding of the special not-a-number (NaN) IEEE 754 floating-point data.

-mnan=legacy selects the legacy encoding. In this case quiet NaNs (qNaNs) are denoted by the first bit of their trailing significand field being 0, whereas signaling NaNs (sNaNs) are denoted by the first bit of their trailing significand field being 1.

-mnan=2008 selects the IEEE 754-2008 encoding. 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. ๐Ÿ™ˆ

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.

  • -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.
  • -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. Note that 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.

  • -mmt, -mno-mt โ€” use (or don't use) MT Multithreading instructions.
  • -mmcu, -mno-mcu โ€” use (or don't use) the MIPS MCU ASE instructions.
  • -meva, -mno-eva โ€” use (or don't use) the MIPS Enhanced Virtual Addressing instructions.
  • -mvirt, -mno-virt โ€” use (or don't use) the MIPS Virtualization (VZ) instructions.
  • -mxpa, -mno-xpa โ€” use (or don't use) the MIPS eXtended Physical Address (XPA) instructions.
  • -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.
  • -mlong32 โ€” force "long", "int", and pointer types to be 32 bits wide.

The default size of "int"s, "long"s and pointers depends on the ABI. All the supported ABIs use 32-bit "int"s. The n64 ABI uses 64-bit "long"s, as does the 64-bit EABI; the others use 32-bit "long"s. Pointers are the same size as "long"s, or the same size as integer registers, whichever is smaller.

  • -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. Speedrun strats. โญ
  • -G num โ€” put definitions of externally-visible data in a small data section if that data is no bigger than num bytes. GCC can then generate more efficient accesses to the data; see -mgpopt for details.

The default -G option depends on the configuration.

  • -mlocal-sdata, -mno-local-sdata โ€” extend (or don't extend) the -G behavior to local data too, such as to static variables in C. -mlocal-sdata is the default for all configurations. ๐Ÿ’–

So if the linker is out here complaining that your application is using wayyy too much small data ๐Ÿ˜ญ bestie, you might wanna try rebuilding the less performance-critical parts with -mno-local-sdata. You might also wanna build large libraries with -mno-local-sdata, so that those libraries leave more room for the main program. ๐Ÿซถ


  • -mextern-sdata, -mno-extern-sdata โ€” Assume (or, with the no version, do not assume) that externally-defined data lives in a small data section if the size of that data is within the -G limit. -mextern-sdata is the default for all configurations, no cap. ๐Ÿ’…

If you compile a module Mod with -mextern-sdata -G num -mgpopt, and Mod references a variable Var that's no bigger than num bytes, you must make sure that Var is placed in a small data section. If Var is defined by another module, you must either compile that module with a high-enough -G setting or attach a "section" attribute to Var's definition. And if Var is common? Then you must link the application with a high-enough -G setting. Periodt.

The easiest way of satisfying these restrictions is to just compile and link every module with the same -G option. Iconic. But maybe you wanna build a library that supports several different small data limits โ€” and you can, 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. Chef's kiss. ๐Ÿ‘‘

  • -mgpopt, -mno-gpopt โ€” Use (or don't use) GP-relative accesses for symbols that are known to be in a small data section; see -G, -mlocal-sdata and -mextern-sdata. -mgpopt is the default for all configurations. โœจ

-mno-gpopt is giving "my $gp register might not hold the value of _gp" energy, and it's useful in exactly those cases. For example, if the code is part of a library that might get used in a boot monitor, programs that call boot monitor routines pass an unknown value in $gp. (In situations like that, the boot monitor itself is usually compiled with -G0.) ๐Ÿ™ˆ

Heads up though: -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 it reduces the amount of RAM required when executing, so it may be preferred for some embedded systems. ๐Ÿ“
  • -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, babe: ๐ŸŒˆ
    • -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's also useful on processors that can be configured to have a dual instruction/data SRAM interface and that, like the M4K, automatically redirect PC-relative loads to the instruction RAM. โญ
    • -mcode-readable=no โ€” Instructions must not access executable sections. This 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 (or disable) use of the %hi() and %lo() assembler relocation operators. This option has been superseded by -mexplicit-relocs but is retained for backwards compatibility. ๐Ÿ™ˆ
  • -mexplicit-relocs, -mno-explicit-relocs โ€” Use (or don't use) assembler relocation operators when dealing with symbolic addresses. The alternative, selected by -mno-explicit-relocs, is to use assembler macros instead.

-mexplicit-relocs is the default if GCC was configured to use an assembler that supports relocation operators. ๐Ÿ’…

  • -mcheck-zero-division, -mno-check-zero-division โ€” Trap (or, with the no version, do not trap) on integer division by zero.

The default is -mcheck-zero-division. ๐ŸŽ€

  • -mdivide-traps, -mdivide-breaks โ€” MIPS systems check for division by zero by generating either a conditional trap or a break instruction. Using traps results in smaller code, but it's only supported on MIPS II and later. Also โ€” and this is the tea โ˜• โ€” 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. And divide-by-zero checks can be completely disabled using -mno-check-zero-division. ๐Ÿ’€

  • -mload-store-pairs, -mno-load-store-pairs โ€” Enable (or disable) an optimization that pairs consecutive load or store instructions to enable load/store bonding. This option is enabled by default but only takes effect when the selected architecture is known to support bonding. โšก
  • -munaligned-access, -mno-unaligned-access โ€” Enable (or disable) direct unaligned access for MIPS Release 6. MIPSr6 requires load/store unaligned-access support, by hardware or trap&emulate. So -mno-unaligned-access may be needed by kernel. ๐Ÿ‘‘
  • -mmemcpy, -mno-memcpy โ€” Force (or don't force) the use of memcpy for non-trivial block moves. The default is -mno-memcpy, which allows GCC to inline most constant-sized copies. ๐Ÿฆ‹
  • -mlong-calls, -mno-long-calls โ€” Disable (or, with the no version, 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. no pressure or anything bestie ๐Ÿ˜ญ

This option has no effect on abicalls code. The default is -mno-long-calls.

  • -mmad, -mno-mad โ€” Enable (or disable) use of the mad, madu and mul instructions, as provided by the R4650 ISA. โœจ
  • -mimadd, -mno-imadd โ€” Enable (or disable) use of the madd and msub integer instructions. The default is -mimadd on architectures that support madd and msub, except for the 74k architecture where it was found to generate slower code. ๐Ÿ˜ฌ
  • -mfused-madd, -mno-fused-madd โ€” Enable (or 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. slay.

  • -nocpp โ€” Tell the MIPS assembler to not run its preprocessor over user assembler files (with a .s suffix) when assembling them. ๐Ÿ’…
  • -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, and bestie there are a few: ๐Ÿ˜ญ
    • 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.
  • -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. ngl that's a pretty specific niche ๐Ÿ˜ญ

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 bestie, we're deep in it now, so let's talk about the R10K's little habit of โœจguessingโœจ

Like a lot of processors out there, the R10K tries to predict how a conditional branch is gonna go, and then it speculatively executes instructions from the branch it thinks is "taken". If it guessed wrong, it aborts those instructions later. Cute, right? ๐Ÿ’… Except โ€” and this is the tea โ€” on the R10K, even aborted instructions can have side effects. ๐Ÿ’€

This problem only affects kernel stores, and depending on your system, kernel loads too. 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 that same area of memory before the "dirty" line is flushed, the cached data just... overwrites the DMA-ed data. ๐Ÿ™ˆ For the full description (including other potential problems), go read the R10K processor manual, bestie.

One workaround is to insert cache barrier instructions before every memory access that might be speculatively executed and that might have side effects even if aborted. -mr10k-cache-barrier=setting controls GCC's implementation of this workaround. It assumes that aborted accesses to any byte in these regions do not have side effects:

  1. the memory occupied by the current function's stack frame;
  2. the memory occupied by an incoming stack argument;
  3. the memory occupied by an object with a link-time-constant address.
It is the kernel's responsibility to ensure that speculative accesses to these regions are indeed safe. No cap, that's on you. ๐Ÿซถ

If the input program contains 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. It expects non-GCC functions (like hand-written assembly code, iykyk) to do the same.

The option has three forms:

  • -mr10k-cache-barrier=load-store โ€” Insert a cache barrier before a load or store that might be speculatively executed and that might have side effects even if aborted.
  • -mr10k-cache-barrier=store โ€” Insert a cache barrier before a store that might be speculatively executed and that might have side effects even if aborted.
  • -mr10k-cache-barrier=none โ€” Disable the insertion of cache barriers. This is the default setting.

  • -mflush-func=func, -mno-flush-func โ€” Specifies the function to call to flush the I and D caches, or to not call any such function at all. If it is called, the function must take the same arguments as the common _flush_func, that is: the address of the memory range for which the cache is being flushed, the size of the memory range, and the number 3 (to flush both caches, obvi). The default depends on the target GCC was configured for, but it's commonly either _flush_func or __cpu_flush.
  • mbranch-cost=num โ€” Set the cost of branches to roughly num "simple" instructions. This cost is only a heuristic and is not guaranteed to produce consistent results across releases, so don't come for me. A zero cost redundantly selects the default, which is based on the -mtune setting.
  • -mbranch-likely, -mno-branch-likely โ€” Enable or disable use of Branch Likely instructions, regardless of what the default is for the selected architecture. By default, Branch Likely instructions may be generated if they're supported by the selected architecture. โœจException alertโœจ: for the MIPS32 and MIPS64 architectures and the processors that implement those architectures, Branch Likely instructions are not generated by default, because the MIPS32 and MIPS64 architectures specifically deprecate their use.
  • -mcompact-branches=never, -mcompact-branches=optimal, -mcompact-branches=always โ€” These options control which form of branches will be generated. The default is -mcompact-branches=optimal.
    • The -mcompact-branches=never option ensures that compact branch instructions will never be generated.
    • The -mcompact-branches=always option ensures that a compact branch instruction will be generated if available for MIPS Release 6 onwards. If a compact branch instruction isn't available (or pre-R6), a delay slot form of the branch will be used instead.
    • If it's used for MIPS16/microMIPS targets, it will be just ignored right now. The behaviour for MIPS16/microMIPS may change in future, since they do have some compact branch instructions.
    • The -mcompact-branches=optimal option will cause a delay slot branch to be used if one is available in the current ISA and the delay slot is successfully filled. If the delay slot isn't filled, a compact branch will be chosen if one is available.
  • -mfp-exceptions, -mno-fp-exceptions โ€” Specifies whether FP exceptions are enabled. This affects how FP instructions are scheduled for some processors. The default is that FP exceptions are enabled. For instance, on the SB-1, if FP exceptions are disabled and we're emitting 64-bit code, then we can use both FP pipes. Otherwise, we can only use one FP pipe. ๐Ÿ˜ค
  • -mvr4130-align, -mno-vr4130-align โ€” The VR4130 pipeline is two-way superscalar, but it can only issue two instructions together if the first one is 8-byte aligned. When this option is enabled, GCC aligns pairs of instructions that it thinks should execute in parallel. This option only has an effect when optimizing for the VR4130. It normally makes code faster, but at the expense of making it bigger. It's enabled by default at optimization level -O3.
  • -msynci, -mno-synci โ€” Enable (disable) generation of synci instructions on architectures that support it. The synci instructions (if enabled) are generated when __builtin___clear_cache is compiled. This option defaults to -mno-synci, but the default can be overridden by configuring GCC with --with-synci. When compiling code for single processor systems, it's generally safe to use synci. However, on many multi-core (SMP) systems, it does not invalidate the instruction caches on all cores and may lead to undefined behavior. ๐Ÿšจ so be careful bestie.
  • -mrelax-pic-calls, -mno-relax-pic-calls โ€” Try to turn PIC calls that are normally dispatched via register $25 into direct calls. This is only possible if the linker can resolve the destination at link time and if the destination is within range for a direct call. -mrelax-pic-calls is the default if GCC was configured to use an assembler and a linker that support the .reloc assembly directive and -mexplicit-relocs is in effect. With -mno-explicit-relocs, this optimization can be performed by the assembler and the linker alone without any help from the compiler. team work makes the dream work ๐Ÿ’–
  • -mmcount-ra-address, -mno-mcount-ra-address โ€” Emit (do not emit) code that allows _mcount to modify the calling function's return address. When enabled, this option extends the usual _mcount interface with a new ra-address parameter, which has type intptr_t * and is passed in register $12. _mcount can then modify the return address by doing both of 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.

  • -mframe-header-opt, -mno-frame-header-opt โ€” Enable (disable) frame header optimization in the o32 ABI. When using the o32 ABI, calling functions will allocate 16 bytes on the stack for the called function to write out register arguments. When enabled, this optimization will suppress the allocation of the frame header if it can be determined that it's unused. This optimization is off by default at all optimization levels.
  • -mlxc1-sxc1, -mno-lxc1-sxc1 โ€” When applicable, enable (disable) the generation of lwxc1, swxc1, ldxc1, sdxc1 instructions. Enabled by default. โœจ
  • -mmadd4, -mno-madd4 โ€” When applicable, enable (disable) the generation of 4-operand madd.s, madd.d and related instructions. Enabled by default. ๐Ÿ”ฅ

๐Ÿ‘‘ MMIX Options ๐Ÿ‘‘

These options are defined for the MMIX:

  • -mlibfuncs, -mno-libfuncs โ€” Specify that intrinsic library functions are being compiled, passing all values in registers, no matter the size.
  • -mepsilon, -mno-epsilon โ€” Generate floating-point comparison instructions that compare with respect to the rE epsilon register.
  • -mabi=mmixware, -mabi=gnu โ€” Generate code that passes function parameters and return values that (in the called function) are seen as registers $0 and up, as opposed to the GNU ABI which uses global registers $231 and up.
  • -mzero-extend, -mno-zero-extend โ€” When reading data from memory in sizes shorter than 64 bits, use (do not use) zero-extending load instructions by default, rather than sign-extending ones.
  • -mknuthdiv, -mno-knuthdiv โ€” Make the result of a division yielding a remainder have the same sign as the divisor. With the default, -mno-knuthdiv, the sign of the remainder follows the sign of the dividend. Both methods are arithmetically valid, the latter being almost exclusively used. ๐Ÿค“
  • -mtoplevel-symbols, -mno-toplevel-symbols โ€” Prepend (do not prepend) a : to all global symbols, so the assembly code can be used with the PREFIX assembly directive.
  • -melf โ€” Generate an executable in the ELF format, rather than the default mmo format used by the mmix simulator.
  • -mbranch-predict, -mno-branch-predict โ€” Use (do not use) the probable-branch instructions, when static branch prediction indicates a probable branch.
  • -mbase-addresses, -mno-base-addresses โ€” Generate (do not 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. The 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.
  • -msingle-exit, -mno-single-exit โ€” Force (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 โ€” okay so this makes GCC generate code that dodges the bugs in the multiply instructions on MN10300 processors. It's the default, bestie, so you're already getting it whether you asked or not ๐Ÿ’…
  • -mno-mult-bug โ€” do not generate that bug-avoiding code for the MN10300 multiply instructions. Live dangerously, I guess ๐Ÿ™ˆ
  • -mam33 โ€” generate code using the features that are specific to the AM33 processor. glow-up time โœจ
  • -mno-am33 โ€” don't use those AM33-specific features. This is the default.
  • -mam33-2 โ€” generate code using features specific to the AM33/2.0 processor. the sequel era ๐Ÿ’–
  • -mam34 โ€” generate code using features specific to the AM34 processor.
  • -mtune=cpu-type โ€” use the timing characteristics of the CPU type you name when scheduling instructions. Important: this does not change the targeted processor type, it just tunes the scheduling vibe. The CPU type has to be one of mn10300, am33, am33-2 or am34.
  • -mreturn-pointer-on-d0 โ€” when GCC generates a function that returns a pointer, this returns that pointer in both a0 and d0. If you don't do this, the pointer only comes back in a0, and trying to call such a function without a prototype results in errors ๐Ÿ˜ญ Heads up: this option is on by default, so use -mno-return-pointer-on-d0 to turn it off.
  • -mno-crt0 โ€” don't link in the C run-time initialization object file. bye bye startup code ๐Ÿซถ
  • -mrelax โ€” tells the linker "bestie please run a relaxation optimization pass" to shorten branches, calls and absolute memory addresses. The catch: this option only does anything when you use it on the command line for the final link step.
fr fr this one makes symbolic debugging impossible. choose your fighter ๐Ÿ’€
  • -mliw โ€” lets the compiler generate Long Instruction Word instructions when the target is AM33 or later. This is the default. It defines the preprocessor macro __LIW__.
  • -mno-liw โ€” does not allow Long Instruction Word instructions. Defines the preprocessor macro __NO_LIW__.
  • -msetlb โ€” lets the compiler generate SETLB and Lcc instructions when the target is AM33 or later. Default behavior. Defines the preprocessor macro __SETLB__.
  • -mno-setlb โ€” nope, no SETLB or Lcc instructions allowed. 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 โ€” don't link in the C run-time initialization object file. (Yes, same name as the MN10300 one, different vibes, same energy ๐Ÿซถ)

๐ŸŒธ MSP430 Options ๐ŸŒธ

These options are defined for the MSP430:

  • -masm-hex โ€” force the assembly output to always use hex constants. Normally those constants are signed decimals, but this option exists for testsuite and/or aesthetic purposes. (aesthetic purposes. iconic. ๐Ÿ’…)
  • -mmcu= โ€” select the MCU to target. This gets used to create a C preprocessor symbol based on the MCU name: uppercased and wrapped with __ on both ends. That symbol then gets used by the msp430.h header file to pick an MCU-specific supplementary header file.

The option also sets which ISA to use. If the MCU name is one that's known to support only the 430 ISA, then that's what gets selected โ€” otherwise the 430X ISA is selected. There's also a generic MCU name msp430 you can use to select the 430 ISA, and similarly the generic MCU name msp430x selects the 430X ISA.

On top of all that, an MCU-specific linker script gets added to the linker command line. The script's name is the MCU name with .ld appended. So specifying -mmcu=xxx on the gcc command line defines the C preprocessor symbol __XXX__ and makes the linker go searching for a script called xxx.ld ๐Ÿ˜Œ

The ISA and hardware multiply supported for the different MCUs is hard-coded into GCC. However, an external devices.csv file can be used to extend device support beyond what's hard-coded. lowkey obsessed with the flexibility ๐Ÿ’–

GCC looks for the devices.csv file using these methods, in this precedence order โ€” first beats second, second beats third:

Include path specified with -I and -L

devices.csv will be searched for in each of the directories specified by include paths and linker library search paths.

Path specified by the environment variable MSP430_GCC_INCLUDE_DIR

Set the global environment variable MSP430_GCC_INCLUDE_DIR to the full path of the directory containing devices.csv, and GCC will search that directory for devices.csv. If it finds it there, that directory also gets registered as an include path and a linker library path. So header files and linker scripts in that directory can be used without you manually putting -I and -L on the command line. convenience queen ๐Ÿ‘‘

The msp430-elf{,bare}/include/devices directory

Finally, GCC checks msp430-elf{,bare}/include/devices from the toolchain root directory. This directory doesn't exist in a default installation, but if you made it and copied devices.csv in there, then the MCU data gets read. As above, this directory also gets registered as an include path and a linker library path.

If none of those search methods find devices.csv, then the hard-coded MCU data is used. back to basics ๐Ÿ’œ

  • -mwarn-mcu
  • -mno-warn-mcu โ€” this turns warnings on or off for conflicts between the MCU name specified by -mmcu 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 which ISA to use. Accepted values are msp430, msp430x and msp430xv2. Heads up: 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.
  • -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 the linker, and lets the linker do certain optimizations that literally can't be done until the final link. the ultimate last-minute glow-up โœจ
  • mhwmult= โ€” describes the type of hardware multiply supported by the target. (yes bestie, no dash, that's really how it's written, don't @ me ๐Ÿ™ˆ) 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 from the MCU name provided by the -mmcu option. If no -mmcu option is specified, or if the MCU name isn't recognized, then no hardware multiply support is assumed. auto is the default setting.

Hardware multiplies are normally performed by calling a library routine โ€” this saves space in the generated code. When compiling at -O3 or higher, though, the hardware multiplier is invoked inline. That makes for bigger, but faster code. trade-offs, they're everywhere ๐Ÿฆ‹

The hardware multiply routines disable interrupts while running and restore the previous interrupt state when they finish. That makes them safe to use inside interrupt handlers as well as in normal code. ๐Ÿ”ฅ

  • -minrt โ€” enable the use of a minimum runtime environment โ€” no static initializers or constructors. This is intended for memory-constrained devices. The compiler includes special symbols in some objects that tell the linker and runtime which code fragments are required.
  • -mtiny-printf โ€” enable reduced code size printf and puts library functions. Caveat time: the tiny implementations of these functions are not reentrant, so they must be used with caution in multi-threaded applications ๐Ÿ˜ญ

Support for streams has been removed, and the string to be printed will always be sent to stdout via the write syscall. The string is not buffered before it's sent to write.

This option requires Newlib Nano IO, so GCC must be configured with --enable-newlib-nano-formatted-io.

  • -mmax-inline-shift= โ€” this option takes an integer between 0 and 64 inclusive, and sets the maximum number of inline shift instructions that should be emitted to perform a shift operation by a constant amount. When that 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 can't 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 you pass for this option gets divided by 2 and that resulting value is used instead. math is math โœจ

  • -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 isn't found or there's a problem 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.
  • -mcmov โ€” generate conditional move instructions.
  • -mno-cmov โ€” do not generate conditional move instructions.
  • -mext-perf โ€” generate performance extension instructions. go faster, bestie ๐Ÿ”ฅ
  • -mno-ext-perf โ€” do not generate performance extension instructions.
  • -mext-perf2 โ€” bestie, turn ON the performance extension 2 instructions โœจ
  • -mno-ext-perf2 โ€” and this one does NOT generate them, ok? literally just the off switch ๐Ÿšซ
  • -mext-string โ€” generate string extension instructions ๐Ÿงต
  • -mno-ext-string โ€” do not generate string extension instructions ๐Ÿ™…โ€โ™€๏ธ
  • -mv3push โ€” generate v3 push25/pop25 instructions ๐Ÿซธ
  • -mno-v3push โ€” do not generate v3 push25/pop25 instructions ๐Ÿซท
  • -m16-bit โ€” generate 16-bit instructions ๐Ÿผ
  • -mno-16-bit โ€” do not generate 16-bit instructions, no cap ๐Ÿ“
  • *-misr-vector-size=num* โ€” specify the size of each interrupt vector, and queen it must be 4 or 16, those are the only options, periodt ๐Ÿ’…
  • *-mcache-block-size=num* โ€” specify the size of each cache block. it must be a power of 2 between 4 and 512, so like, do the math first ๐Ÿงฎ
  • *-march=arch* โ€” specify the name of the target architecture ๐Ÿ›๏ธ
  • *-mcmodel=code-model* โ€” set the code model to one of these, pick your fighter:
    • small All the data and read-only data segments must be within 512KB addressing space. The text segment must be within 16MB addressing space. small but mighty fr ๐Ÿฃ
    • medium The data segment must be within 512KB while the read-only data segment can be within 4GB addressing space. The text segment should be still within 16MB addressing space. mid-size, mid-energy ๐Ÿฅ
    • large All the text and data segments can be within 4GB addressing space. big girl energy ๐Ÿ‘‘
  • -mctor-dtor โ€” enable constructor/destructor feature ๐Ÿ—๏ธ
  • -mrelax โ€” guide the linker to relax instructions ๐Ÿง˜โ€โ™€๏ธ it's giving zen

๐Ÿฆ‹ Nios II Options ๐Ÿฆ‹

okay so these are the options defined for the Altera Nios II processor, buckle up bestie, there's a lot ๐Ÿ’œ

  • -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. tiny objects get the VIP small-data treatment ๐Ÿ’–
  • *-mgpopt=option*
  • -mgpopt
  • -mno-gpopt โ€” generate (or do NOT generate) GP-relative accesses. These option names below are recognized, and they are very much a vibe ladder:
    • none Do not generate GP-relative accesses. nada. zero. ๐Ÿ™…
    • local Generate GP-relative accesses for small data objects that are not external, weak, or uninitialized common symbols. Also use GP-relative addressing for objects that have been explicitly placed in a small data section via a "section" attribute. keeping it local ๐Ÿ”’
    • global As for local, but also generate GP-relative accesses for small data objects that are external, weak, or common. โš ๏ธ If you use this option, you must ensure that all parts of your program (including libraries) are compiled with the same -G setting. no mixing, bestie, it's giving consistency check ๐ŸŒ
    • data Generate GP-relative accesses for all data objects in the program. โš ๏ธ If you use this option, the entire data and BSS segments of your program must fit in 64K of memory and you must use an appropriate linker script to allocate them within the addressable range of the global pointer. that's a real constraint, not a drill ๐Ÿซ 
    • all Generate GP-relative addresses for function pointers as well as data pointers. โš ๏ธ If you use this option, the entire text, data, and BSS segments of your program must fit in 64K of memory and you must use an appropriate linker script to allocate them within the addressable range of the global pointer. ALL of it. every last byte. iconic but risky ๐Ÿ’€

k so, -mgpopt is equivalent to -mgpopt=local, and -mno-gpopt is equivalent to -mgpopt=none โ€” memorize that, iykyk ๐Ÿง 

The default is -mgpopt except when -fpic or -fPIC is specified to generate position-independent code. Note that the Nios II ABI does not permit GP-relative accesses from shared libraries ๐Ÿ“š

You may need to specify -mno-gpopt explicitly when building programs that include large amounts of small data, including large GOT data sections. In this case, the 16-bit offset for GP-relative addressing may not be large enough to allow access to the entire small data section ๐Ÿ˜ญ yeah, it just runs out of room

  • *-mgprel-sec=regexp* โ€” this option specifies additional section names that can be accessed via GP-relative addressing. It is most useful in conjunction with "section" attributes on variable declarations and a custom linker script. The regexp is a POSIX Extended Regular Expression ๐Ÿ”

This option does not affect the behavior of the -G option, and the specified sections are in addition to the standard ".sdata" and ".sbss" small-data sections that are recognized by -mgpopt โœจ

  • *-mr0rel-sec=regexp* โ€” this option specifies names of sections that can be accessed via a 16-bit offset from "r0"; that is, in the low 32K or high 32K of the 32-bit address space. It is most useful in conjunction with "section" attributes on variable declarations and a custom linker script. The regexp is a POSIX Extended Regular Expression ๐ŸŽฏ

In contrast to the use of GP-relative addressing for small data, zero-based addressing is never generated by default and there are no conventional section names used in standard linker scripts for sections in the low or high areas of memory ๐ŸŒˆ (so like, you're on your own here, bestie)

  • -mel
  • -meb โ€” generate little-endian (default) or big-endian (experimental) code, respectively. -meb is literally labeled experimental, so proceed with caution ๐Ÿงช
  • *-march=arch* โ€” this specifies the name of the target Nios II architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. Permissible names are: r1, r2 ๐Ÿ‘‘

The preprocessor macro __nios2_arch__ is available to programs, with value 1 or 2, indicating the targeted ISA level ๐Ÿ”ข

  • -mbypass-cache
  • -mno-bypass-cache โ€” force all load and store instructions to always bypass cache by using I/O variants of the instructions. The default is not to bypass the cache ๐Ÿšช
  • -mno-cache-volatile
  • -mcache-volatile โ€” volatile memory access bypass the cache using the I/O variants of the load and store instructions. The default is not to bypass the cache ๐ŸŒ€
  • -mno-fast-sw-div
  • -mfast-sw-div โ€” do not use table-based fast divide for small numbers. The default is to use the fast divide at -O3 and above โšก
  • -mno-hw-mul
  • -mhw-mul
  • -mno-hw-mulx
  • -mhw-mulx
  • -mno-hw-div
  • -mhw-div โ€” enable or disable emitting "mul", "mulx" and "div" family of instructions by the compiler. The default is to emit "mul" and not emit "div" and "mulx" ๐Ÿงฎ
  • -mbmx
  • -mno-bmx
  • -mcdx
  • -mno-cdx โ€” enable or disable generation of Nios II R2 BMX (bit manipulation) and CDX (code density) instructions. โš ๏ธ Enabling these instructions also requires -march=r2. Since these instructions are optional extensions to the R2 architecture, the default is not to emit them ๐Ÿ’…
  • *-mcustom-insn*=N
  • *-mno-custom-insn* โ€” each -mcustom-insn=N option enables use of a custom instruction with encoding N when generating code that uses insn. For example, -mcustom-fadds=253 generates custom instruction 253 for single-precision floating-point add operations instead of the default behavior of using a library call ๐ŸŒŸ

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. sorry bestie, it's a package deal ๐Ÿ’€

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 ๐Ÿคฏ like it just handles it, slay

  • 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 ๐Ÿ“–

No cap, you can also grab more local control over how Nios II custom instructions get generated by using the target("custom-insn=N") and target("no-custom-insn") function attributes or pragmas. Cute, right? ๐Ÿ’…

  • -mcustom-fpu-cfg=name โ€” this one turns on a predefined, named set of custom instruction encodings (peep -mcustom-insn above for the deets). Right now these sets are the ones that exist:
    • -mcustom-fpu-cfg=60-1 is equivalent to: -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -fsingle-precision-constant
    • -mcustom-fpu-cfg=60-2 is equivalent to: -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255 -fsingle-precision-constant
    • -mcustom-fpu-cfg=72-3 is equivalent to: -mcustom-floatus=243 -mcustom-fixsi=244 -mcustom-floatis=245 -mcustom-fcmpgts=246 -mcustom-fcmples=249 -mcustom-fcmpeqs=250 -mcustom-fcmpnes=251 -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255 -fsingle-precision-constant
    • -mcustom-fpu-cfg=fph2 is equivalent to: -mcustom-fabss=224 -mcustom-fnegs=225 -mcustom-fcmpnes=226 -mcustom-fcmpeqs=227 -mcustom-fcmpges=228 -mcustom-fcmpgts=229 -mcustom-fcmples=230 -mcustom-fcmplts=231 -mcustom-fmaxs=232 -mcustom-fmins=233 -mcustom-round=248 -mcustom-fixsi=249 -mcustom-floatis=250 -mcustom-fsqrts=251 -mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255

Custom instruction assignments you hand over with individual -mcustom-insn= options override the ones from -mcustom-fpu-cfg=, and bestie, that's true no matter what order the options show up in on the command line. Order who? Never heard of her. ๐Ÿ’€

Oh and btw, you can get more local control over picking a FPU configuration by using the target("custom-fpu-cfg=name") function attribute or pragma.

The name fph2 is short for Nios II Floating Point Hardware 2 Component โ€” say that five times fast, I dare you. ๐ŸŒธ Also pls note: the custom instructions that -mcustom-fmins=233 and -mcustom-fmaxs=234 enable only get generated if -ffinite-math-only is specified. And the custom instruction that -mcustom-round=248 enables only gets generated if -fno-math-errno is specified. And unlike literally every other configuration over here, -fsingle-precision-constant is not set.


๐Ÿฆ‹ These extra -m options are for the Altera Nios II ELF (bare-metal) target ๐Ÿฆ‹

  • -mhal โ€” link with HAL BSP. This suppresses linking with the GCC-provided C runtime startup and termination code, and is typically used together with -msys-crt0= to say where the alternate startup code that the HAL BSP provides actually lives.
  • -msmallc โ€” link with a limited version of the C library, -lsmallc, instead of Newlib. Tiny library, big heart. ๐Ÿซถ
  • -msys-crt0=startfile โ€” startfile is the file name of the startfile (crt0) to use when linking. This option is only useful when you pair it with -mhal, iykyk.
  • -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 one is typically used to link with a library that a HAL BSP provides.

๐Ÿ‘‘ Nvidia PTX Options ๐Ÿ‘‘

These options are defined for Nvidia PTX:

  • -m64 โ€” Ignored, but preserved for backward compatibility. Only 64-bit ABI is supported, so likeโ€ฆ there's nothing else to be. Main character only. โœจ
  • -march=architecture-string โ€” generate code for the specified PTX ISA target architecture (e.g. sm_35). The valid architecture strings are sm_30, sm_35, sm_53, sm_70, sm_75 and sm_80. The default depends on how the compiler has been configured, see --with-arch.

This option sets the value of the preprocessor macro "__PTX_SM__"; for instance, for sm_35, it has the value 350.

  • -misa=architecture-string โ€” alias of -march=. Same vibe, different name. ๐Ÿ’…
  • -march-map=architecture-string โ€” select the closest available -march= value that is not more capable. For instance, for -march-map=sm_50 select -march=sm_35, and for -march-map=sm_53 select -march=sm_53.
  • -mptx=version-string โ€” generate code for the specified PTX ISA version (e.g. 7.0). Valid version strings include 3.1, 6.0, 6.3, and 7.0. The default PTX ISA version is 6.0, unless a higher version is required for the specified PTX ISA target architecture via option -march=.

This option sets the values of the preprocessor macros "__PTX_ISA_VERSION_MAJOR__" and "__PTX_ISA_VERSION_MINOR__"; for instance, for 3.1 the macros have the values 3 and 1, respectively.

  • -mmainkernel โ€” link in code for a __main kernel. This is for stand-alone instead of offloading execution. Solo era. ๐ŸŽ€
  • -moptimize โ€” apply partitioned execution optimizations. This is the default when any level of optimization is selected. Slay, she's already on by default.
  • -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, makes it possible to access automatic variables from other threads, or with atomic instructions. This code generation variant is used for OpenMP offloading, but the option is exposed on its own for the purpose of testing the compiler; to generate code suitable for linking into programs using OpenMP offloading, use option -mgomp.
  • -muniform-simt โ€” switch to a 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. Not me understanding warp politics better than my own group chat ๐Ÿ˜ญ
  • -mgomp โ€” generate code for use in OpenMP offloading: enables -msoft-stack and -muniform-simt options, and selects the corresponding multilib variant. Combo deal, bestie. ๐Ÿ“

๐ŸŒˆ OpenRISC Options ๐ŸŒˆ

These options are defined for OpenRISC:

  • -mboard=name โ€” configure a board specific runtime. This will be passed to the linker for newlib board library linking. The default is "or1ksim".
  • -mnewlib โ€” this option is ignored; it's for compatibility purposes only. This used to select linker and preprocessor options for use with newlib. She's retired but we still invite her to the party. ๐Ÿ’€
  • -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.
  • -mcmodel=small โ€” generate OpenRISC code for the small model: the GOT is limited to 64k. This is the default model.
  • -mcmodel=large โ€” generate OpenRISC code for the large model: the GOT may grow up to 4G in size.

๐Ÿ’œ PDP-11 Options ๐Ÿ’œ

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.

๐ŸŒธ PowerPC Options ๐ŸŒธ

These are listed under

๐Ÿงš PRU Options ๐Ÿงš

These command-line options are defined for the PRU target:

  • -minrt โ€” link with a minimum runtime environment, with no support for static initializers and constructors. Using this option can significantly reduce the size of the final ELF binary. But beware, bestie: the compiler could still generate code with static initializers and constructors. It is up to the programmer to make sure the source program will not use those features. That's on you, gorgeous. ๐Ÿ™ˆ
  • -mmcu=mcu โ€” tells GCC which PRU MCU variant you're building for ๐Ÿ’…. Wanna know the exact list of supported MCUs? Go check Newlib, bestie, that's where it lives.
  • -mno-relax โ€” makes GCC hand --no-relax over to the linker instead of the usual --relax option. no relaxing today, we're locked in ๐Ÿ”’
  • -mloop โ€” lets GCC (or doesn't let GCC, depending) use the LOOP instruction.
  • -mabi=variant โ€” pick the ABI variant your code gets compiled for. -mabi=ti gives you the unmodified TI ABI, while -mabi=gnu gives you a GNU variant that copes more naturally with certain GCC assumptions. Here's the tea on what actually differs โ˜•:
    • Function Pointer Size โ€” the TI ABI says function (code) pointers are 16-bit, whereas GNU only supports 32-bit data and code pointers.
    • Optional Return Value Pointer โ€” any function return value bigger than 64 bits gets passed via a hidden pointer as the first argument of the function. But the TI ABI mandates that this pointer can be NULL in case the caller isn't even using the returned value. GNU, on the other hand, always passes and expects a valid return value pointer. no NULL besties allowed ๐Ÿ˜ค

The current -mabi=ti implementation just raises a compile error the moment any of the above code constructs gets detected. Which means โ€” as a direct consequence โ€” the standard C library cannot be built, and it gets omitted when you link with -mabi=ti. so sad, truly ๐Ÿ’”

Also, relaxation is a GNU feature, and for safety reasons it's disabled when you're using -mabi=ti. Why? Because the TI toolchain does not emit relocations for QBBx instructions, so the GNU linker can't adjust them when it's shortening adjacent LDI32 pseudo instructions. iykyk.


๐ŸŒŠ RISC-V Options ๐ŸŒŠ

These command-line options are defined for RISC-V targets:

  • -mbranch-cost=n โ€” set the cost of branches to roughly n instructions.
  • -mplt, -mno-plt โ€” when generating PIC code, do or don't allow the use of PLTs. Ignored for non-PIC. The default is -mplt.
  • -mabi=ABI-string โ€” specify the integer and floating-point calling convention โœจ. ABI-string is made up of two parts: the size of integer types, and the registers used for floating-point types. So for example, -march=rv64ifd -mabi=lp64d means that long and pointers are 64-bit (which implicitly defines int to be 32-bit), and that floating-point values up to 64 bits wide get passed in F registers. Now contrast that with -march=rv64ifd -mabi=lp64f, which still lets the compiler generate code using 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, where literally no floating-point arguments get passed in registers at all.

The default for this argument is system dependent, so if you want a specific calling convention you should specify one explicitly, bestie. The valid calling conventions are: ilp32, ilp32f, ilp32d, lp64, lp64f, and lp64d. Heads up tho โ€” some calling conventions are straight-up impossible to implement on some ISAs: for example, -march=rv32if -mabi=ilp32d is invalid because the ABI requires 64-bit values be passed in F registers, but F registers are only 32 bits wide ๐Ÿ’€. There's also the ilp32e ABI that can only be used with the rv32e architecture. This ABI is not well specified at present, and is subject to change. you've been warned ๐Ÿ‘‘

  • -mfdiv, -mno-fdiv โ€” do or don't use hardware floating-point divide and square root instructions. This requires the F or D extensions for floating-point registers. The default is to use them if the specified architecture has these instructions.
  • -mdiv, -mno-div โ€” do or don't use hardware instructions for integer division. This requires the M extension. The default is to use them if the specified architecture has these instructions.
  • -misa-spec=ISA-spec-string โ€” specify which version of the RISC-V Unprivileged (formerly User-Level) ISA specification you want to produce code conforming to. The possibilities for ISA-spec-string are:
    • 2.2 โ€” produce code conforming to version 2.2.
    • 20190608 โ€” produce code conforming to version 20190608.
    • 20191213 โ€” produce code conforming to version 20191213.

The default is -misa-spec=20191213 unless GCC has been configured with --with-isa-spec= specifying a different default version.

  • -march=ISA-string โ€” generate code for the given RISC-V ISA (e.g. rv64im). ISA strings must be lower-case, no yelling allowed ๐Ÿ˜Œ. Examples include rv64i, rv32g, rv32e, and rv32imaf.

When -march= isn't specified, use the setting from -mcpu.

If neither -march nor -mcpu= is specified, the default for this argument is system dependent โ€” so if you want a specific architecture extensions, specify one explicitly, okay bestie?

  • -mcpu=processor-string โ€” use the architecture of, and optimize the output for, the given processor, specified by a particular CPU name. The 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 a whole squad fr fr ๐Ÿ”ฅ
  • -mtune=processor-string โ€” optimize the output for the given processor, specified by microarchitecture or a particular CPU name. The permissible values for this option are: rocket, sifive-3-series, sifive-5-series, sifive-7-series, thead-c906, size, and all valid options for -mcpu=.

When -mtune= isn't specified, use the setting from -mcpu โ€” and the default is rocket if both are unspecified.

Now, the size choice is not intended for use by end-users, okay? It's used when -Os is specified. It overrides the instruction cost info provided by -mtune=, but it does not override the pipeline info. This helps reduce code size while still giving good performance. it's giving "trust the process" ๐Ÿ’…

  • -mpreferred-stack-boundary=num โ€” attempt to keep the stack boundary aligned to a 2 raised to num-byte boundary. If -mpreferred-stack-boundary isn't specified, the default is 4 (16 bytes or 128-bits).
โš ๏ธ Warning: if you use this switch, then you must build all modules with the same value, including any libraries. This includes the system libraries and startup modules. all or nothing, no half-vibes ๐Ÿ˜ญ
  • -msmall-data-limit=n โ€” put global and static data smaller than n bytes into a special section (on some targets).
  • -msave-restore, -mno-save-restore โ€” do or don't use smaller but slower prologue and epilogue code that calls library functions. The default is to use fast inline prologues and epilogues. speed over size, iconic behavior โญ
  • -minline-atomics, -mno-inline-atomics โ€” do or don't use smaller but slower subword atomic emulation code that calls libatomic functions. The default is to use fast inline subword atomics that do not require libatomic.
  • -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 itself be compressed ๐Ÿฆ‹. Currently targets 32-bit integer load/stores only.
  • -mstrict-align, -mno-strict-align โ€” do not or do generate unaligned memory accesses. The default is set depending on whether the processor we're 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. the main character of code models ๐Ÿ‘‘
  • -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.

Just so you know: the code generated by the medium-any code model is position-independent, but it is not guaranteed to function correctly when linked into position-independent executables or libraries. read that twice, bestie ๐Ÿ™ˆ

  • -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, the typo in -mno-exlicit-relocs is real, we don't make the rules ๐Ÿ’€)
  • -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.
  • -mriscv-attribute, -mno-riscv-attribute โ€” emit (or do not emit) a RISC-V attribute to record extra information into ELF objects. This feature requires at least binutils 2.32. don't be out here with old binutils, it's giving outdated ๐Ÿ“Ÿ
  • -mcsr-check, -mno-csr-check โ€” enables or disables the CSR checking.
  • -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. The supported locations are global for a global canary, or tls for a per-thread canary in the TLS block ๐Ÿ”.

With that latter choice, the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which register to use as the base register for reading the canary, and from what offset from that base register. There is no default register or offset, because this is entirely for use within the Linux kernel. kernel girlies only ๐Ÿ’œ


๐Ÿ“ RL78 Options ๐Ÿ“

  • -msim โ€” links in additional target libraries to support operation within a simulator.
  • -mmul=none, -mmul=g10, -mmul=g13, -mmul=g14, -mmul=rl78 โ€” specifies the type of hardware multiplication and division support to be used. The simplest is none, which uses software for both multiplication and division โ€” and that's the default. The g13 value is for the hardware multiply/divide peripheral found on the RL78/G13 (S2 core) targets. The g14 value selects the use of the multiplication and division instructions supported by the RL78/G14 (S3 core) parts. The value rl78 is an alias for g14, and the value mg10 is an alias for none. aliases stay aliasing, periodt ๐Ÿ’…

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 โ€” targets the RL78 G10 core, also called the S1 core.
  • -mcpu=g13 โ€” targets the RL78 G13 core, a.k.a. the S2 core.
  • -mcpu=g14 โ€” targets the RL78 G14 core, a.k.a. the S3 core, a.k.a. just plain RL78.
  • -mcpu=rl78 โ€” same vibe, the RL78 core ๐Ÿ’œ

Specifies which RL78 core you're targeting, bestie. Default is the G14 core โ€” also known as the S3 core, or literally just RL78, no cap. The G13 (S2) core doesn't have multiply or divide instructions, and the way it handles those is via a hardware peripheral instead. The G10 (S1) core has no register banks at all, so it uses a whole different calling convention. โœจ

If you set this option it also picks the type of hardware multiply support to use, unless something overrides that with an explicit -mmul=none on the command line. So: -mcpu=g13 turns on the G13 hardware multiply peripheral, and -mcpu=g10 disables hardware multiplication entirely. ๐Ÿ’…

Important, queens: even though RL78/G14 is the default target, actually saying -mcpu=g14 or -mcpu=rl78 on the command line does change how the toolchain behaves, because it also turns on G14 hardware multiply support. If you don't pass those on the command line, then software multiplication routines get used โ€” even though the code is targeting the RL78 core. That's for backwards compatibility with older toolchains that didn't have hardware multiply and divide support. Not a bug, just โœจlegacy vibesโœจ.

Also, a C preprocessor macro is defined based on how you set this option. Possible values: "__RL78_G10__", "__RL78_G13__" or "__RL78_G14__".

  • -mg10 โ€” alias for the matching -mcpu= option
  • -mg13 โ€” alias for the matching -mcpu= option
  • -mg14 โ€” alias for the matching -mcpu= option
  • -mrl78 โ€” alias for the matching -mcpu= option

These are aliases for the corresponding -mcpu= option. They're provided for backwards compatibility. ๐Ÿซถ

  • -mallregs โ€” let the compiler use every available register, bestie

Lets the compiler use all of the available registers. By default, registers r24..r31 are reserved for use in interrupt handlers. Flip this on and those registers can be used in ordinary functions too. more registers, more power ๐Ÿ”ฅ

  • -m64bit-doubles โ€” makes double 64 bits wide
  • -m32bit-doubles โ€” makes double 32 bits wide

Makes the double data type 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. Default is -m32bit-doubles.

  • -msave-mduc-in-interrupts โ€” interrupt handlers should preserve the MDUC registers
  • -mno-save-mduc-in-interrupts โ€” don't bother

Says that interrupt handler functions should preserve the MDUC registers. You only need this if normal code might be using the MDUC registers โ€” like, say, because it's doing multiplication and division. Default is to ignore the MDUC registers, since that makes interrupt handlers faster. Heads up: you gotta pass the target option -mg13 for this to work at all, because the feature only exists on the G13 target (S2 core). And the MDUC registers only get saved if the interrupt handler actually does a multiplication or division, or 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 โ€” allow (or don't allow) the optional PowerPC General Purpose group instructions
  • -mpowerpc-gfxopt / -mno-powerpc-gfxopt โ€” allow (or don't allow) the optional PowerPC Graphics group instructions
  • -mpowerpc64 / -mno-powerpc64 โ€” extra 64-bit PowerPC64 instructions, treat GPRs as 64-bit
  • -mmfcrf / -mno-mfcrf โ€” move from condition register field instruction
  • -mpopcntb / -mno-popcntb โ€” popcount + double-precision FP reciprocal estimate
  • -mpopcntd / -mno-popcntd โ€” popcount instruction
  • -mfprnd / -mno-fprnd โ€” FP round to integer instructions
  • -mcmpb / -mno-cmpb โ€” compare bytes instruction
  • -mhard-dfp / -mno-hard-dfp โ€” decimal floating-point instructions

You use these options to say which instructions are available on the processor you're using. The default value of these is decided when GCC is configured. Specifying -mcpu=cpu_type overrides whatever you set here. And fr fr, the recommendation is: use -mcpu=cpu_type instead of the big list above. ๐Ÿ’…

Specifying -mpowerpc-gpopt lets GCC use the optional PowerPC architecture instructions in the General Purpose group, floating-point square root included. Specifying -mpowerpc-gfxopt lets GCC use the optional ones in the Graphics group, floating-point select included. โœจ

The -mmfcrf option lets GCC generate the move from condition register field instruction โ€” that's the one implemented on the POWER4 processor and other processors supporting the PowerPC V2.01 architecture. The -mpopcntb option lets GCC generate the popcount and double-precision FP reciprocal estimate instruction, implemented on POWER5 and friends supporting PowerPC V2.02. The -mpopcntd option lets GCC generate the popcount instruction implemented on POWER7 and other PowerPC V2.06 processors. The -mfprnd option lets GCC generate the FP round to integer instructions implemented on POWER5+ and other PowerPC V2.03 processors. The -mcmpb option lets GCC generate the compare bytes instruction implemented on POWER6 and other PowerPC V2.05 processors. And the -mhard-dfp option lets GCC generate the decimal floating-point instructions implemented on some POWER processors. ๐Ÿ“

The -mpowerpc64 option lets GCC generate the additional 64-bit instructions found in the full PowerPC64 architecture, and treats GPRs as 64-bit, doubleword quantities. GCC defaults to -mno-powerpc64.


๐Ÿ’– -mcpu=cpu_type ๐Ÿ’–

  • -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 endianness), 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 the cpu type detects and selects the architecture option that matches the host processor of the system doing the compilation. -mcpu=native does nothing if GCC doesn't recognize the processor. ๐Ÿ˜ญ

The other options specify a specific processor. Code generated under those 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 wanna set an individual option to a particular value, you can 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 doesn't have full support for these options. You can still enable or disable them individually if you're sure it'll work in your environment. ๐Ÿซก


๐Ÿฆ‹ -mtune=cpu_type ๐Ÿฆ‹

  • -mtune=cpu_type โ€” set instruction scheduling parameters for machine type cpu_type, without touching architecture type or register usage

Sets the instruction scheduling parameters for machine type cpu_type, but does 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. periodt ๐Ÿ’…


  • -mcmodel=small โ€” PowerPC64 code for the small model
  • -mcmodel=medium โ€” PowerPC64 code for the medium model
  • -mcmodel=large โ€” PowerPC64 code for the large model

-mcmodel=small generates PowerPC64 code for the small model: the TOC is limited to 64k.

-mcmodel=medium generates PowerPC64 code for the medium model: the TOC and other static data may be up to a total of 4G in size. This is the default for 64-bit Linux.

-mcmodel=large generates PowerPC64 code for the large model: the TOC may be up to 4G in size, and 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
  • -mvrsave / -mno-vrsave โ€” generate VRSAVE instructions when generating AltiVec code
  • -msecure-plt โ€” non-executable .plt and .got sections, PowerPC 32-bit SYSV ABI option
  • -mbss-plt โ€” BSS .plt section filled in by ld.so, PowerPC 32-bit SYSV ABI option
  • -misel / -mno-isel โ€” turn generation of ISEL instructions on or off
  • -mvsx / -mno-vsx โ€” use (don't use) vector/scalar (VSX) instructions
  • -mcrypto / -mno-crypto โ€” enable (disable) built-ins for the cryptographic instructions added in version 2.07 of the PowerPC ISA
  • -mhtm / -mno-htm โ€” enable (disable) built-ins for the Hardware Transactional Memory (HTM) instructions added in version 2.07 of the PowerPC ISA
  • -mpower8-fusion / -mno-power8-fusion โ€” keep (don't keep) some integer operations adjacent so they can be fused on power8 and later

-maltivec / -mno-altivec generates code that uses (does not use) AltiVec instructions, and also enables 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 matches array element order corresponding to the endianness of the target. That is: element zero identifies the leftmost element in a vector register when targeting a big-endian platform, and identifies the rightmost element in a vector register when targeting a little-endian platform. iykyk ๐Ÿ’…

-mvrsave / -mno-vrsave generates VRSAVE instructions when generating AltiVec code.

-msecure-plt generates code that lets ld and ld.so build executables and shared libraries with non-executable .plt and .got sections. This is a PowerPC 32-bit SYSV ABI option.

-mbss-plt generates code that uses a BSS .plt section that ld.so fills in, and requires .plt and .got sections that are both writable and executable. Also a PowerPC 32-bit SYSV ABI option. ๐Ÿ‘‘

-misel / -mno-isel enables or disables the generation of ISEL instructions.

-mvsx / -mno-vsx generates code that uses (does not use) vector/scalar (VSX) instructions, and also enables the use of built-in functions that allow more direct access to the VSX instruction set.

-mcrypto / -mno-crypto enables (or disables) the use of the built-in functions that allow direct access to the cryptographic instructions added in version 2.07 of the PowerPC ISA. ๐Ÿ”ฅ

-mhtm / -mno-htm enables (or disables) the use of the built-in functions that allow direct access to the Hardware Transactional Memory (HTM) instructions added in version 2.07 of the PowerPC ISA.

-mpower8-fusion / -mno-power8-fusion generates code that keeps (does not keeps) some integer operations adjacent so that the instructions can be fused together on power8 and later processors. (Yes bestie, "does not keeps" โ€” we're quoting the source exactly, no editing the canon. ๐Ÿ’€)

  • -mpower8-vector, -mno-power8-vector โ€” turns on (or off, bestie) the generation of code that uses the vector and scalar instructions added in version 2.07 of the PowerPC ISA. It also opens the door for built-in functions that give you more direct access to those vector instructions. ๐Ÿ’–
  • -mquad-memory, -mno-quad-memory โ€” generate code that uses (or doesn't use) the non-atomic quad word memory instructions. Heads up though: -mquad-memory requires you to be in 64-bit mode. No 64-bit? No quad-memory. periodt.
  • -mquad-memory-atomic, -mno-quad-memory-atomic โ€” same energy but for the atomic quad word memory instructions. And yes, -mquad-memory-atomic also requires 64-bit mode. ๐Ÿ’…
  • -mfloat128, -mno-float128 โ€” enable or disable the __float128 keyword for IEEE 128-bit floating point, and pick whether you want software emulation or actual hardware instructions for it.

Okay real talk: to use the IEEE 128-bit floating point support you must have the VSX instruction set enabled (-mvsx). And it's only supported on Linux, sorry not sorry. The default for -mfloat128 is enabled on PowerPC Linux systems that use the VSX instruction set, and disabled everywhere else.

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 will also enable the generation of ISA 3.0 IEEE 128-bit floating point instructions. Otherwise โ€” like if you don't specify ISA 3.0 instructions, or you're targeting a 32-bit big endian system โ€” it's software emulation city. ๐Ÿ˜ญ

  • -mfloat128-hardware, -mno-float128-hardware โ€” enable or disable using ISA 3.0 hardware instructions to back the __float128 data type. The default for -mfloat128-hardware is enabled on PowerPC Linux systems using the ISA 3.0 instruction set, and disabled on other systems. โœจ
  • -m32, -m64 โ€” generate code for 32-bit or 64-bit environments of Darwin and SVR4 targets (including GNU/Linux, obviously). 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, just like -mpowerpc64.
  • -mfull-toc, -mno-fp-in-toc, -mno-sum-in-toc, -mminimal-toc โ€” these modify how the TOC (Table Of Contents) gets generated. Every executable file has one, btw. -mfull-toc is selected by default. In that case GCC allocates at least one TOC entry for each unique non-automatic variable reference in your program. GCC also puts floating-point constants in the TOC. But โ€” plot twist โ€” only 16,384 entries are available in the TOC. ๐Ÿ‘‘

If you get a linker error saying you've overflowed the available TOC space, you can shrink the TOC usage with -mno-fp-in-toc and -mno-sum-in-toc. Here's the tea: -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 putting that sum into the TOC. You can specify one or both. Each one makes GCC produce very slightly slower and larger code โ€” the trade-off is that you conserve TOC space. ๐Ÿซถ

If you still run out of TOC space even after both of those, specify -mminimal-toc instead. This option makes GCC create only one TOC entry for every file. When you use it, GCC produces code that is slower and larger, but it uses extremely little TOC space. You might wanna use this only on files that contain less frequently-executed code. iykyk.

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

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 and is 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 run. The system must have PE installed in the standard location (/usr/lpp/ppe.poe/), or the specs file must be overridden with the -specs= option to specify the appropriate directory location. And โ€” important โ€” 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) 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 (or does use) the floating-point register set. Software floating-point emulation is provided if you use -msoft-float, and you also pass the option to GCC when linking. Don't forget the linking part, bestie.
  • -mmultiple, -mno-multiple โ€” generate code that uses (or doesn't use) the load multiple word instructions and the store multiple word instructions. These instructions are generated by default on POWER systems, and not generated on PowerPC systems.
โš ๏ธ Do not use -mmultiple on little-endian PowerPC systems, because 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. So likeโ€ฆ know your chip. ๐Ÿ”ฅ
  • -mupdate, -mno-update โ€” generate code that uses (or doesn't use) the load or store instructions that update the base register to the address of the calculated memory location. These instructions are generated by default.
If you use -mno-update, there's a small window between the time the stack pointer is updated and the address of the previous frame is stored โ€” which means code that walks the stack frame across interrupts or signals may get corrupted data. That's a no-no. ๐Ÿ˜ญ
  • -mavoid-indexed-addresses, -mno-avoid-indexed-addresses โ€” generate code that tries to avoid (or 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 (or doesn't use) the floating-point multiply and accumulate instructions. These instructions are generated by default if hardware floating point is used. The machine-dependent -mfused-madd option is now mapped to the machine-independent -ffp-contract=fast option, and -mno-fused-madd is mapped to -ffp-contract=off. Glow up. โœจ
  • -mmulhw, -mno-mulhw โ€” generate code that uses (or doesn't 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 (or doesn't 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 (or do) force structures and unions that contain bit-fields to be aligned to the base type of the bit-field.

For example: 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. By using -mno-bit-align, the structure is aligned to a 1-byte boundary and is 1 byte in size. Cute and compact. ๐ŸŽ€

  • -mno-strict-align, -mstrict-align โ€” on System V.4 and embedded PowerPC systems, do not (or do) assume that unaligned memory references are handled by the system.
  • -mrelocatable, -mno-relocatable โ€” generate code that allows (or doesn't allow) a static executable to be relocated to a different address at run time. A simple embedded PowerPC system loader should relocate the entire contents of ".got2" and 4-byte locations listed in the ".fixup" section โ€” that's a table of 32-bit addresses generated by this option. For this to work, all objects linked together must be compiled with -mrelocatable or -mrelocatable-lib. Also, -mrelocatable code aligns the stack to an 8-byte boundary. ๐Ÿฆ‹
  • -mrelocatable-lib, -mno-relocatable-lib โ€” like -mrelocatable, -mrelocatable-lib generates a ".fixup" section to allow static executables to be relocated at run time โ€” but -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. So flexible. So iconic. ๐ŸŒˆ
  • -mno-toc, -mtoc โ€” on System V.4 and embedded PowerPC systems, do not (or do) assume that register 2 contains a pointer to a global area pointing to the addresses used in the program. โญ

okay bestie, OPTIONS round idk we're deep in PowerPC land and it's giving very much โ€œendianness is a lifestyleโ€ ๐ŸŒˆโœจ buckle up, here's the tea:

  • -mlittle, -mlittle-endian โ€” on System V.4 and embedded PowerPC systems, compile code for the processor in little-endian mode ๐Ÿ’… -mlittle-endian is literally just -mlittle, same vibe.
  • -mbig, -mbig-endian โ€” on System V.4 and embedded PowerPC systems, compile code for the processor in big-endian mode ๐ŸŒธ -mbig-endian is the same as -mbig. no cap.
  • -mdynamic-no-pic โ€” on Darwin and Mac OS X systems, compile code so it's not relocatable, but its external references are relocatable โœจ the resulting code is suitable for applications, but not shared libraries. periodt.
  • -msingle-pic-base โ€” treat the register used for PIC addressing as read-only, instead of loading it in the prologue for each function ๐ŸŽ€ the runtime system is responsible for initializing this register with an appropriate value before execution begins. it's giving โ€œtrust the runtime, bestie.โ€
  • -mprioritize-restricted-insns=priority โ€” this controls the priority assigned to dispatch-slot restricted instructions during the second scheduling pass ๐Ÿ‘‘ the argument priority takes 0, 1, or 2 to assign no, highest, or second-highest (respectively) priority to dispatch-slot restricted instructions.
  • -msched-costly-dep=dependence_type โ€” controls which dependences are considered costly by the target during instruction scheduling ๐Ÿ’€ the argument dependence_type takes one of these values:
    • no โ€” no dependence is costly.
    • all โ€” all dependences are costly.
    • true_store_to_load โ€” a true dependence from store to load is costly.
    • store_to_load โ€” any dependence from store to load is costly.
    • number โ€” any dependence for which the latency is greater than or equal to number is costly.
  • -minsert-sched-nops=scheme โ€” controls which NOP insertion scheme is used during the second scheduling pass ๐Ÿฆ‹ the argument scheme takes one of these values:
    • no โ€” don't insert NOPs.
    • pad โ€” pad with NOPs any dispatch group that has vacant issue slots, according to the scheduler's grouping.
    • regroup_exact โ€” insert NOPs to force costly dependent insns into separate groups. insert exactly as many NOPs as needed to force an insn to a new group, according to the estimated processor grouping.
    • number โ€” insert NOPs to force costly dependent insns into separate groups. insert number NOPs to force an insn to a new group.
  • -mcall-sysv โ€” on System V.4 and embedded PowerPC systems, compile code using calling conventions that adhere to the March 1995 draft of the System V Application Binary Interface, PowerPC processor supplement ๐Ÿ“œ this is the default unless you configured GCC using powerpc-*-eabiaix.
  • -mcall-sysv-eabi, -mcall-eabi โ€” specify both -mcall-sysv and -meabi options ๐Ÿ’– two-for-one, slay.
  • -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 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 ๐Ÿ˜ญ
  • -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 ๐Ÿ’ฅ
  • -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 ๐Ÿ’›
  • -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 (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 โ€” so this one caps how many bytes of string comparison get inlined: it compares at most num string bytes with inline code. If the difference (or the end of the string) isn't found by the time the inline compare ends, a call to "strcmp" or "strncmp" handles the rest of the comparison for you. The default is 64 bytes. ๐Ÿ’…
  • -G num โ€” on embedded PowerPC systems, this drops global and static items that are 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 also gets passed along to the linker. And listen: all modules should be compiled with the same -G num value โ€” keep it consistent, bestie, or things get weird. โœจ
  • -mregnames, -mno-regnames โ€” on System V.4 and embedded PowerPC systems, these do (or do not) emit register names in the assembly language output using symbolic forms.
  • -mlongcall, -mno-longcall โ€” by default this assumes all calls are far away, so a longer and more expensive calling sequence is required. This is needed 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 away. You can override this setting with the "shortcall" function attribute, or with #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 are plans 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 (peep -mpltseq). But 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). Those 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 gets 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 it 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 they're enabled by default if that support is detected when configuring GCC โ€” and for 32-bit PowerPC specifically, if GCC was configured with --enable-secureplt. Heads up: -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. That relocation lets the linker reliably associate the function call with the argument setup instructions for TLS optimization, which in turn lets GCC schedule the sequence better. โœจ
  • -mrecip, -mno-recip โ€” this option enables use of the reciprocal estimate and reciprocal square root estimate instructions, with extra Newton-Raphson steps to boost 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. ngl, note that while the throughput of the sequence is generally higher than the throughput of the non-reciprocal instruction, the precision can drop 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 actually 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. cute, right? ๐ŸŽ€

  • -mrecip-precision, -mno-recip-precision โ€” assume (or don't assume) that the reciprocal estimate instructions provide higher-precision estimates than the PowerPC ABI mandates. 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. And 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. Fair warning bestie: 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, the TOC value to be loaded in register "r2", and the static chain value to be loaded in register "r11". -mpointers-to-nested-functions is on by default. And heads up: you cannot call through pointers to nested functions, or pointers to functions compiled in other languages that use the static chain, if you're using -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 fixed 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 a canary at guard. Supported locations are global for global canary, or tls for per-thread canary in the TLS block (the default with GNU libc version 2.4 or later).

With that latter choice, the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which register 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. And -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 -mmma option requires that the option -mcpu=power10 (or later) is enabled. ๐Ÿ’–
  • -mrop-protect, -mno-rop-protect โ€” turns ROP protection instructions on (or off) when the target processor can actually back it ๐Ÿ’ช. Heads up fr: right now this option also disables the shrink-wrap optimization (-fshrink-wrap), it's a package deal bestie.
  • -mprivileged, -mno-privileged โ€” generate (or don't generate) code that will run in privileged state ๐Ÿ‘‘. That's the whole vibe.
  • -mblock-ops-unaligned-vsx, -mno-block-ops-unaligned-vsx โ€” generate (or don't) unaligned vsx loads and stores for inline expansion of memcpy and memmove โœจ.
  • --param rs6000-vect-unroll-limit= โ€” the vectorizer checks with target info to figure out whether unrolling the main vectorized loop would even be worth it, and by how much ๐Ÿ”„. This parameter sets the upper bound of how much the vectorizer will unroll the main loop. The default value is four, lowkey iconic.

๐ŸŽ€ RX Options ๐ŸŽ€

These command-line options are defined for RX targets, bestie:

  • -m64bit-doubles, -m32bit-doubles โ€” make the double data type be 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. The default is -m32bit-doubles. Note that RX floating-point hardware only works on 32-bit values, which is literally why the default is -m32bit-doubles ๐Ÿ’….
  • -fpu, -nofpu โ€” enables (-fpu) or disables (-nofpu) the use of RX floating-point hardware. The default is enabled for the RX600 series and disabled for the RX200 series ๐Ÿ“.

Floating-point instructions are only generated for 32-bit floating-point values, however, so the FPU hardware is not used for doubles if the -m64bit-doubles option is used, no cap.

Note: If the -fpu option is enabled then -funsafe-math-optimizations is also enabled automatically ๐Ÿ˜ญ. This is because the RX FPU instructions are themselves unsafe. It's giving chaos but okay.
  • -mcpu=name โ€” selects the type of RX CPU to be targeted. Currently three types are supported: the generic RX600 and RX200 series hardware, and the specific RX610 CPU. The default is RX600 โœจ.

The only difference between RX600 and RX610 is that the RX610 does not support the MVTIPL instruction ๐Ÿšซ.

The RX200 series does not have a hardware floating-point unit and so -nofpu is enabled by default when this type is selected.

  • -mbig-endian-data, -mlittle-endian-data โ€” store data (but not code) in the big-endian format. The default is -mlittle-endian-data, i.e. to store data in the little-endian format ๐ŸŒˆ.
  • -msmall-data-limit=N โ€” specifies the maximum size in bytes of global and static variables which can be placed into the small data area ๐ŸŽ€. Using the small data area can lead to smaller and faster code, but the size of the area is limited and it is up to the programmer to ensure that the area does not overflow. Also, when the small data area is used, one of the RX's registers (usually r13) is reserved for use pointing to this area, so it is no longer available for use by the compiler. This could result in slower and/or larger code if variables are pushed onto the stack instead of being held in this register ๐Ÿ’€.

Note, common variables (variables that have not been initialized) and constants are not placed into the small data area as they are assigned to other sections in the output executable.

The default value is zero, which disables this feature. Note, this feature is not enabled by default with higher optimization levels (-O2 etc) because of the potentially detrimental effects of reserving a register. It is up to the programmer to experiment and discover whether this feature is of benefit to their program ๐Ÿ™ˆ. See the description of the -mpid option for a description of how the actual register to hold the small data area pointer is chosen.

  • -msim, -mno-sim โ€” use the simulator runtime. The default is to use the libgloss board-specific runtime ๐Ÿฆ‹.
  • -mas100-syntax, -mno-as100-syntax โ€” when generating assembler output, use a syntax that is compatible with Renesas's AS100 assembler โœจ. This syntax can also be handled by the GAS assembler, but it has some restrictions so it is not generated by default.
  • -mmax-constant-size=N โ€” specifies the maximum size, in bytes, of a constant that can be used as an operand in a RX instruction. Although the RX instruction set does allow constants of up to 4 bytes in length to be used in instructions, a longer value equates to a longer instruction ๐Ÿ“. Thus in some circumstances it can be beneficial to restrict the size of constants that are used in instructions. Constants that are too big are instead placed into a constant pool and referenced via register indirection.

The value N can be between 0 and 4. A value of 0 (the default) or 4 means that constants of any size are allowed ๐Ÿ’….

  • -mrelax โ€” enable linker relaxation. Linker relaxation is a process whereby the linker attempts to reduce the size of a program by finding shorter versions of various instructions โœ‚๏ธ. Disabled by default.
  • -mint-register=N โ€” specify the number of registers to reserve for fast interrupt handler functions. The value N can be between 0 and 4. A value of 1 means that register r13 is reserved for the exclusive use of fast interrupt handlers. A value of 2 reserves r13 and r12. A value of 3 reserves r13, r12 and r11, and a value of 4 reserves r13 through r10. A value of 0, the default, does not reserve any registers ๐Ÿ‘‘.
  • -msave-acc-in-interrupts โ€” specifies that interrupt handler functions should preserve the accumulator register ๐ŸŽ€. This is only necessary if normal code might use the accumulator register, for example because it performs 64-bit multiplications. The default is to ignore the accumulator as this makes the interrupt handlers faster โšก.
  • -mpid, -mno-pid โ€” enables the generation of position independent data ๐ŸŒŸ. When enabled, any access to constant data is done via an offset from a base address held in a register. This allows the location of constant data to be determined at run time without requiring the executable to be relocated, which is a benefit to embedded applications with tight memory constraints. Data that can be modified is not affected by this option.

Note, using this feature reserves a register, usually r13, for the constant data base address. This can result in slower and/or larger code, especially in complicated functions ๐Ÿ’€.

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 ๐Ÿงš. Thus 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, as the RX only supports one such interrupt.
  • -mallow-string-insns, -mno-allow-string-insns โ€” enables or disables the use of the string manipulation instructions SMOVF, SCMPU, SMOVB, SMOVU, SUNTIL, SWHILE and also the RMPA instruction ๐Ÿ’…. These instructions may prefetch data, which is not safe to do if accessing an I/O register. (See section 12.2.7 of the RX62N Group User's Manual for more information.)

The default is to allow these instructions, but it is not possible for GCC to reliably detect all circumstances where a string instruction might be used to access an I/O register, so their use cannot be disabled automatically ๐Ÿ˜ญ. Instead it is reliant upon the programmer to use the -mno-allow-string-insns option if their program accesses I/O space.

When the instructions are enabled, GCC defines the C preprocessor symbol __RX_ALLOW_STRING_INSNS__, otherwise it defines the symbol __RX_DISALLOW_STRING_INSNS__ ๐ŸŒธ.

  • -mjsr, -mno-jsr โ€” use only (or not only) JSR instructions to access functions. This option can be used when code size exceeds the range of BSR instructions ๐Ÿ“. Note that -mno-jsr does not mean to not use JSR but instead means that any type of branch may be used, periodt.
Note: The generic GCC command-line option -ffixed-reg has special significance to the RX port when used with the interrupt function attribute ๐Ÿซถ. This attribute indicates a function intended to process fast interrupts. GCC ensures that it only uses the registers r10, r11, r12 and/or r13 and only provided that the normal use of the corresponding registers have been restricted via the -ffixed-reg or -mint-register command-line options.

๐Ÿ‘‘ S/390 and zSeries Options ๐Ÿ‘‘

These are the -m options defined for the S/390 and zSeries architecture, bestie ๐Ÿ’œ.

  • -mhard-float, -msoft-float โ€” use (do not use) the hardware floating-point instructions and registers for floating-point operations ๐Ÿ”ฅ. When -msoft-float is specified, functions in libgcc.a are used to perform floating-point operations. When -mhard-float is specified, the compiler generates IEEE floating-point instructions. This is the default โœจ.
  • -mhard-dfp, -mno-hard-dfp โ€” use (do not use) the hardware decimal-floating-point instructions for decimal-floating-point operations ๐ŸŽ€. When -mno-hard-dfp is specified, functions in libgcc.a are used to perform decimal-floating-point operations. When -mhard-dfp is specified, the compiler generates decimal-floating-point hardware instructions. This is the default for -march=z9-ec or higher ๐Ÿ‘‘.
  • -mlong-double-64, -mlong-double-128 โ€” these switches control the size of long double type ๐Ÿ“. A size of 64 bits makes the long double type equivalent to the double type. This is the default.
  • -mbackchain, -mno-backchain โ€” store (do not store) the address of the caller's frame as backchain pointer into the callee's stack frame ๐Ÿฆ‹. A backchain may be needed to allow debugging using tools that do not understand DWARF call frame information. When -mno-packed-stack is in effect, the backchain pointer is stored at the bottom of the stack frame; when -mpacked-stack is in effect, the backchain is placed into the topmost word of the 96/160 byte register save area โญ.

In general, code compiled with -mbackchain is call-compatible with code compiled with -mno-backchain. BUT โ€” and this is the tea โ€” using the backchain for debugging purposes usually requires that the whole binary is built with -mbackchain. Also note: the combo of -mbackchain, -mpacked-stack and -mhard-float? Not supported, bestie, don't try it. If you wanna build a linux kernel, use -msoft-float. ๐Ÿซถ

The default is to not maintain the backchain.

  • -mpacked-stack, -mno-packed-stack โ€” use (or don't use, no pressure) the packed stack layout. When -mno-packed-stack is specified, the compiler uses all fields of the 96/160 byte register save area only for their default purpose, and unused fields still take up stack space (wasteful, lowkey ๐Ÿ˜ญ). When -mpacked-stack is specified, register save slots are densely packed at the top of the register save area, and unused space gets reused for other purposes โ€” allowing for more efficient use of the available stack space. โœจ However, when -mbackchain is also in effect, the topmost word of the save area is always used to store the backchain, and the return address register is always saved two words below the backchain.

As long as the stack frame backchain is not used, code generated with -mpacked-stack is call-compatible with code generated with -mno-packed-stack. Note that some non-FSF releases of GCC 2.95 for S/390 or zSeries generated code that uses the stack frame backchain at run time, not just for debugging purposes. Such code is not call-compatible with code compiled with -mpacked-stack. Also, note that the combination of -mbackchain, -mpacked-stack and -mhard-float is not supported. In order to build a linux kernel, use -msoft-float.

The default is to not use the packed stack layout.

  • -msmall-exec, -mno-small-exec โ€” generate (or 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 โ€” when -m31 is specified, generate code compliant to the GNU/Linux for S/390 ABI. When -m64 is specified, generate code compliant to the GNU/Linux for zSeries ABI. This lets GCC, in particular, generate 64-bit instructions. For the s390 targets, the default is -m31, while the s390x targets default to -m64.
  • -mzarch, -mesa โ€” when -mzarch is specified, generate code using the instructions available on z/Architecture. When -mesa is specified, generate code using the instructions available on ESA/390. Heads up bestie: -mesa is not possible with -m64. When generating code compliant to the GNU/Linux for S/390 ABI, the default is -mesa. When generating code compliant to the GNU/Linux for zSeries ABI, the default is -mzarch.
  • -mhtm, -mno-htm โ€” the -mhtm option enables a set of builtins making use of instructions available with the transactional execution facility introduced with the IBM zEnterprise EC12 machine generation S/390 System z Built-in Functions. -mhtm is enabled by default when using -march=zEC12. ๐Ÿ”ฅ
  • -mvx, -mno-vx โ€” when -mvx is specified, generate code using the instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option changes the ABI for some vector type values with regard to alignment and calling conventions. In case vector type values are being used in an ABI-relevant context, a GAS .gnu_attribute command will be added to mark the resulting binary with the ABI used. -mvx is enabled by default when using -march=z13.
  • -mzvector, -mno-zvector โ€” the -mzvector option enables vector language extensions and builtins using instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option adds support for vector to be used as a keyword to define vector type variables and arguments. vector is only available when GNU extensions are enabled โ€” it will not be expanded when requesting strict standard compliance, e.g. with -std=c99. In addition to the GCC low-level builtins, -mzvector enables a set of builtins added for compatibility with AltiVec-style implementations like Power and Cell. In order to make use of these builtins, the header file vecintrin.h needs to be included. -mzvector is disabled by default.
  • -mmvcle, -mno-mvcle โ€” generate (or don't 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 the 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 (or 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 (or 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 (or 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's 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, bestie ๐Ÿ“‰). 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.


๐ŸŒธ 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 โ€” okay bestie, this one generates code for the SH4-200 and does it in such a way that no double-precision floating-point operations are used. Single precision only, no cap. ๐Ÿ’…
  • -m4-300 โ€” Generate code for SH4-300. That's it, that's the vibe. โœจ
  • -m4-300-nofpu โ€” Generate code for SH4-300 in such a way that the floating-point unit is not used. FPU? Not invited. ๐Ÿšซ
  • -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 โ€” Same energy as above: 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). It's giving bare metal. ๐Ÿ’€
  • -m4-500 โ€” Generate code for SH4-500 (no FPU). It passes -isa=sh4-nofpu to the assembler. Slay. โœจ
  • -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. Iconic. ๐Ÿ‘‘
  • -m4al โ€” Same as -m4a-nofpu, except that it implicitly passes -dsp to the assembler. GCC doesn't generate any DSP instructions at the moment. Noted, bestie. ๐Ÿ“
  • -mb โ€” Compile code for the processor in big-endian mode. Big endian energy. ๐Ÿ˜
  • -ml โ€” Compile code for the processor in little-endian mode. Tiny endian vibes. ๐Ÿญ
  • -mdalign โ€” Align doubles at 64-bit boundaries. Note that this changes the calling conventions, and thus some functions from the standard C library do not work unless you recompile it first with -mdalign. So like, recompile or perish. ๐Ÿ˜ญ
  • -mrelax โ€” Shorten some address references at link time, when possible; uses the linker option -relax. Chill. ๐Ÿง˜
  • -mbigtable โ€” Use 32-bit offsets in switch tables. The default is to use 16-bit offsets. Size matters. ๐Ÿ’…
  • -mbitops โ€” Enable the use of bit manipulation instructions on SH2A. Bit twiddling supremacy. ๐Ÿช„
  • -mfmovd โ€” Enable the use of the instruction fmovd. Check -mdalign for alignment constraints. Don't skip the alignment check, babe. ๐Ÿ”
  • -mrenesas โ€” Comply with the calling conventions defined by Renesas. Respect. ๐Ÿซถ
  • -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. Old school cool. ๐ŸŒˆ
  • -mnomacsave โ€” Mark the MAC register as call-clobbered, even if -mrenesas is given. The MAC register said no thanks. ๐Ÿ’…
  • -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. IEEE drama, but make it fast. โšก
  • -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. Careful, bestie. โš ๏ธ
  • -misize โ€” Dump instruction size and location in the assembly code. For the nosy girlies who need receipts. ๐Ÿ”
  • -mpadstruct โ€” This option is deprecated. It pads structures to multiple of 4 bytes, which is incompatible with the SH ABI. Do not use, fr fr. ๐Ÿšซ
  • -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. This one is spicy. ๐ŸŒถ๏ธ
  • -mprefergot โ€” When generating position-independent code, emit function calls using the Global Offset Table instead of the Procedure Linkage Table. GOT > PLT, apparently. ๐Ÿ’…
  • -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. No user mode, no problem. ๐Ÿ™ˆ
  • -multcost=number โ€” Set the cost to assume for a multiply insn. Multiplication has a price, bestie. ๐Ÿ’ธ
  • -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.
  • -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. Efficient queen. ๐Ÿ‘‘
  • -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. Rename responsibly. โœจ
  • -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 โ€” Assume num to be the cost for a branch instruction. Higher numbers make the compiler try to generate more branch-free code if possible. If not specified the value is selected depending on the processor type that is being compiled for. Branch out, but make it efficient. ๐Ÿฆ‹
  • -mzdcbranch, -mno-zdcbranch โ€” okay so bestie, do we assume the zero displacement conditional branch instructions bt and bf are fast, or do we not? That's literally the whole question. Drop -mzdcbranch and the compiler starts preferring zero displacement branch code sequences like the little overachiever it is ๐Ÿ’…. This is turned on by default when you're generating code for SH4 and SH4A. And if you want it gone-gone, you can explicitly turn it off by passing -mno-zdcbranch. Periodt.
  • -mcbranch-force-delay-slot โ€” this one forces the usage of delay slots for conditional branches, and if it can't find a suitable instruction to put there, it just stuffs the delay slot with a nop ๐Ÿ˜ญ. By default this option is disabled. You'd enable it to work around hardware bugs, like the ones found in the original SH7055. Hardware being messy is so not the vibe.
  • -mfused-madd, -mno-fused-madd โ€” generate code that uses (or does not use) the floating-point multiply and accumulate instructions โœจ. These instructions get generated by default if hardware floating point is being used. And heads 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. Glow-up behavior fr fr.
  • -mfsca, -mno-fsca โ€” allow or disallow the compiler to emit 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. And using -mno-fsca disables sine and cosine approximations even if -funsafe-math-optimizations is in effect. No sine for you, bestie ๐Ÿ’€.
  • -mfsrra, -mno-fsrra โ€” allow or disallow the compiler to emit 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. Two options deep and it still says no? iconic behavior ๐Ÿ˜Œ.
  • -mpretend-cmove โ€” prefer zero-displacement conditional branches for conditional move instruction patterns. Result? Potentially faster code on the SH4 processor ๐Ÿ”ฅ. We love a speed-up.
  • -mfdpic โ€” generate code using the FDPIC ABI. That's it, that's the whole thing ๐ŸŽ€.

โ˜€๏ธ Solaris 2 Options โ˜€๏ธ

These -m options are supported on Solaris 2:

  • -mclear-hwcap โ€” -mclear-hwcap tells the compiler to remove the hardware capabilities generated by the Solaris assembler ๐Ÿ™ˆ. This is only necessary when object files use ISA extensions that aren't supported by the current machine, but check at runtime whether or not to use them.
  • -mimpure-text โ€” -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.
And -mimpure-text suppresses the "relocations remain against allocatable but non-writable sections" linker error message ๐Ÿ’€. However โ€” and this is the important part โ€” 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. Do it the right way bestie, I'm begging ๐Ÿซถ.

These switches are supported in addition to the above on Solaris 2:

  • -pthreads โ€” this is a synonym for -pthread. Same thing, different name, no cap โœจ.

๐Ÿช 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.

Also, -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 of it or none of it, that's the rule ๐ŸŽ€.

  • -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. Know what you're doing, bestie.
  • -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. Nostalgia mode activated, I guess.
  • -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, bestie, take notes ๐Ÿ“:

  • 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. With -mcpu=tsc701, the compiler additionally optimizes it for the TEMIC SPARClet chip ๐Ÿ‘‘.

With -mcpu=v9, GCC spits out code for the V9 flavor of the SPARC architecture ๐Ÿ’… โ€” that brings 64-bit integer and floating-point move instructions, 3 extra floating-point condition code registers (yes, three, count 'em), and conditional move instructions. Then with -mcpu=ultrasparc, the compiler additionally optimizes for the Sun UltraSPARC I/II/IIi chips. With -mcpu=ultrasparc3, it additionally optimizes for the Sun UltraSPARC III/III+/IIIi/IIIi+/IV/IV+ chips. With -mcpu=niagara, it additionally optimizes for Sun UltraSPARC T1 chips. With -mcpu=niagara2, it additionally optimizes for Sun UltraSPARC T2 chips. With -mcpu=niagara3, it additionally optimizes for Sun UltraSPARC T3 chips. With -mcpu=niagara4, it additionally optimizes for Sun UltraSPARC T4 chips. With -mcpu=niagara7, it additionally optimizes for Oracle SPARC M7 chips. And with -mcpu=m8, the compiler additionally optimizes it for Oracle M8 chips. (the way it just keeps going, iconic honestly ๐Ÿ‘‘)

  • -mtune=cpu_type โ€” this one sets the instruction scheduling parameters for machine type cpu_type, but lowkey refuses to set the instruction set or register set the way -mcpu=cpu_type does. Same values accepted as -mcpu=cpu_type, but honestly only the ones that pick out a particular CPU implementation are useful: cypress, supersparc, hypersparc, leon, leon3, leon3v7, leon5, f930, f934, sparclite86x, tsc701, ultrasparc, ultrasparc3, niagara, niagara2, niagara3, niagara4, niagara7 and m8. Oh and with native Solaris and GNU/Linux toolchains you can also use native โœจ
  • -mv8plus, -mno-v8plus โ€” with -mv8plus, GCC generates code for the SPARC-V8+ ABI. The glow-up from the V8 ABI is that the global and out registers are treated as 64 bits wide. This is on 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. Default is -mno-vis, bestie. Sorry.
  • -mvis2, -mno-vis2 โ€” with -mvis2, GCC generates code that takes advantage of version 2.0 of the UltraSPARC Visual Instruction Set extensions. Default is -mvis2 when you're targeting a cpu that supports such instructions, like UltraSPARC-III and later. Heads up: setting -mvis2 also sets -mvis ๐Ÿฆ‹
  • -mvis3, -mno-vis3 โ€” with -mvis3, GCC generates code that takes advantage of version 3.0 of the UltraSPARC Visual Instruction Set extensions. Default is -mvis3 when targeting a cpu that supports such instructions, such as niagara-3 and later. Setting -mvis3 also sets -mvis2 and -mvis. It's a whole bundle, she's generous ๐Ÿ’…
  • -mvis4, -mno-vis4 โ€” with -mvis4, GCC generates code that takes advantage of version 4.0 of the UltraSPARC Visual Instruction Set extensions. 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. Default is -mvis4b when targeting a cpu that supports such instructions, such as m8 and later. Setting -mvis4b also sets -mvis4, -mvis3, -mvis2 and -mvis. The whole chain, slay โœจ
  • -mcbcond, -mno-cbcond โ€” with -mcbcond, GCC generates code that takes advantage of the UltraSPARC Compare-and-Branch-on-Condition instructions. 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. 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. Default is -mfsmuld when targeting a CPU supporting the architecture versions V8 or V9 with FPU โ€” with one exception, -mcpu=leon.
  • -mpopc, -mno-popc โ€” with -mpopc, GCC generates code that takes advantage of the UltraSPARC Population Count instruction. 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. Default is -msubxc when targeting a CPU that supports such an instruction, such as Niagara-7 and later.
  • -mfix-at697f โ€” turns on the documented workaround for the single erratum of the Atmel AT697F processor (which corresponds to erratum #13 of the AT697E processor). Tiny bug, big yikes ๐Ÿซถ
  • -mfix-ut699 โ€” turns on the documented workarounds for the floating-point errata and the data cache nullify errata of the UT699 processor. Two for one ๐Ÿ’–
  • -mfix-ut700 โ€” turns on the documented workaround for the back-to-back store errata of the UT699E/UT700 processor.
  • -mfix-gr712rc โ€” turns on the documented workaround for the back-to-back store errata of the GR712RC processor.

Okay so 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 โ€” set 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. No PIC?? in this economy?? ๐Ÿ˜ญ
  • -mmemory-model=mem-model โ€” set 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. Very official, very iconic ๐Ÿ“œ

  • -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 extra 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. (bestie, they're telling you to use the other ones, take the hint ๐Ÿ’€)
  • -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.

๐Ÿฆ‹ V850 Options ๐Ÿฆ‹

These -m options are defined for V850 implementations:

  • -mlong-calls, -mno-long-calls โ€” treat all calls as being far away (near). If calls are assumed to be far away, the compiler always loads the function's address into a register, and calls indirect through the pointer.
  • -mno-ep, -mep โ€” do not optimize (do optimize) basic blocks that use the same index pointer 4 or more times to copy pointer into the ep register, and use the shorter sld and sst instructions. The -mep option is on by default if you optimize โœจ
  • -mno-prolog-function, -mprolog-function โ€” do not use (do use) external functions to save and restore registers at the prologue and epilogue of a function. The external functions are slower, but use less code space if more than one function saves the same number of registers. The -mprolog-function option is on by default if you optimize.
  • -mspace โ€” try to make the code as small as possible. At present, this just turns on the -mep and -mprolog-function options. Tiny code, tiny vibes ๐Ÿ“
  • -mtda=n โ€” put static or global variables whose size is n bytes or less into the tiny data area that register ep points to. The tiny data area can hold up to 256 bytes in total (128 bytes for byte references).
  • -msda=n โ€” put static or global variables whose size is n bytes or less into the small data area that register gp points to. The small data area can hold up to 64 kilobytes.
  • -mzda=n โ€” put static or global variables whose size is n bytes or less into the first 32 kilobytes of memory.
  • -mv850 โ€” specify that the target processor is the V850.
  • -mv850e3v5 โ€” specify that the target processor is the V850E3V5. The preprocessor constant __v850e3v5__ is defined if this option is used.
  • -mv850e2v4 โ€” specify that the target processor is the V850E3V5. This is an alias for the -mv850e3v5 option.
  • -mv850e2v3 โ€” specify that the target processor is the V850E2V3. The preprocessor constant __v850e2v3__ is defined if this option is used.
  • -mv850e2 โ€” specify that the target processor is the V850E2. The preprocessor constant __v850e2__ is defined if this option is used.
  • -mv850e1 โ€” bestie, this says the target processor is the V850E1 ๐Ÿ’…. When you use it, the preprocessor constants __v850e1__ and __v850e__ get defined. two for the price of one, iconic.
  • -mv850es โ€” target is the V850ES. this is literally just an alias for -mv850e1, no cap.
  • -mv850e โ€” target is the V850E, and the preprocessor constant __v850e__ is defined when you use it โœจ.

okay so if you don't pick any of -mv850, -mv850e, -mv850e1, -mv850e2, -mv850e2v3 or -mv850e3v5, then a default target processor gets chosen for you and the relevant __v850*__ preprocessor constant is defined. the compiler's got you ๐Ÿซถ.

and the preprocessor constants __v850 and __v851__? those are always defined, no matter which processor variant you're targeting. always on, main character constants ๐Ÿ’–.

  • -mdisable-callt, -mno-disable-callt โ€” this one suppresses the generation of the "CALLT" instruction for the v850e, v850e1, v850e2, v850e2v3 and v850e3v5 flavors of the v850 architecture.

it's enabled by default when the RH850 ABI is in use (peep -mrh850-abi), and disabled by default when the GCC ABI is in use. and 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, your choice bestie) 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 is only significant when the target architecture is V850E2V3 or higher, so don't stress otherwise. 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. it's not enabled by default when the e3v5 architecture is selected, because its use is still experimental โ€” so, like, proceed with awareness ๐Ÿ™ˆ.
  • -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. only use this if the assembler/linker complain about out of range branches within a switch table, fr fr.
  • -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.
  • -mlra, -mno-lra โ€” enable Local Register Allocation. this is still experimental for the VAX, so by default the compiler uses standard reload ๐Ÿงš.

๐ŸŒˆ 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.
heads up bestie: -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 selects the CPU to generate code for at compilation time by determining the processor type of the compiling machine. using -march=native enables all instruction subsets supported by the local machine (hence the result might not run on different machines). using -mtune=native produces code optimized for the local machine under the constraints of the selected instruction set ๐Ÿ–ฅ๏ธ.
  • x86-64 โ€” a generic CPU with 64-bit extensions.
  • x86-64-v2, x86-64-v3, x86-64-v4 โ€” these choices for cpu-type select the corresponding micro-architecture level from the x86-64 psABI. on ABIs other than the x86-64 psABI they select the same CPU features as the x86-64 psABI documents for the particular micro-architecture level.

since these cpu-type values do not have a corresponding -mtune setting, using -march with these values enables generic tuning. specific tuning can be enabled using the -mtune=other-cpu-type option with an appropriate other-cpu-type value ๐ŸŒˆ.

  • i386 โ€” Original Intel i386 CPU.
  • 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 โ€” bestie when you pair this with -march, it rolls out the Pentium Pro instruction set, so your code runs on literally every i686 family chip out there. When you use it with -mtune tho, it means the exact same thing as generic. โœจ
  • pentium2 โ€” Intel Pentium II CPU, i.e. Pentium Pro core energy but now with MMX and FXSR instruction set support. ๐Ÿ’…
  • pentium3, pentium3m โ€” Intel Pentium III CPU, again the Pentium Pro core, serving MMX, FXSR and SSE instruction set support.
  • pentium-m โ€” Intel Pentium M, which is the low-power version of the Intel Pentium III CPU, bringing MMX, SSE, SSE2 and FXSR instruction set support. This is the one Centrino notebooks used, iconic. ๐Ÿซถ
  • pentium4, pentium4m โ€” Intel Pentium 4 CPU with MMX, SSE, SSE2 and FXSR instruction set support.
  • prescott โ€” the improved version of the Intel Pentium 4 CPU, with MMX, SSE, SSE2, SSE3 and FXSR instruction set support.
  • nocona โ€” also an improved version of the Intel Pentium 4 CPU, and it's giving 64-bit extensions, MMX, SSE, SSE2, SSE3 and FXSR instruction set support.
  • core2 โ€” Intel Core 2 CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, CX16, SAHF and FXSR instruction set support.
  • nehalem, corei7 โ€” Intel Nehalem CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF and FXSR instruction set support.
  • westmere โ€” Intel Westmere CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR and PCLMUL instruction set support.
  • sandybridge, corei7-avx โ€” Intel Sandy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE and PCLMUL instruction set support.
  • ivybridge, core-avx-i โ€” Intel Ivy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND and F16C instruction set support.
  • haswell, core-avx2 โ€” Intel Haswell CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE and HLE instruction set support.
  • broadwell โ€” Intel Broadwell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX and PREFETCHW instruction set support. (yes bestie, MOVBE really does show up twice in the list, that's fr fr what it says ๐Ÿ˜ญ)
  • skylake โ€” Intel Skylake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES and SGX instruction set support.
  • skylake-avx512 โ€” Intel Skylake Server 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, CLWB, AVX512VL, AVX512BW, AVX512DQ and AVX512CD instruction set support. ๐Ÿ‘‘
  • cascadelake โ€” Intel Cascade Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD and AVX512VNNI instruction set support.
  • cannonlake โ€” Intel Cannon Lake Server CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA and SHA instruction set support.
  • cooperlake โ€” Intel Cooper Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VNNI and AVX512BF16 instruction set support.
  • icelake-client โ€” Intel Ice Lake Client CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2 , VPCLMULQDQ, AVX512BITALG, RDPID and AVX512VPOPCNTDQ instruction set support.
  • icelake-server โ€” Intel Ice Lake Server CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2 , VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD and CLWB instruction set support.
  • tigerlake โ€” Intel Tiger Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, MOVDIRI, MOVDIR64B, CLWB, AVX512VP2INTERSECT and KEYLOCKER instruction set support.
  • rocketlake โ€” Intel Rocket Lake CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID and AVX512VPOPCNTDQ instruction set support.
  • alderlake, raptorlake, meteorlake โ€” Intel Alder Lake/Raptor Lake/Meteor Lake 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, GFNI-SSE, CLWB, MOVDIRI, MOVDIR64B, WAITPKG, ADCX, AVX, AVX2, BMI, BMI2, F16C, FMA, LZCNT, PCONFIG, PKU, VAES, VPCLMULQDQ, SERIALIZE, HRESET, KL, WIDEKL and AVX-VNNI instruction set support.
  • sapphirerapids, emeraldrapids โ€” Intel Sapphire Rapids/Emerald Rapids CPU with 64-bit extensions, 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, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512-FP16 and AVX512BF16 instruction set support. ๐Ÿ”ฅ
  • graniterapids โ€” Intel Granite Rapids CPU with 64-bit extensions, 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, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512-FP16, AVX512BF16, AMX-FP16 and PREFETCHI instruction set support.
  • graniterapids-d โ€” Intel Granite Rapids D CPU with 64-bit extensions, 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, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512FP16, AVX512BF16, AMX-FP16, PREFETCHI and AMX-COMPLEX instruction set support.
  • bonnell, atom โ€” Intel Bonnell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support.
  • silvermont, slm โ€” Intel Silvermont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW and RDRND instruction set support.
  • goldmont โ€” Intel Goldmont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT and FSGSBASE instruction set support.
  • goldmont-plus โ€” Intel Goldmont Plus CPU, and she comes with 64-bit extensions, plus MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT, FSGSBASE, PTWRITE, RDPID and SGX instruction set support. โœจ
  • tremont โ€” Intel Tremont CPU, 64-bit extensions + MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT, FSGSBASE, PTWRITE, RDPID, SGX, CLWB, GFNI-SSE, MOVDIRI, MOVDIR64B, CLDEMOTE and WAITPKG instruction set support. ๐Ÿฆ‹
  • sierraforest โ€” Intel Sierra Forest CPU, 64-bit extensions + MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT, FSGSBASE, PTWRITE, RDPID, SGX, GFNI-SSE, CLWB, MOVDIRI, MOVDIR64B, CLDEMOTE, WAITPKG, ADCX, AVX, AVX2, BMI, BMI2, F16C, FMA, LZCNT, PCONFIG, PKU, VAES, VPCLMULQDQ, SERIALIZE, HRESET, KL, WIDEKL, AVX-VNNI, AVXIFMA, AVXVNNIINT8, AVXNECONVERT, CMPCCXADD, ENQCMD and UINTR instruction set support. ๐Ÿ”ฅ
  • grandridge โ€” Intel Grand Ridge CPU, 64-bit extensions + MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT, FSGSBASE, PTWRITE, RDPID, SGX, GFNI-SSE, CLWB, MOVDIRI, MOVDIR64B, CLDEMOTE, WAITPKG, ADCX, AVX, AVX2, BMI, BMI2, F16C, FMA, LZCNT, PCONFIG, PKU, VAES, VPCLMULQDQ, SERIALIZE, HRESET, KL, WIDEKL, AVX-VNNI, AVXIFMA, AVXVNNIINT8, AVXNECONVERT, CMPCCXADD, ENQCMD and UINTR instruction set support. ๐Ÿ’…
  • knl โ€” Intel Knights Landing CPU, 64-bit extensions + MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AVX512PF, AVX512ER, AVX512F, AVX512CD and PREFETCHWT1 instruction set support. (yes bestie, MOVBE really does show up twice up in there, we're just vibing. ๐Ÿ˜ญ)
  • knm โ€” Intel Knights Mill CPU, 64-bit extensions + MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AVX512PF, AVX512ER, AVX512F, AVX512CD and PREFETCHWT1, AVX5124VNNIW, AVX5124FMAPS and AVX512VPOPCNTDQ instruction set support. ๐Ÿ‘‘
  • k6 โ€” AMD K6 CPU, and her whole personality is MMX instruction set support. ๐ŸŒธ
  • k6-2, k6-3 โ€” the glow-up versions of the AMD K6 CPU, now serving 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 โ€” the improved AMD Athlon CPU, and she brings 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 the AMD K8 cores, now with SSE3 instruction set support. โœจ
  • amdfam10, barcelona โ€” CPUs based on AMD Family 10h cores with x86-64 instruction set support. (This supersets MMX, SSE, SSE2, SSE3, SSE4A, 3DNow!, enhanced 3DNow!, ABM and 64-bit instruction set extensions.) ๐Ÿ’–
  • bdver1 โ€” CPUs based on AMD Family 15h cores with x86-64 instruction set support. (This supersets FMA4, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.)
  • bdver2 โ€” AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersets BMI, TBM, F16C, FMA, FMA4, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.)
  • bdver3 โ€” AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersets BMI, TBM, F16C, FMA, FMA4, FSGSBASE, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.)
  • bdver4 โ€” AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersets BMI, BMI2, TBM, F16C, FMA, FMA4, FSGSBASE, AVX, AVX2, XOP, LWP, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.)
  • znver1 โ€” AMD Family 17h core based CPUs with x86-64 instruction set support. (This supersets BMI, BMI2, F16C, FMA, FSGSBASE, AVX, AVX2, ADCX, RDSEED, MWAITX, SHA, CLZERO, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM, XSAVEC, XSAVES, CLFLUSHOPT, POPCNT, and 64-bit instruction set extensions.) ๐Ÿฆ‹
  • znver2 โ€” AMD Family 17h core based CPUs with x86-64 instruction set support. (This supersets BMI, BMI2, CLWB, F16C, FMA, FSGSBASE, AVX, AVX2, ADCX, RDSEED, MWAITX, SHA, CLZERO, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM, XSAVEC, XSAVES, CLFLUSHOPT, POPCNT, RDPID, WBNOINVD, and 64-bit instruction set extensions.) ๐Ÿฆ‹
  • znver3 โ€” AMD Family 19h core based CPUs with x86-64 instruction set support. (This supersets BMI, BMI2, CLWB, F16C, FMA, FSGSBASE, AVX, AVX2, ADCX, RDSEED, MWAITX, SHA, CLZERO, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM, XSAVEC, XSAVES, CLFLUSHOPT, POPCNT, RDPID, WBNOINVD, PKU, VPCLMULQDQ, VAES, and 64-bit instruction set extensions.) ๐Ÿ’œ
  • 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.) ๐Ÿ”ฅ
  • znver5 โ€” AMD Family 1ah 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, AVXVNNI, MOVDIRI, MOVDIR64B, AVX512VP2INTERSECT, PREFETCHI 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.) ๐Ÿซถ
  • lujiazui โ€” the ZHAOXIN lujiazui CPU ๐Ÿ’š it's got x86-64, plus MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PCLMUL, RDRND, XSAVE, XSAVEOPT, FSGSBASE, CX16, ABM, BMI, BMI2, FXSR, RDSEED instruction set support all up in there. And okay, yes, these chips do support AVX and F16C, but those are not enabled by -march=lujiazui โ€” for performance reasons, bestie. It's giving "we could but we won't" ๐Ÿ˜Œ
  • geode โ€” the AMD Geode embedded processor ๐Ÿ‘ with MMX and 3DNow! instruction set support. Little guy, big vibes.

-mtune=cpu-type ๐Ÿ’…

So -mtune= tunes everything applicable about the generated code to the cpu-type โ€” except for the ABI and the set of available instructions. Like, it's about the vibe of the codegen, not what instructions you're allowed to use.

Picking a specific cpu-type schedules things appropriately for that particular chip. But here's the tea โ˜• โ€” the compiler does not generate any code that can't run on the default machine type unless you also throw a -march=cpu-type in there. For example, if GCC is configured for i686-pc-linux-gnu, then -mtune=pentium4 gives you code that's tuned for Pentium 4 but still runs on i686 machines. No cap.

The choices for cpu-type are literally the same as for -march. But -mtune also supports 2 extra choices for cpu-type, and they're kinda special:

generic โœจ

Produces code optimized for the most common IA32/AMD64/EM64T processors. Now โ€” if you know the CPU your code is gonna run on, you should use the corresponding -mtune or -march option instead of -mtune=generic. But if you have literally no idea what CPUs your users will have?? Then yeah, use this one. It's the "idk just make it work everywhere" queen ๐Ÿ‘‘

As new processors show up in the marketplace, the behavior of this option will change. So if you upgrade to a newer version of GCC, the code generation controlled by this option shifts to reflect whatever processors are most common when that version of GCC drops. It's a moving target, bestie, keep up ๐Ÿฆ‹

And notice ๐Ÿšจ there is no -march=generic option. Why? Because -march indicates the instruction set the compiler can use, and there is no generic instruction set applicable to all processors. Meanwhile -mtune indicates the processor (or, in this case, a whole collection of processors) for which the code is optimized. Different jobs, different girls ๐Ÿ’…

intel ๐Ÿ”ฅ

Produces code optimized for the most current Intel processors โ€” which are Haswell and Silvermont for this version of GCC. Again: if you know the CPU your code will run on, use the corresponding -mtune or -march option instead of -mtune=intel. But if you want your application to perform better on both Haswell and Silvermont, then use this one, periodt.

As new Intel processors get 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 changes to reflect the most current Intel processors at the time that version of GCC is released. Ever-evolving icon behavior ๐Ÿ’ซ

And once again ๐Ÿšจ there is no -march=intel option โ€” because -march indicates the instruction set the compiler can use, and there's no common instruction set applicable to all processors. -mtune, though, indicates the processor (or collection of processors) for which code is optimized. Same energy as the generic situation fr fr.


  • -mcpu=cpu-type โ€” a deprecated synonym for -mtune. Like, it exists, it works, but it's giving "old money that got repossessed" ๐Ÿ’€ use -mtune instead, bestie.

-mfpmath=unit ๐ŸŒธ

Generates floating-point arithmetic for the selected unit. The choices for unit are:

  • 387 โ€” use the standard 387 floating-point coprocessor that's present on the majority of chips (and emulated otherwise). Code compiled with this option runs almost everywhere, which is lowkey iconic. But the temporary results get computed in 80-bit precision instead of the precision specified by the type, so you get slightly different results compared to most other chips ๐Ÿ˜ฌ Check -ffloat-store for a more detailed description of that whole situation.

This is the default choice for non-Darwin x86-32 targets.

  • sse โ€” use scalar floating-point instructions present in the SSE instruction set. This instruction set is supported by Pentium III and newer chips, and in the AMD line by Athlon-4, Athlon XP and Athlon MP chips. The earlier version of the SSE instruction set only supports single-precision arithmetic, so double and extended-precision arithmetic are still done using 387. A later version โ€” present only in Pentium 4 and AMD x86-64 chips โ€” supports double-precision arithmetic too. Glow up โœจ

For the x86-32 compiler, you must use -march=cpu-type, -msse or -msse2 switches to enable SSE extensions and make this option actually take effect. For the x86-64 compiler, these extensions are enabled by default. Lucky them ๐Ÿ’…

The resulting code should be considerably faster in the majority of cases and avoids 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 choice for x86-32 targets with the SSE2 instruction set when -ffast-math is enabled.

  • sse,387
  • sse+387
  • both โ€” attempt to utilize both instruction sets at once. This effectively doubles the amount of available registers, and on chips with separate execution units for 387 and SSE it doubles the execution resources too. Use this option with care though ๐Ÿšจ because it is still experimental โ€” the GCC register allocator does not model separate functional units well, resulting in unstable performance. It's giving messy, ngl.

  • -masm=dialect โ€” output assembly instructions using the selected dialect. Also affects which dialect is used for basic asm and extended asm. Supported choices (in dialect order) are att or intel. The default is att. And heads up ๐Ÿซถ Darwin does not support intel.

  • -mieee-fp
  • -mno-ieee-fp โ€” control whether or not the compiler uses IEEE floating-point comparisons. These correctly handle the case where the result of a comparison is unordered. Important little detail, bestie ๐Ÿค

  • -m80387
  • -mhard-float โ€” generate output containing 80387 instructions for floating point. Hardware girlies, rise ๐Ÿ’ช

  • -mno-80387
  • -msoft-float โ€” generate output containing library calls for floating point. Software girlies, also rise ๐ŸŒˆ
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. That's on you, 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. So like, mostly soft, but not fully soft. It's giving "mostly vegan" ๐Ÿฅ—


  • -mno-fp-ret-in-387 โ€” do not use the FPU registers for return values of functions.

The usual calling convention has functions return values of types float and double in an FPU register โ€” even if there is no FPU. The idea being that the operating system should emulate an FPU. Cute of them ๐Ÿ’–

The option -mno-fp-ret-in-387 causes such values to be returned in ordinary CPU registers instead. Plot twist.


  • -mno-fancy-math-387 โ€” okay so some 387 emulators do not support the sin, cos and sqrt instructions for the 387. Specify this option to avoid generating those instructions. This option gets overridden when -march indicates that the target CPU always has an FPU and so the instruction doesn't need emulation. And PSA ๐Ÿ“ข these instructions are not generated unless you also use the -funsafe-math-optimizations switch. Two-key combo, iykyk ๐Ÿ”‘

  • -malign-double
  • -mno-align-double โ€” control whether GCC aligns double, long double, and long long variables on a two-word boundary or a one-word boundary. Aligning double variables on a two-word boundary produces code that runs somewhat faster on a Pentium โ€” at the expense of more memory. Speed vs. RAM, the eternal trade ๐Ÿ’€

On x86-64, -malign-double is enabled by default. Slay.

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. This is a real "you've been warned" moment bestie ๐Ÿšฉ

  • -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 isn't 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. Just add more bits, it's fine โœจ

In the x86-64 compiler, -m128bit-long-double is the default choice, since its ABI specifies that long double is aligned on a 16-byte boundary.

Notice ๐Ÿ‘€ that neither of these options enable any extra precision over the x87 standard of 80 bits for a long double. It's about alignment, not precision, periodt.

Warning: if you override the default value for your target ABI, this changes the size of structures and arrays containing long double variables, as well as modifying the function calling convention for functions taking long double. Hence they are not binary-compatible with code compiled without that switch. Same energy as the last warning ๐Ÿšจ

  • -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. 80 is just... 80, you know? ๐ŸŒธ
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. Yeah, same warning AGAIN. It's a recurring theme, bestie, they really want you to know ๐Ÿ˜ญ

  • -malign-data=type โ€” control how GCC aligns variables ๐ŸŽ€ The supported values for type are:
    • compat โ€” uses increased alignment value compatible with GCC 4.8 and earlier.
    • abi โ€” uses alignment value as specified by the psABI.
    • cacheline โ€” uses increased alignment value to match the cache line size.

compat is the default. Nostalgia core ๐Ÿ’œ

  • -mlarge-data-threshold=threshold โ€” so when you've got -mcmodel=medium turned on, any data object bigger than threshold gets shipped off to the large data section. ๐Ÿซถ And this value has to be the same across every single object linked into the binary โ€” no vibes-based per-file choices, bestie โ€” and it defaults to 65535.

  • -mrtd โ€” this one's a whole different function-calling convention โœจ: functions that take a fixed number of arguments come back with the ret num instruction, which pops their arguments while returning. That saves one instruction in the caller, because there's nothing left to pop over there. Score. ๐Ÿ’…

You can tell one specific function to use this calling sequence with the function attribute stdcall. And you can override the -mrtd option entirely for a function by using the function attribute cdecl.

โš ๏ธ Warning: this calling convention is incompatible with the one normally used on Unix, so you literally 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 (yes, printf is included in that, iykyk); otherwise incorrect code is generated for calls to those functions. ๐Ÿ˜ญ

On top of that, seriously incorrect code results if you call a function with too many arguments. (Normally, extra arguments are harmlessly ignored โ€” but not here. Periodt.)

  • -mregparm=num โ€” controls how many registers get 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 one specific function with 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. That means the system libraries and startup modules too. No skips. ๐Ÿ™ˆ
  • -msseregparm โ€” uses SSE register passing conventions for float and double arguments and return values. For one specific function, you can control this behavior with the function attribute sseregparm.
โš ๏ธ Warning: if you use this switch then you must build all modules with the same value, including any libraries. Again: system libraries and startup modules are included, bestie.
  • -mvect8-ret-in-mem โ€” returns 8-byte vectors in memory instead of MMX registers. On VxWorks this is the default, to match the ABI of the Sun Studio compilers up until version 12. Only use this option if you need to stay compatible with existing code produced by those previous compiler versions or older versions of GCC. ๐Ÿ‘‘
  • -mpc32
  • -mpc64
  • -mpc80 โ€” these set the 80387 floating-point precision to 32, 64 or 80 bits. When -mpc32 is specified, the significands of results of floating-point operations get 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. ๐Ÿงš

Setting the rounding of floating-point operations to less than the default 80 bits can speed some programs by 2% or more. ๐Ÿ”ฅ But note that some mathematical libraries assume 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. ๐Ÿ’€

  • -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 or -shared is specified โ€” note that -mdaz-ftz will set FTZ/DAZ flags even with -shared. ๐ŸŒธ
  • -mstackrealign โ€” realigns the stack at entry. On the x86, the -mstackrealign option generates an alternate prologue and epilogue that realign 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, which applies to individual functions. ๐Ÿ’…
  • -mpreferred-stack-boundary=num โ€” attempts to keep the stack boundary aligned to a 2 raised to num byte boundary. If -mpreferred-stack-boundary isn't 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 an 8 byte boundary. Since the x86-64 ABI requires 16 byte stack alignment, this is ABI incompatible and is intended to be used in a controlled environment where stack space is an 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 a misaligned stack. In that 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 โ€” and yes, that includes the system libraries and startup modules.
  • -mincoming-stack-boundary=num โ€” assumes the incoming stack is aligned to a 2 raised to num byte boundary. If -mincoming-stack-boundary isn't 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 they suffer significant run time performance penalties. On Pentium III, the Streaming SIMD Extension (SSE) data type __m128 may not work properly if it isn't 16-byte aligned. ๐Ÿ‘€

To ensure proper alignment of these 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. So 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's 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's sensitive to stack space usage โ€” like 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
  • -mavx512fp16
  • -mgfni
  • -mvaes
  • -mwaitpkg
  • -mvpclmulqdq
  • -mavx512bitalg
  • -mmovdiri
  • -mmovdir64b
  • -menqcmd
  • -muintr
  • -mtsxldtrk
  • -mavx512vpopcntdq
  • -mavx512vp2intersect
  • -mavx5124fmaps
  • -mavx512vnni
  • -mavxvnni
  • -mavx5124vnniw
  • -mcldemote
  • -mserialize
  • -mamx-tile
  • -mamx-int8
  • -mamx-bf16
  • -mhreset
  • -mkl
  • -mwidekl
  • -mavxifma
  • -mavxvnniint8
  • -mavxneconvert
  • -mcmpccxadd
  • -mamx-fp16
  • -mprefetchi
  • -mraoint
  • -mamx-complex

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, AVX512-FP16, AVXIFMA, AVXVNNIINT8, AVXNECONVERT, CMPCCXADD, AMX-FP16, PREFETCHI, RAOINT, AMX-COMPLEX or CLDEMOTE extended instruction sets. ๐Ÿ’– Each one 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. Those names can then be used in -mtune-ctrl=feature-list. ๐ŸŒˆ
  • -mtune-ctrl=feature-list โ€” okay so this is the โœจfine grainโœจ dial for x86 code generation features, bestie. feature-list is a comma separated list of feature names. Peep -mdump-tune-features too. When you specify one, the feature gets turned on unless it's got a ^ in front of it, in which case it gets turned off. ๐ŸŽ›๏ธ
Heads up though: -mtune-ctrl=feature-list is meant for GCC developers, iykyk. If you use it you might wander into code paths nobody tested, and that can literally result in compiler ICEs or runtime errors. ๐Ÿ’€ Not a cute look.
  • -mno-default โ€” tells GCC to turn off all the tunable features. ๐Ÿ‘‹ See also -mtune-ctrl=feature-list and -mdump-tune-features.
  • -mcld โ€” makes GCC emit a "cld" instruction in the prologue of functions that use string instructions. Why do we care? Because string instructions depend on the DF flag to pick between autoincrement mode and autodecrement mode, and while the ABI says the DF flag should be cleared when you enter a function, some operating systems simply do not respect that โ€” they don't clear DF in their exception dispatchers. ๐Ÿ™ˆ So the exception handler can get invoked with DF already set, which means wrong direction mode when string instructions run. Messy. This option can be on by default for 32-bit x86 targets if GCC was configured with the --enable-cld configure option. And in that case, you can suppress the "cld" instructions with the -mno-cld compiler option. ๐Ÿซถ
  • -mvzeroupper โ€” instructs GCC to emit a "vzeroupper" instruction before control flow gets transferred out of the function, which minimizes the AVX to SSE transition penalty and removes unnecessary "zeroupper" intrinsics. Transition penalty?? Not on our watch. โœจ
  • -mprefer-avx128 โ€” tells GCC to use 128-bit AVX instructions instead of 256-bit AVX instructions in the auto-vectorizer. Go small or go home. ๐Ÿ’…
  • -mprefer-vector-width=opt โ€” tells GCC to use opt-bit vector width in instructions instead of the default on the platform you picked.
  • -mmove-max=bits โ€” sets the maximum number of bits that can be efficiently moved from memory to memory to bits. Valid values for bits are 128, 256 and 512. ๐Ÿงš
  • -mstore-max=bits โ€” sets the maximum number of bits that can be efficiently stored to memory to bits. Valid values for bits are 128, 256 and 512. ๐Ÿงš
    • none โ€” no extra limitations applied to GCC beyond whatever the selected platform already defines.
    • 128 โ€” prefer 128-bit vector width for instructions.
    • 256 โ€” prefer 256-bit vector width for instructions.
    • 512 โ€” prefer 512-bit vector width for instructions.
  • -mcx16 โ€” lets GCC generate "CMPXCHG16B" instructions in 64-bit code so it can do compare-and-exchange operations on 16-byte aligned 128-bit objects. So useful for atomic updates of data structures that are bigger than one machine word. ๐Ÿ‘‘ The compiler uses this instruction to implement __sync Builtins. But plot twist: for __atomic Builtins operating on 128-bit integers, a library call is always used. Always. No exceptions. ๐Ÿ˜Œ
  • -msahf โ€” enables generation of "SAHF" instructions in 64-bit code. Backstory: early Intel Pentium 4 CPUs with Intel 64 support, before the Pentium 4 G1 step showed up in December 2005, were missing the "LAHF" and "SAHF" instructions that AMD64 supports. Those two are load and store instructions, respectively, for certain status flags. In 64-bit mode, "SAHF" is used to optimize the "fmod", "drem", and "remainder" built-in functions โ€” see Other Builtins for the deets. ๐ŸŽ€
  • -mmovbe โ€” enables use of the "movbe" instruction to implement __builtin_bswap32 and __builtin_bswap64. slay. ๐Ÿ”ฅ
  • -mshstk โ€” the -mshstk option enables shadow stack built-in functions from x86 Control-flow Enforcement Technology (CET). ๐Ÿ›ก๏ธ
  • -mcrc32 โ€” this one enables built-in functions __builtin_ia32_crc32qi, __builtin_ia32_crc32hi, __builtin_ia32_crc32si and __builtin_ia32_crc32di so they generate the "crc32" machine instruction. โญ
  • -mmwait โ€” enables built-in functions __builtin_ia32_monitor, and __builtin_ia32_mwait so they generate the "monitor" and "mwait" machine instructions. ๐ŸŒธ
  • -mrecip โ€” enables use of "RCPSS" and "RSQRTSS" instructions (plus their vectorized variants "RCPPS" and "RSQRTPS") with an extra Newton-Raphson step to bump precision, instead of "DIVSS" and "SQRTSS" (and their vectorized variants) for single-precision floating-point arguments. These instructions only get generated when -funsafe-math-optimizations is enabled together with -ffinite-math-only and -fno-trapping-math. ๐Ÿซถ
Now listen: while the throughput of that sequence is higher than the throughput of the non-reciprocal instruction, the precision of the sequence can be decreased by up to 2 ulp. Like, the inverse of 1.0 equals 0.99999994. ๐Ÿ˜ญ Close enough-ish?

Also note that GCC already implements 1.0f/sqrtf(x) in terms of "RSQRTSS" (or "RSQRTPS") with -ffast-math (or that option combo above), and doesn't need -mrecip.

And also-also: GCC emits that sequence with the 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. periodt. ๐Ÿ’…

  • -mrecip=opt โ€” controls which reciprocal estimate instructions are allowed to be used. opt is a comma-separated list of options, and each one may be preceded by a ! to invert it:
    • all โ€” enable all estimate instructions.
    • default โ€” enable the default instructions, equivalent to -mrecip.
    • none โ€” disable all estimate instructions, equivalent to -mno-recip.
    • div โ€” enable the approximation for scalar division.
    • vec-div โ€” enable the approximation for vectorized division.
    • sqrt โ€” enable the approximation for scalar square root.
    • vec-sqrt โ€” enable the approximation for vectorized square root.

So like, for example, -mrecip=all,!sqrt enables all of the reciprocal approximations, except for square root. See how that works? ๐ŸŽ€

  • -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. no shortcuts bestie. ๐Ÿซถ

GCC currently emits calls to "vmldExp2", "vmldLn2", "vmldLog102", "vmldPow2", "vmldTanh2", "vmldTan2", "vmldAtan2", "vmldAtanh2", "vmldCbrt2", "vmldSinh2", "vmldSin2", "vmldAsinh2", "vmldAsin2", "vmldCosh2", "vmldCos2", "vmldAcosh2", "vmldAcos2", "vmlsExp4", "vmlsLn4", "vmlsLog104", "vmlsPow4", "vmlsTanh4", "vmlsTan4", "vmlsAtan4", "vmlsAtanh4", "vmlsCbrt4", "vmlsSinh4", "vmlsSin4", "vmlsAsinh4", "vmlsAsin4", "vmlsCosh4", "vmlsCos4", "vmlsAcosh4" and "vmlsAcos4" for the corresponding function type when -mveclibabi=svml is used. And it emits "__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. Useful when you're 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. Useful when used with the option -fcf-protection=branch to control ENDBR insertion at the function entry. ๐ŸŽ€
  • -mcet-switch โ€” so by default, CET instrumentation is turned off on switch statements that use a jump table, and indirect branch track is disabled. Since jump tables are stored in read-only memory, this doesn't result in a direct loss of hardening. But if the jump table index is attacker-controlled, the indirect jump may not be constrained by CET. ๐Ÿ˜ณ This option turns on CET instrumentation to enable indirect branch track for switch statements with jump tables, which leads to the jump targets being reachable via any indirect jumps.
  • -mcall-ms2sysv-xlogues โ€” because 64-bit ABIs differ, any Microsoft ABI function that calls a System V ABI function has to consider RSI, RDI and XMM6-15 as clobbered. By default, the code for saving and restoring these registers is emitted inline, which makes for pretty 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, which cuts down function size at the cost of a few extra instructions. trade-off queen. ๐Ÿ‘‘
  • -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 the method using SUB/MOV operations, and it's enabled by default. In some cases disabling it may improve performance, because of improved scheduling and reduced dependencies. โœจ
  • -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?? A notable increase in code size. ๐Ÿ˜ญ And heads up: this switch implies -mno-push-args. periodt.
  • -mthreads โ€” turns on thread-safe exception handling over on MinGW, bestie ๐Ÿ’– and like, if your program depends on that, you have to compile and link everything with -mthreads, no exceptions (pun fully intended). At compile time it defines -D_MT; at link time it pulls in a special little thread helper library, -lmingwthrd, whose whole job is cleaning up all that per-thread exception-handling data. so iconic of it โœจ
  • -mms-bitfields, -mno-ms-bitfields โ€” flip bit-field layout on or off so it matches what the native Microsoft Windows compiler does. ๐ŸชŸ

Okay so here's the tea: if "packed" gets used on a struct, or bit-fields show up at all, the Microsoft ABI might lay that struct out completely differently than GCC normally would ๐Ÿ˜ญ. And especially when you're moving packed data between functions built by GCC and functions built by the native Microsoft compiler โ€” whether that's through a function call or as raw data sitting in a file โ€” sometimes you just need to read either format. So yeah.

This option is on by default for Microsoft Windows targets. lowkey also controllable locally through variable or type attributes. for the deets, go peek at x86 Variable Attributes and x86 Type Attributes ๐Ÿ“š

Now, the Microsoft structure layout algorithm is honestly pretty simple, except for the bit-field packing part, which is giving chaos ๐Ÿ‘€. The padding and alignment of struct members โ€” and whether a bit-field can straddle a storage-unit boundary โ€” all comes down to these rules:

  1. Structure members get stored sequentially in the order they're declared, periodt: the first member lands at the lowest memory address, the last member at the highest.
  2. Every data object has an alignment requirement. For literally everything except structures, unions, and arrays, that requirement is either the size of the object or the current packing size (whichever you set with 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. And every object gets an offset so that:
offset % alignment_requirement == 0
  1. Adjacent bit-fields get 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 bit-fields' common alignment requirements.

Now MSVC reads zero-length bit-fields like this:

  1. If a zero-length bit-field gets inserted between two bit-fields that would normally be coalesced, then they are not coalesced.

like, for example:

struct
 {
   unsigned long bf_1 : 12;
   unsigned long : 0;
   unsigned long bf_2 : 12;
 } t1;

t1 is 8 bytes with that zero-length bit-field in there. Remove it and t1 shrinks to 4 bytes. the way that zero-length bit-field is just occupying space for no reason ๐Ÿ’€

  1. If a zero-length bit-field comes after a bit-field, foo, and the alignment of that zero-length bit-field is greater than the member that follows it, bar, then bar gets aligned as if it were 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 gets placed at offset 2 instead of offset 1. So t2 comes out to size 4. For t3, that zero-length bit-field doesn't mess with the alignment of bar at all โ€” and therefore doesn't change the size of the struct either.

Keeping all that in mind, here's what you really need to clock:

  1. If a zero-length bit-field follows a normal bit-field, the type of the zero-length bit-field can affect the alignment of the structure as a whole. For example, t2 is 4 bytes in size, since the zero-length bit-field follows a normal bit-field and is of type short.
  2. Even if a zero-length bit-field isn't followed by a normal bit-field, it can still affect the alignment of the structure:
struct
 {
   char foo : 6;
   long : 0;
 } t4;

Here, t4 takes up 4 bytes. yeah. one bit-field. four bytes. ๐Ÿซ 

  1. Zero-length bit-fields that follow non-bit-field members get ignored:
struct
 {
   char foo;
   long : 0;
   char bar;
 } t5;

Here, t5 takes up 2 bytes. slay ๐Ÿ’…


  • -mno-align-stringops โ€” don't align the destination of inlined string operations. This one shrinks your code size and boosts performance when the destination is already aligned but GCC has no idea about it ๐Ÿ™ˆ
  • -minline-all-stringops โ€” by default GCC only inlines string operations when the destination is known to be aligned to at least a 4-byte boundary. This turns on way more inlining and grows your code size, but it can speed up code that leans on fast "memcpy" and "memset" for short lengths. It also enables inline expansion of "strlen" for all pointer alignments. go off โœจ
  • -minline-stringops-dynamically โ€” for string operations of unknown size, use run-time checks: inline code for small blocks, library call for large blocks. best of both worlds fr fr ๐ŸŒˆ
  • -mstringop-strategy=alg โ€” override the internal decision heuristic for which algorithm to use when inlining string operations. The allowed values for alg are:
    • rep_byte
    • rep_4byte
    • rep_8byte โ€” expand using the 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 โ€” override the internal decision heuristic that decides whether "__builtin_memcpy" should be inlined, and which inline algorithm to use when the expected size of the copy operation is known. strategy is a comma-separated list of alg:max_size:dest_align triplets. alg is specified in -mstringop-strategy, and 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 have to be in increasing order. The minimal byte size for alg is 0 for the first triplet, and "max_size + 1" of the preceding range for the rest. ๐Ÿ“
  • -mmemset-strategy=strategy โ€” same energy as -mmemcpy-strategy=, except it's here to control "__builtin_memset" expansion instead.
  • -momit-leaf-frame-pointer โ€” don't keep the frame pointer in a register for leaf functions. This skips all those instructions that save, set up, and restore frame pointers, and frees up an extra register in leaf functions ๐ŸŽ€ Just know that -fomit-leaf-frame-pointer yanks the frame pointer out of leaf functions entirely, which might make debugging harder. ๐Ÿซถ
  • -mtls-direct-seg-refs, -mno-tls-direct-seg-refs โ€” controls whether TLS variables can be accessed using offsets from the TLS segment register (%gs for 32-bit, %fs for 64-bit), or whether the thread base pointer has to be added in. Whether that's 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. Heads up though: on x86 architectures the attribute "ms_hook_prologue" isn't possible right now when you're using -mfentry and -pg. ๐Ÿ˜ญ
  • -mrecord-mcount, -mno-record-mcount โ€” if profiling is active (-pg), generate a __mcount_loc section holding pointers to each profiling call. super 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. Handy when they're meant to get patched in later dynamically. lowkey probably 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 โ€” it does not touch sibling calls ending with jump. Valid types are none (don't instrument), call (generate a call to __return__), or nop5 (generate a 5 byte nop). ๐ŸŽฏ
  • -mrecord-return, -mno-record-return โ€” generate a __return_loc section pointing to all the return instrumentation code.
  • -mfentry-name=name โ€” set the name of the __fentry__ symbol that gets called at function entry for -pg -mfentry functions. โœ๏ธ
  • -mfentry-section=name โ€” set the name of the section used to record -mrecord-mcount calls (default is __mcount_loc). ๐ŸŒธ
  • -mskip-rax-setup, -mno-skip-rax-setup โ€” when generating code for the x86-64 architecture with SSE extensions disabled, -mskip-rax-setup lets you skip setting up the RAX register when there are no variable arguments passed in vector registers.
Warning: since the RAX register is what avoids 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. still though. bestie. be careful.
  • -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 the dividend and the divisor are within the range 0 to 255, an 8-bit unsigned integer divide gets used instead of a 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 โ€” bestie, this one tells the compiler to build stack protection code with the canary sitting at guard. Your options are global (canary lives in a global) or tls (canary lives per-thread in the TLS block โ€” that's the default ๐Ÿ’…). Heads up though: it only does literally anything when -fstack-protector or -fstack-protector-all is also on. Otherwise it's just vibing.
  • -mstack-protector-guard-reg=reg, -mstack-protector-guard-offset=offset โ€” ok so when you picked tls up there, these two get to shine โœจ. -mstack-protector-guard-reg=reg says which segment register to use as the base register for reading the canary โ€” that's %fs or %gs. -mstack-protector-guard-offset=offset says from what offset from that base register you're reading. Defaults for both? Whatever the relevant ABI says, no cap. ๐Ÿซถ
  • -mgeneral-regs-only โ€” generate code that only touches general-purpose registers. This stops the compiler from using floating-point, vector, mask and bound registers. Very "we keep it simple here" energy. ๐ŸŽ€
  • -mrelax-cmpxchg-loop โ€” so when we're emitting a compare-and-swap loop for __sync Builtins and __atomic Builtins that don't have a native instruction, this optimizes for the highly contended case: it issues an atomic load before the CMPXCHG instruction, and it uses the PAUSE instruction to save CPU power when restarting the loop. Your CPU said thank you. ๐Ÿ”ฅ
  • -mindirect-branch=choice โ€” convert indirect call and jump with choice. Default is keep, which keeps indirect call and jump unmodified (aka no notes, untouched ๐Ÿ™ˆ). 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. Not compatible fr fr, they do not slay together. Also 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. 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. And 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. That's the whole thing, she's short and iconic. ๐Ÿ‘‘
  • -mharden-sls=choice โ€” generate code to mitigate against straight line speculation (SLS) with choice. 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. Pick your fighter, or pick all and let her cook. ๐ŸŒˆ
  • -mindirect-branch-cs-prefix โ€” add 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, to allow them to be replaced with lfence; call *%r8-r15 or lfence; jmp *%r8-r15 at run-time. Very specific, very demure, very mindful. ๐Ÿ’…

These -m switches are supported in addition to the above on x86-64 processors in 64-bit environments. So yes bestie, there's more. ๐Ÿ˜Œ

  • -m32, -m64, -mx32, -m16, -miamcu โ€” generate code for a 16-bit, 32-bit or 64-bit environment. Let's break it down because there's a lot going on and all of it matters:
    • 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 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. No -m32, no -miamcu, that's the rule. ๐Ÿšจ
  • -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. She said "no red zone slander but also no red zone." ๐Ÿ“
  • -mcmodel=small โ€” generate code for the small code model: the program and its symbols must be linked in the lower 2 GB of the address space. Pointers are 64 bits. Programs can be statically or dynamically linked. This is the default code model, the main character, the one that shows up without being asked. ๐ŸŒŸ
  • -mcmodel=kernel โ€” generate code for the kernel code model. The kernel runs in the negative 2 GB of the address space. This model has to be used for Linux kernel code. Not optional, bestie, it's mandatory behavior. ๐Ÿซก
  • -mcmodel=medium โ€” generate code for the medium model: the program is linked in the lower 2 GB of the address space. Small symbols are also placed there. Symbols with sizes larger than -mlarge-data-threshold are put into large data or BSS sections and can be located above 2GB. Programs can be statically or dynamically linked.
  • -mcmodel=large โ€” generate code for the large model. This model makes no assumptions about addresses and sizes of sections. She's free, she's unbothered, she assumes nothing. ๐Ÿฆ‹
  • -maddress-mode=long โ€” generate 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 โ€” generate code for short address mode. Only supported for 32-bit and x32 environments. It's the default address mode for 32-bit and x32 environments. Matching set, we love a pair. ๐ŸŽ€
  • -mneeded, -mno-needed โ€” emit GNU_PROPERTY_X86_ISA_1_NEEDED GNU property for Linux target to indicate the micro-architecture ISA level required to execute the binary. iykyk. โœจ
  • -mno-direct-extern-access โ€” without -fpic nor -fPIC, always use the GOT pointer to access external symbols. With -fpic or -fPIC, treat access to protected symbols as local symbols. The default is -mdirect-extern-access.
Warning: shared libraries compiled with -mno-direct-extern-access and executable compiled with -mdirect-extern-access may not be binary compatible if protected symbols are used in shared libraries and executable. This is the "do not mix these, I am begging you" corner of the manual. ๐Ÿ’€
  • -munroll-only-small-loops โ€” controls conservative small loop unrolling. It's default enabled by O2, and unrolls loop with less than 4 insns by 1 time. Explicit -f[no-]unroll-[all-]loops would disable this flag to avoid any unintended unrolling behavior that user does not want. Nobody wants surprise unrolling, periodt. ๐Ÿ™…
  • -mlam=choice โ€” LAM (linear-address masking) allows special bits in the pointer to be used for metadata. The default is none. With u48, pointer bits in positions 62:48 can be used for metadata; with u57, pointer bits in positions 62:57 can be used for metadata. Metadata bits said "we're here too." ๐Ÿ’œ

๐Ÿ’ป x86 Windows Options ๐Ÿ’ป

These additional options are available for Microsoft Windows targets:

  • -mconsole โ€” this option specifies that a console application is to be generated, by instructing the linker to set the PE header subsystem type required for console applications. This option is available for Cygwin and MinGW targets and is enabled by default on those targets.
  • -mdll โ€” available for Cygwin and MinGW targets. It specifies that a DLL โ€” a dynamic link library โ€” is to be generated, enabling the selection of the required runtime startup object and entry point. ๐Ÿ’…
  • -mnop-fun-dllimport โ€” available for Cygwin and MinGW targets. It specifies that the "dllimport" attribute should be ignored. Just straight up ignored, bestie, not read, not answered, left on seen. ๐Ÿ™ˆ
  • -mthreads โ€” available for MinGW targets. It specifies that MinGW-specific thread support is to be used.
  • -municode โ€” available for MinGW-w64 targets. It causes the "UNICODE" preprocessor macro to be predefined, and chooses Unicode-capable runtime startup code. ๐ŸŒˆ
  • -mwin32 โ€” available for Cygwin and MinGW targets. It specifies that the typical Microsoft Windows predefined macros are to be set in the pre-processor, but does not influence the choice of runtime library/startup code. Macros yes, runtime no. Stay in your lane. ๐ŸŽ€
  • -mwindows โ€” available for Cygwin and MinGW targets. It specifies that a GUI application is to be generated by instructing the linker to set the PE header subsystem type appropriately. โœจ
  • -fno-set-stack-executable โ€” available for MinGW targets. It specifies that 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, since there the User32 API, which is used to set executable privileges, isn't available.
  • -fwritable-relocated-rdata โ€” available for MinGW and Cygwin targets. It specifies that relocated-data in read-only section is put into the .data section. This is a necessary for older runtimes not supporting modification of .rdata sections for pseudo-relocation.
  • -mpe-aligned-commons โ€” available for Cygwin and MinGW targets. It specifies that the GNU extension to the PE file format that permits the correct alignment of COMMON variables should be used when generating code. It is enabled by default if GCC detects that the target assembler found during configuration supports the feature. ๐Ÿ”

See also under x86 Options for standard options.


๐Ÿฆ‹ 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 Xstormy16 moment. ๐ŸŒธ

๐ŸŒบ Xtensa Options ๐ŸŒบ

These options are supported for Xtensa targets:

  • -mconst16, -mno-const16 โ€” turns on/off using CONST16 instructions to load constant values. Real talk: CONST16 currently isn't a standard option from Tensilica. When it's enabled, CONST16 instructions are always used in place of the standard L32R instructions. And it's only enabled by default if the L32R instruction isn't available. Periodt. ๐Ÿ’…
  • -mfused-madd, -mno-fused-madd โ€” enable/disable fused multiply/add and multiply/subtract instructions in the floating-point option. Heads up: this has no effect if the floating-point option isn't also enabled. Disabling fused multiply/add and multiply/subtract instructions forces the compiler to use separate instructions for the multiply and add/subtract operations. Lowkey useful when you need strict IEEE 754-compliant results: the fused multiply add/subtract instructions don't round the intermediate result, so they produce 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. โœจ
  • -mserialize-volatile, -mno-serialize-volatile โ€” when this option is enabled, GCC inserts MEMW instructions before volatile memory references to guarantee sequential consistency. Default is -mserialize-volatile. Use -mno-serialize-volatile to omit the MEMW instructions. ๐Ÿซถ
  • -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. Default is -mno-text-section-literals, which places literals in a separate section in the output file. That 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, literals are interspersed in the text section 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 also control the treatment of literal pools. Default is -mno-auto-litpools, which places literals in a separate section in the output file unless -mtext-section-literals is used. With -mauto-litpools, the literals are interspersed in the text section by the assembler. The compiler does not 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. ๐Ÿ’€
  • -mtarget-align, -mno-target-align โ€” when 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. 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 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. Default is -mno-longcalls. This option should be used in programs where the call target can potentially be out of range. 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. Note that the assembler uses an indirect call for every cross-file call, not just those that really are out of range. ๐Ÿ˜ญ
  • -mabi=name โ€” generate code for the specified ABI. Permissible values are: call0, windowed. The default ABI is chosen by the Xtensa core configuration. โœจ
  • -mabi=call0 โ€” when 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 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. ๐ŸŽ€
  • -mextra-l32r-costs=n โ€” specify an extra cost of instruction RAM/ROM access for L32R instructions, in clock cycles. This affects, when optimizing for speed, whether loading a constant from literal pool using L32R or synthesizing the constant from a small one with a couple of arithmetic instructions. The default value is 0. ๐Ÿ”ฅ

๐ŸŒˆ zSeries Options ๐ŸŒˆ

These are listed under

๐ŸŒธ ENVIRONMENT ๐ŸŒธ

ok so this section is all about the env vars that change how GCC does its thing ๐Ÿ’ซ Some of them work by giving you a place to stash directories or prefixes to look in when hunting down files. Others are just, like, telling GCC about the general vibe of the compilation environment.

Also real quick bestie โ€” you can also point at search spots with options like -B, -I and -L. Those win over anything you set in the environment, and the environment wins over whatever GCC's own configuration says. Priority order, periodt. ๐Ÿ‘‘

  • LANG, LC_CTYPE, LC_MESSAGES, LC_ALL โ€” these control how GCC handles localization info, which is the whole reason it can play nice with different national conventions. GCC peeks at the locale categories LC_CTYPE and LC_MESSAGES if it was configured to do so. You can set these to any value your installation supports. A super typical one is en_GB.UTF-8 โ€” that's English in the United Kingdom, encoded in UTF-8. ๐Ÿ‡ฌ๐Ÿ‡งโœจ

LC_CTYPE is the one that specifies character classification. GCC uses it to figure out character boundaries in a string, and this is needed because some multibyte encodings contain quote and escape characters that would otherwise get read as a string end or an escape. messy ๐Ÿ’€

LC_MESSAGES specifies the language for diagnostic messages.

If LC_ALL is set, it overrides both LC_CTYPE and LC_MESSAGES. If it's not set, then LC_CTYPE and LC_MESSAGES just default to whatever LANG says. And if none of these are set at all? GCC falls back to traditional C English behavior. classic.

  • TMPDIR โ€” if set, this tells GCC which directory to use for temporary files. GCC generates temp files to hold the output of one compilation stage that's about to be fed into the next stage as input. The example given is the output of the preprocessor, which becomes the input to the compiler proper. it's giving relay race ๐Ÿƒโ€โ™€๏ธ
  • GCC_COMPARE_DEBUG โ€” setting this is nearly equivalent to passing -fcompare-debug to the compiler driver. For the whole story, go see the documentation for that option.
  • GCC_EXEC_PREFIX โ€” if it's set, this is the prefix used in the names of the subprograms the compiler executes. No slash gets added when this prefix is combined with the subprogram name, but you absolutely may specify a prefix that ends with a slash if that's your thing ๐Ÿ’…

If GCC_EXEC_PREFIX isn't set, GCC tries to figure out a suitable prefix based on the pathname it was invoked with.

If GCC can't find the subprogram using the prefix you gave, it goes and looks in the usual places instead.

The default value of GCC_EXEC_PREFIX is prefix/lib/gcc/, where prefix is the prefix of the installed compiler. In many cases prefix is the value of "prefix" when you ran the configure script.

Other prefixes given with -B take precedence over this one.

This prefix is also used to find files like crt0.o that get used for linking.

And it's used in a genuinely unusual way when finding 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 make an alternate directory name. So with -Bfoo/, GCC searches foo/bar just before it searches the standard directory /usr/local/lib/bar. And if a standard directory begins with the configured prefix, then the value of that prefix gets replaced by GCC_EXEC_PREFIX when looking for header files. lowkey wild ๐Ÿคฏ

  • COMPILER_PATH โ€” its value is a colon-separated list of directories, much like PATH. GCC tries these directories when searching for subprograms, but only if it couldn't find the subprograms using GCC_EXEC_PREFIX.
  • LIBRARY_PATH โ€” same deal, colon-separated list of directories, much like PATH. When GCC is configured as a native compiler, it tries the directories you list when searching for special linker files, if it couldn't find them using GCC_EXEC_PREFIX. Linking with GCC also uses these directories when hunting for ordinary libraries for the -l option โ€” but directories specified with -L come first, no exceptions. ๐Ÿฅ‡
  • LANG โ€” (yep, again) this one passes locale info to the compiler. One way that info gets used is deciding 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, these values of LANG are recognized:
    • C-JIS โ€” recognize JIS characters.
    • C-SJIS โ€” recognize SJIS characters.
    • C-EUCJP โ€” recognize EUCJP characters.

And if LANG is not defined, or it's set to literally anything else, then the compiler uses mblen and mbtowc as defined by the default locale to recognize and translate multibyte characters. ๐Ÿˆถ

  • GCC_EXTRA_DIAGNOSTIC_OUTPUT โ€” if you set this to one of the values below, extra text gets emitted to stderr whenever fix-it hints are emitted. Just so you know, -fdiagnostics-parseable-fixits and -fno-diagnostics-parseable-fixits take precedence over this environment variable.
    • fixits-v1 โ€” emit parseable fix-it hints, equivalent to -fdiagnostics-parseable-fixits. In particular, columns are expressed as a count of bytes, starting at byte 1 for the initial column.
    • fixits-v2 โ€” same as fixits-v1, except 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 one's value is a list of directories separated by a special character, much like PATH, where header files get looked for. That special character, PATH_SEPARATOR, is target-dependent and decided at GCC build time. For Microsoft Windows-based targets it's a semicolon, and for almost literally every other target it's a colon.

CPATH gives a list of directories searched as if they were specified with -I, but after any paths given with -I options on the command line. This environment variable is used no matter which language is being preprocessed.

The rest of these environment variables only apply when preprocessing the particular language they name. Each one gives a list of directories 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 tells the compiler to search its current working directory. Empty elements can sit at the beginning or the end of a path. For instance, if the value of CPATH is :/special/include, that does the same thing as -I. -I/special/include. agent of chaos behavior, honestly ๐Ÿซถ

  • DEPENDENCIES_OUTPUT โ€” if this is set, its value specifies how to output dependencies for Make, based on the non-system header files the compiler processed. System header files get ignored in the dependency output.

The value can be just a file name โ€” in that case the Make rules get written to that file, and the target name is guessed from the source file name. Or the value can have the form file target, in which case the rules are written to the file file using target as the target name.

Basically, this env var is equivalent to combining the options -MM and -MF, with an optional -MT switch thrown in 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 set, its value specifies a UNIX timestamp to use in place of the current date and time in the __DATE__ and __TIME__ macros, so the embedded timestamps become reproducible. so iconic for reproducible builds ๐Ÿ•ฐ๏ธ

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. It's 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, like the last modification time of the source or package, and it should be set by the build process.

๐Ÿ’€ BUGS ๐Ÿ’€

Want the instructions on reporting bugs? Go look at:

/usr/share/doc/gcc-13/README.Bugs
(In the original that's written as a file:// URL โ€” <file:///usr/share/doc/gcc-13/README.Bugs> โ€” same place either way bestie ๐Ÿ’…)

๐ŸŒŸ 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 โ€” and nobody wants subtle defects, that's the worst kind ๐Ÿ˜ญ Supplying them in cases where they're not necessary is innocuous though, so no stress. Also: -shared suppresses the addition of startup code to alter the floating-point environment, as done with -ffast-math, -Ofast or -funsafe-math-optimizations on some targets.

๐Ÿซถ SEE ALSO ๐Ÿซถ

gpl(7), gfdl(7), fsf-funding(7), cpp(1), gcov(1), as(1), ld(1), gdb(1) and the Info entries for gcc, cpp, as, ld, binutils and gdb. the whole friend group fr fr ๐ŸŒˆ

๐Ÿ‘‘ AUTHOR ๐Ÿ‘‘

See the Info entry for gcc, or:

https://gcc.gnu.org/onlinedocs/gcc/Contributors.html

...for contributors to GCC. (In the original that's written as a URL in angle brackets: <https://gcc.gnu.org/onlinedocs/gcc/Contributors.html>.) shoutout to the contributors ๐Ÿ’œ

Copyright (c) 1988-2023 Free Software Foundation, Inc.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "GNU General Public License" and "Funding Free Software", the Front-Cover texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the gfdl(7) man page.

(a) The FSF's Front-Cover Text is:

A GNU Manual

(b) The FSF's Back-Cover Text is:

You have freedom to copy and modify this GNU Manual, like GNU
software.  Copies published by the Free Software Foundation raise
funds for GNU development.

and that's a wrap on the whole entire manpage bestie ๐Ÿฅน you read all 122 parts, that's main character energy no cap ๐Ÿ’…โœจ this little cutie was put out by gcc-13 and it's dated 2026-09-10 โ€” go compile something iconic with it ๐ŸŒธ๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from