GCC(1)

๐Ÿ“ฆ
version 13.5.0+git10516 ยท 2 versions
, in opensuse-leap 16.0

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

๐ŸŒธ NAME ๐ŸŒธ

gcc - GNU project C and C++ compiler

Itโ€™s giving โ€œthe compiler icon,โ€ bestie. ๐ŸŽ€

๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

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

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

๐ŸŒˆ DESCRIPTION ๐ŸŒˆ

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

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

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

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

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

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

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

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

๐Ÿ‘‘ OPTIONS ๐Ÿ‘‘

๐ŸŽ€ Option Summary ๐ŸŽ€

Here is a summary of all the options, grouped by type. Explanations are in the following sections. Itโ€™s the cheat sheet era. ๐Ÿ’…

โœจ 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]

โš ๏ธ Warning Options โš ๏ธ

Okay bestie, breathe. This is the big one. This is the entire warning catalogue, and yes, it is giving "my mom's grocery list but make it compilers." These are all the little flags that make GCC tell you stuff. Some yell. Some whisper. Some just vibe. Every single one is here, in order, no cap. ๐Ÿซถ

  • -fsyntax-only โ€” checks the syntax and then dips โœจ
  • -fmax-errors=n โ€” cap the error count at n, we're not doing infinity today
  • -Wpedantic โ€” the hall monitor of warnings ๐ŸŽ€
  • -pedantic-errors โ€” hall monitor, but now it's serious
  • -w โ€” the "la la la I can't hear you" flag ๐Ÿ’€
  • -Wextra โ€” extra warnings, extra love
  • -Wall โ€” the one everyone types first, iconic behavior ๐Ÿ‘‘
  • -Wabi=n โ€” ABI tea โ˜•
  • -Waddress โ€” address her directly
  • -Wno-address-of-packed-member โ€” the no version, respectfully ๐Ÿ’…
  • -Waggregate-return โ€” aggregates, returning them, drama
  • -Walloc-size-larger-than=byte-size โ€” watch that byte-size number bestie
  • -Walloc-zero โ€” zero allocations, zero chill
  • -Walloca โ€” alloca is main character energy ๐ŸŒˆ
  • -Walloca-larger-than=byte-size โ€” again with the byte-size
  • -Wno-aggressive-loop-optimizations โ€” not me being aggressive
  • -Warith-conversion โ€” arithmetic conversion arc
  • -Warray-bounds โ€” stay in your lane, array
  • -Warray-bounds=n โ€” same but with a n because levels โœจ
  • -Warray-compare โ€” comparing arrays, bold of you
  • -Wno-attributes โ€” attributes? not today
  • -Wattribute-alias=n โ€” alias with a n on top
  • -Wno-attribute-alias โ€” nope to that too
  • -Wno-attribute-warning โ€” the quiet one ๐Ÿ™ˆ
  • -Wbidi-chars=[none|unpaired|any|ucn] โ€” pick your mode: none, unpaired, any, or ucn
  • -Wbool-compare โ€” bool comparisons, very true/false of you
  • -Wbool-operation โ€” bool operations slay
  • -Wno-builtin-declaration-mismatch โ€” no mismatch parties today
  • -Wno-builtin-macro-redefined โ€” macro said what it said
  • -Wc90-c99-compat โ€” C90 to C99 compatibility era ๐Ÿ•ฐ๏ธ
  • -Wc99-c11-compat โ€” C99 to C11, the sequel
  • -Wc11-c2x-compat โ€” C11 to C2x, the threequel
  • -Wc++-compat โ€” C++ compatibility, we contain multitudes
  • -Wc++11-compat โ€” C++11 era
  • -Wc++14-compat โ€” C++14 era
  • -Wc++17-compat โ€” C++17 era
  • -Wc++20-compat โ€” C++20 era
  • -Wno-c++11-extensions โ€” no extensions, C++11 division
  • -Wno-c++14-extensions โ€” C++14 division, also no
  • -Wno-c++17-extensions โ€” you get the idea
  • -Wno-c++20-extensions โ€” yes, also this one
  • -Wno-c++23-extensions โ€” and this one, she's new ๐Ÿ’œ
  • -Wcast-align โ€” casts, aligned
  • -Wcast-align=strict โ€” strict mode, behave
  • -Wcast-function-type โ€” cast that function, I dare you
  • -Wcast-qual โ€” qualifiers keep their meaning, tyvm
  • -Wchar-subscripts โ€” chars as subscripts, chaotic
  • -Wclobbered โ€” the word itself is a threat ๐Ÿ’€
  • -Wcomment โ€” comment section moderation
  • -Wno-complain-wrong-lang โ€” not complaining about the wrong language, growth ๐ŸŒฑ
  • -Wconversion โ€” conversions get called out
  • -Wno-coverage-mismatch โ€” no coverage mismatch discourse
  • -Wno-cpp โ€” not the preprocessor's problem
  • -Wdangling-else โ€” dangling else, dangling earrings, same energy ๐ŸŽ€
  • -Wdangling-pointer โ€” pointer just hanging around
  • -Wdangling-pointer=n โ€” same, but with a n
  • -Wdate-time โ€” date and time check โฐ
  • -Wno-deprecated โ€” deprecated? never heard of her
  • -Wno-deprecated-declarations โ€” the declarations version of never heard of her
  • -Wno-designated-init โ€” designated init and no commentary
  • -Wdisabled-optimization โ€” optimization said "not today"
  • -Wno-discarded-array-qualifiers โ€” qualifiers, discarded, array flavored
  • -Wno-discarded-qualifiers โ€” the plain version
  • -Wno-div-by-zero โ€” division by zero, we simply don't discuss it ๐Ÿ™ˆ
  • -Wdouble-promotion โ€” double promotion, she's climbing the ranks ๐Ÿ“ˆ
  • -Wduplicated-branches โ€” twins but branches
  • -Wduplicated-cond โ€” twins but conditions
  • -Wempty-body โ€” empty body, no thoughts head empty
  • -Wno-endif-labels โ€” endif said no labels
  • -Wenum-compare โ€” enums comparing each other, petty
  • -Wenum-conversion โ€” enums converting, glow up
  • -Wenum-int-mismatch โ€” mismatch, enum vs int ๐Ÿ’…
  • -Werror โ€” every warning is now an ERROR. good luck bestie ๐Ÿ”ฅ
  • -Werror=* โ€” the wildcard version, truly unhinged
  • -Wexpansion-to-defined โ€” expansion to defined, she's a journey
  • -Wfatal-errors โ€” one error and we're DONE ๐Ÿ˜ญ
  • -Wfloat-conversion โ€” floats converting
  • -Wfloat-equal โ€” floats being equal, suspicious
  • -Wformat โ€” format strings get the spotlight
  • -Wformat=2 โ€” format level two, because levels
  • -Wno-format-contains-nul โ€” nul in format, no comment
  • -Wno-format-extra-args โ€” extra args, extra baggage
  • -Wformat-nonliteral โ€” nonliteral format, mysterious โœจ
  • -Wformat-overflow=n โ€” overflow, with a n
  • -Wformat-security โ€” security check, very demure, very mindful
  • -Wformat-signedness โ€” signedness discourse
  • -Wformat-truncation=n โ€” truncation plus n
  • -Wformat-y2k โ€” y2k called, she wants her warning back ๐Ÿ’€
  • -Wframe-address โ€” frame address, framed
  • -Wframe-larger-than=byte-size โ€” that byte-size again
  • -Wno-free-nonheap-object โ€” no freeing non-heap today
  • -Wno-if-not-aligned โ€” not aligned, not addressed
  • -Wno-ignored-attributes โ€” ignored attributes, ignored accordingly
  • -Wignored-qualifiers โ€” qualifiers getting ignored, rude
  • -Wno-incompatible-pointer-types โ€” incompatible pointers? in this economy?
  • -Wimplicit โ€” implicit things being loud
  • -Wimplicit-fallthrough โ€” fallthrough, careful ๐Ÿ’…
  • -Wimplicit-fallthrough=n โ€” fallthrough with a n
  • -Wno-implicit-function-declaration โ€” no implicit function declarations, growth
  • -Wno-implicit-int โ€” no implicit int
  • -Winfinite-recursion โ€” infinite recursion, we LOVE a loop ๐Ÿ”
  • -Winit-self โ€” init self, self care
  • -Winline โ€” inline, in line, in love
  • -Wno-int-conversion โ€” leave int conversion alone
  • -Wint-in-bool-context โ€” int in a bool context, choose a lane
  • -Wno-int-to-pointer-cast โ€” no intโ†’pointer casts
  • -Wno-invalid-memory-model โ€” memory model said valid actually
  • -Winvalid-pch โ€” PCH said invalid
  • -Winvalid-utf8 โ€” utf8 no longer valid, embarrassing
  • -Wno-unicode โ€” unicode, unbothered
  • -Wjump-misses-init โ€” jump missed init, relatable
  • -Wlarger-than=byte-size โ€” byte-size, again, love her
  • -Wlogical-not-parentheses โ€” logical not + parentheses = chaos combo
  • -Wlogical-op โ€” logical operators doing logic
  • -Wlong-long โ€” long long, extra long ๐Ÿ’…
  • -Wno-lto-type-mismatch โ€” LTO said no mismatch today
  • -Wmain โ€” main character, literally โญ
  • -Wmaybe-uninitialized โ€” maybe ๐Ÿ˜ญ
  • -Wmemset-elt-size โ€” memset element size check
  • -Wmemset-transposed-args โ€” transposed args, we've all been there
  • -Wmisleading-indentation โ€” misleading indentation, evil actually ๐Ÿ’€
  • -Wmissing-attributes โ€” attributes missing, come back
  • -Wmissing-braces โ€” braces missing, put them back ๐ŸŽ€
  • -Wmissing-field-initializers โ€” field initializers went MIA
  • -Wmissing-format-attribute โ€” format attribute absent
  • -Wmissing-include-dirs โ€” include dirs, where'd they go
  • -Wmissing-noreturn โ€” noreturn missing, ironic
  • -Wno-missing-profile โ€” profile missing and nobody's talking
  • -Wno-multichar โ€” multichar, mind your business
  • -Wmultistatement-macros โ€” macros with multiple statements, bold
  • -Wnonnull โ€” non-null check
  • -Wnonnull-compare โ€” comparing against nonnull, why
  • -Wnormalized=[none|id|nfc|nfkc] โ€” modes: none, id, nfc, nfkc
  • -Wnull-dereference โ€” null dereference, the classic ๐Ÿ˜ญ
  • -Wno-odr โ€” ODR, but she said no
  • -Wopenacc-parallelism โ€” OpenACC parallelism era
  • -Wopenmp-simd โ€” OpenMP SIMD, we parallel here
  • -Wno-overflow โ€” overflow, not today
  • -Woverlength-strings โ€” strings too long, she's extra
  • -Wno-override-init-side-effects โ€” side effects, declined
  • -Wpacked โ€” packed, compact, cute
  • -Wno-packed-bitfield-compat โ€” bitfield compat, no thanks
  • -Wpacked-not-aligned โ€” packed but not aligned, pick one
  • -Wpadded โ€” padded, cozy
  • -Wparentheses โ€” the parentheses committee has notes ๐ŸŽ€
  • -Wno-pedantic-ms-format โ€” the MS format pedantry has been excused
  • -Wpointer-arith โ€” pointer arithmetic doing math
  • -Wno-pointer-compare โ€” pointers compared? not on my watch
  • -Wno-pointer-to-int-cast โ€” no pointerโ†’int casts
  • -Wno-pragmas โ€” pragmas, unbothered
  • -Wno-prio-ctor-dtor โ€” ctor/dtor priority, we simply moved on
  • -Wredundant-decls โ€” redundant declarations, say it once bestie
  • -Wrestrict โ€” restrict, respectfully
  • -Wno-return-local-addr โ€” local address returned? not discussed ๐Ÿ™ˆ
  • -Wreturn-type โ€” return type check, do it right
  • -Wno-scalar-storage-order โ€” storage order, no comment
  • -Wsequence-point โ€” sequence points, stay in sequence
  • -Wshadow โ€” spooky variable names ๐Ÿ‘ป
  • -Wshadow=global โ€” global spooky
  • -Wshadow=local โ€” local spooky
  • -Wshadow=compatible-local โ€” compatible local spooky
  • -Wno-shadow-ivar โ€” ivar shadowing, blocked
  • -Wno-shift-count-negative โ€” negative shift count, not today
  • -Wno-shift-count-overflow โ€” shift count overflow, also not today
  • -Wshift-negative-value โ€” negative value shifted, hmm
  • -Wno-shift-overflow โ€” shift overflow, declined
  • -Wshift-overflow=n โ€” shift overflow with a n
  • -Wsign-compare โ€” sign comparison discourse
  • -Wsign-conversion โ€” sign conversion era
  • -Wno-sizeof-array-argument โ€” sizeof on array argument, let it go
  • -Wsizeof-array-div โ€” sizeof divided, math girlie
  • -Wsizeof-pointer-div โ€” sizeof on pointer, divided, chaotic
  • -Wsizeof-pointer-memaccess โ€” sizeof with pointer memaccess
  • -Wstack-protector โ€” stack protector, she protects ๐ŸŒธ
  • -Wstack-usage=byte-size โ€” byte-size strikes again
  • -Wstrict-aliasing โ€” strict aliasing, no shortcuts
  • -Wstrict-aliasing=n โ€” strict aliasing with a n
  • -Wstrict-overflow โ€” strict overflow, strict vibes
  • -Wstrict-overflow=n โ€” strict overflow with a n
  • -Wstring-compare โ€” strings compared
  • -Wno-stringop-overflow โ€” stringop overflow, off the table
  • -Wno-stringop-overread โ€” no overreading
  • -Wno-stringop-truncation โ€” no truncation commentary
  • -Wstrict-flex-arrays โ€” flexible arrays but strict ๐Ÿ’…
  • -Wsuggest-attribute=[pure|const|noreturn|format|malloc] โ€” pick one: pure, const, noreturn, format, malloc
  • -Wswitch โ€” switch statements get a look ๐Ÿ‘€
  • -Wno-switch-bool โ€” switch on bool, no thoughts
  • -Wswitch-default โ€” default case check
  • -Wswitch-enum โ€” enum switches, she's thorough
  • -Wno-switch-outside-range โ€” outside range, outside jurisdiction
  • -Wno-switch-unreachable โ€” unreachable, unreachable
  • -Wsync-nand โ€” sync nand, iconic name actually
  • -Wsystem-headers โ€” system headers count now, beware ๐Ÿ’€
  • -Wtautological-compare โ€” comparing a thing to itself, we've all done it
  • -Wtrampolines โ€” trampolines, jumping ๐Ÿฆ˜
  • -Wtrigraphs โ€” trigraphs, vintage
  • -Wtrivial-auto-var-init โ€” trivial auto var init
  • -Wtsan โ€” TSan said hello
  • -Wtype-limits โ€” type limits, boundaries
  • -Wundef โ€” undef, undefined, unbothered
  • -Wuninitialized โ€” uninitialized, the classic ๐Ÿ˜ญ
  • -Wunknown-pragmas โ€” unknown pragmas, mysterious
  • -Wunsuffixed-float-constants โ€” float constants without a suffix, rude
  • -Wunused โ€” the whole "you're not using that" section ๐Ÿ’…
  • -Wunused-but-set-parameter โ€” set but not used, a parameter tragedy
  • -Wunused-but-set-variable โ€” same but a variable
  • -Wunused-const-variable โ€” const variable, unused, sad
  • -Wunused-const-variable=n โ€” with a n, obviously
  • -Wunused-function โ€” function just sitting there
  • -Wunused-label โ€” label with nothing to do
  • -Wunused-local-typedefs โ€” local typedefs gathering dust
  • -Wunused-macros โ€” macro unused, ghosted
  • -Wunused-parameter โ€” parameter unused, relatable
  • -Wno-unused-result โ€” unused result, no comment
  • -Wunused-value โ€” value unused, wasteful
  • -Wunused-variable โ€” variable unused, we been knew
  • -Wno-varargs โ€” varargs, not today
  • -Wvariadic-macros โ€” variadic macros, so many args
  • -Wvector-operation-performance โ€” vector ops, performance era โšก
  • -Wvla โ€” VLA, variable length, variable vibes
  • -Wvla-larger-than=byte-size โ€” VLA + byte-size, iconic combo
  • -Wno-vla-larger-than โ€” the no version of that
  • -Wvolatile-register-var โ€” volatile register var, rare sighting
  • -Wwrite-strings โ€” write strings, careful
  • -Wxor-used-as-pow โ€” xor pretending to be pow, we see you ๐Ÿ’€
  • -Wzero-length-bounds โ€” zero length, zero bounds, zero problems

๐Ÿ”ฎ Static Analyzer Options ๐Ÿ”ฎ

This next batch is the analyzer squad. She reads your code, builds a whole little world in her head, and then tells you what she thinks. Very main character, very "I did my own research." ๐Ÿ’œ

  • -fanalyzer โ€” the analyzer herself, the moment ๐ŸŒŸ
  • -fanalyzer-call-summaries โ€” call summaries, she takes notes
  • -fanalyzer-checker=name โ€” pick a checker by name
  • -fno-analyzer-feasibility โ€” feasibility checks off
  • -fanalyzer-fine-grained โ€” fine grained, she's detailed
  • -fno-analyzer-state-merge โ€” no state merging
  • -fno-analyzer-state-purge โ€” no state purging
  • -fno-analyzer-suppress-followups โ€” no suppressing follow-ups
  • -fanalyzer-transitivity โ€” transitivity, very math of her
  • -fno-analyzer-undo-inlining โ€” inlining stays undone
  • -fanalyzer-verbose-edges โ€” verbose edges, edges with lore
  • -fanalyzer-verbose-state-changes โ€” state changes but verbose
  • -fanalyzer-verbosity=level โ€” set the level, queen of settings
  • -fdump-analyzer โ€” dump it, bestie ๐Ÿ’พ
  • -fdump-analyzer-callgraph โ€” dump the callgraph
  • -fdump-analyzer-exploded-graph โ€” exploded graph, dramatic much
  • -fdump-analyzer-exploded-nodes โ€” exploded nodes
  • -fdump-analyzer-exploded-nodes-2 โ€” the sequel
  • -fdump-analyzer-exploded-nodes-3 โ€” the threequel
  • -fdump-analyzer-exploded-paths โ€” exploded paths
  • -fdump-analyzer-feasibility โ€” feasibility dump
  • -fdump-analyzer-json โ€” json flavored dump โœจ
  • -fdump-analyzer-state-purge โ€” state purge dump
  • -fdump-analyzer-stderr โ€” dump to stderr
  • -fdump-analyzer-supergraph โ€” supergraph, super dump
  • -fdump-analyzer-untracked โ€” the untracked ones get dumped too
  • -Wno-analyzer-double-fclose โ€” double fclose, muted
  • -Wno-analyzer-double-free โ€” double free, muted
  • -Wno-analyzer-exposure-through-output-file โ€” exposure via output file, shh
  • -Wno-analyzer-exposure-through-uninit-copy โ€” exposure via uninit copy, also shh
  • -Wno-analyzer-fd-access-mode-mismatch โ€” fd access mode mismatch, no comment
  • -Wno-analyzer-fd-double-close โ€” fd double close, we closed that chapter
  • -Wno-analyzer-fd-leak โ€” fd leak, plugged
  • -Wno-analyzer-fd-phase-mismatch โ€” fd phase mismatch, off the table
  • -Wno-analyzer-fd-type-mismatch โ€” fd type mismatch, nope
  • -Wno-analyzer-fd-use-after-close โ€” use after close, not discussed
  • -Wno-analyzer-fd-use-without-check โ€” use without check, declined
  • -Wno-analyzer-file-leak โ€” file leak, contained
  • -Wno-analyzer-free-of-non-heap โ€” freeing non-heap, let it be
  • -Wno-analyzer-imprecise-fp-arithmetic โ€” imprecise fp arithmetic, whatever
  • -Wno-analyzer-infinite-recursion โ€” infinite recursion, we've made peace ๐Ÿ•Š๏ธ
  • -Wno-analyzer-jump-through-null โ€” jumping through null, blocked
  • -Wno-analyzer-malloc-leak โ€” malloc leak, muzzled
  • -Wno-analyzer-mismatching-deallocation โ€” mismatching deallocation, quiet
  • -Wno-analyzer-null-argument โ€” null argument, hushed
  • -Wno-analyzer-null-dereference โ€” null dereference, silenced
  • -Wno-analyzer-out-of-bounds โ€” out of bounds, out of mind
  • -Wno-analyzer-possible-null-argument โ€” possible null argument, also quiet
  • -Wno-analyzer-possible-null-dereference โ€” possible null deref, quiet
  • -Wno-analyzer-putenv-of-auto-var โ€” putenv of auto var, moving on
  • -Wno-analyzer-shift-count-negative โ€” negative shift count, no comment
  • -Wno-analyzer-shift-count-overflow โ€” shift count overflow, no comment
  • -Wno-analyzer-stale-setjmp-buffer โ€” stale setjmp buffer, stale discourse
  • -Wno-analyzer-tainted-allocation-size โ€” tainted allocation size, declined
  • -Wno-analyzer-tainted-assertion โ€” tainted assertion, also declined
  • -Wno-analyzer-tainted-array-index โ€” tainted array index, no
  • -Wno-analyzer-tainted-divisor โ€” tainted divisor, no
  • -Wno-analyzer-tainted-offset โ€” tainted offset, no
  • -Wno-analyzer-tainted-size โ€” tainted size, no
  • -Wanalyzer-too-complex โ€” the analyzer telling you you're too complex ๐Ÿ’€
  • -Wno-analyzer-unsafe-call-within-signal-handler โ€” unsafe call in a signal handler, muted
  • -Wno-analyzer-use-after-free โ€” use after free, we don't talk about it
  • -Wno-analyzer-use-of-pointer-in-stale-stack-frame โ€” stale stack frame pointer, quiet
  • -Wno-analyzer-use-of-uninitialized-value โ€” uninitialized value use, silenced
  • -Wno-analyzer-va-arg-type-mismatch โ€” va_arg type mismatch, hushed
  • -Wno-analyzer-va-list-exhausted โ€” va_list exhausted, she's tired
  • -Wno-analyzer-va-list-leak โ€” va_list leak, contained
  • -Wno-analyzer-va-list-use-after-va-end โ€” va_list use after va_end, no comment
  • -Wno-analyzer-write-to-const โ€” writing to const, blocked
  • -Wno-analyzer-write-to-string-literal โ€” writing to a string literal, absolutely not ๐Ÿ™ˆ

๐Ÿ“ C and Objective-C-only Warning Options ๐Ÿ“

C girlies and Objective-C girlies, this section is for you specifically. Everyone else can scroll. ๐Ÿ’…

  • -Wbad-function-cast โ€” bad function cast, we've all had one
  • -Wmissing-declarations โ€” declarations went missing
  • -Wmissing-parameter-type โ€” parameter type absent
  • -Wmissing-prototypes โ€” prototypes MIA
  • -Wnested-externs โ€” nested externs, nesting doll energy ๐Ÿช†
  • -Wold-style-declaration โ€” old style declaration, vintage
  • -Wold-style-definition โ€” old style definition, also vintage
  • -Wstrict-prototypes โ€” strict prototypes, she has standards
  • -Wtraditional โ€” traditional, classic, timeless ๐ŸŒธ
  • -Wtraditional-conversion โ€” traditional conversion, old money
  • -Wdeclaration-after-statement โ€” declaration after statement, the audacity
  • -Wpointer-sign โ€” pointer sign, sign of the times

๐Ÿฆ‹ Debugging Options ๐Ÿฆ‹

Okay so debugging is literally where you become the detective. These flags are your magnifying glass, your little notebook, your "wait what happened here" toolkit. -g girlies rise. ๐Ÿ”

  • -g โ€” the debugging flag, the blueprint, the icon ๐Ÿ‘‘
  • -glevel โ€” set a level, because levels
  • -gdwarf โ€” DWARF flavored debug info
  • -gdwarf-version โ€” DWARF but pick a version
  • -gbtf โ€” BTF debug info, so specific, love her
  • -gctf โ€” CTF debug info
  • -gctflevel โ€” CTF plus a level
  • -ggdb โ€” GDB-specific debug info, bestie behavior ๐Ÿซถ
  • -grecord-gcc-switches โ€” record those GCC switches, receipts kept
  • -gno-record-gcc-switches โ€” no receipts, no problem
  • -gstrict-dwarf โ€” strict DWARF
  • -gno-strict-dwarf โ€” not strict DWARF, she's chill
  • -gas-loc-support โ€” as loc support, on
  • -gno-as-loc-support โ€” as loc support, off
  • -gas-locview-support โ€” as locview support, on
  • -gno-as-locview-support โ€” as locview support, off
  • -gcolumn-info โ€” column info, column queen
  • -gno-column-info โ€” no column info
  • -gdwarf32 โ€” DWARF 32, compact
  • -gdwarf64 โ€” DWARF 64, extra
  • -gstatement-frontiers โ€” statement frontiers, very frontiers
  • -gno-statement-frontiers โ€” frontiers, declined
  • -gvariable-location-views โ€” variable location views
  • -gno-variable-location-views โ€” no views today
  • -ginternal-reset-location-views โ€” internal reset locations views
  • -gno-internal-reset-location-views โ€” the no version
  • -ginline-points โ€” inline points, points made
  • -gno-inline-points โ€” points retracted
  • -gvms โ€” VMS debug info, retro
  • -gz[=type] โ€” compressed debug info, optional type ๐ŸŽ€
  • -gsplit-dwarf โ€” split DWARF, she's divided but thriving
  • -gdescribe-dies โ€” describe the DIEs, tell us everything
  • -gno-describe-dies โ€” DIEs undescribed
  • -fdebug-prefix-map=old=new โ€” map old to new, remap era
  • -fdebug-types-section โ€” types section, sectioned
  • -fno-eliminate-unused-debug-types โ€” keep those unused debug types, don't eliminate
  • -femit-struct-debug-baseonly โ€” emit struct debug, base only
  • -femit-struct-debug-reduced โ€” emit struct debug, reduced
  • -femit-struct-debug-detailed[=spec-list] โ€” detailed, optionally with a spec-list โœจ
  • -fno-eliminate-unused-debug-symbols โ€” unused debug symbols stay
  • -femit-class-debug-always โ€” class debug, always
  • -fno-merge-debug-strings โ€” no merging those debug strings
  • -fno-dwarf2-cfi-asm โ€” no DWARF2 CFI asm
  • -fvar-tracking โ€” var tracking, she's watching ๐Ÿ‘€
  • -fvar-tracking-assignments โ€” var tracking but assignments

โšก Optimization Options โšก

Okay bestie, breathe. This is the roster โ€” every optimization switch GCC has, dumped in one glorious pile. No skips, no "you don't need those", nothing. Copy-paste to your heart's content. ๐Ÿซถ

-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]]]] -fmin-function-alignment=[n]
-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

A couple of faves to call out so you don't get lost in there ๐Ÿ’–

  • --param name=value โ€” the "set a knob by name" escape hatch, sitting right before the -O crew.
  • -O, -O0, -O1, -O2, -O3, -Os, -Ofast, -Og, -Oz โ€” yes, all nine of them, chilling at the very bottom of the list. The main characters, honestly. ๐Ÿ‘‘

๐Ÿฉบ Program Instrumentation Options ๐Ÿฉบ

Now we're in the "watch what my program is actually doing" zone: profiling, coverage, sanitizers, stack protection, function instrumentation. It's giving ๐Ÿ•ต๏ธโ€โ™€๏ธ investigator era.

-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

Do notice the -fsanitize=style family and -fsanitize-recover=style / -fsanitize-trap=style โ€” those take a style argument, they're not just vibes. Same for -fcf-protection=[full|branch|return|none|check] and -fvtable-verify=[std|preinit|none], all spelled out with their exact options above. ๐ŸŽ€


๐Ÿ“ Preprocessor Options ๐Ÿ“

The preprocessor is the part of the pipeline that shows up before anyone else and starts rewriting stuff โ€” very "let me just fix your text rq" energy. ๐Ÿ˜ญ

-Aquestion=answer -A-question[=answer] -C  -CC  -Dmacro[=defn] -dD
-dI  -dM  -dN  -dU -fdebug-cpp  -fdirectives-only
-fdollars-in-identifiers -fexec-charset=charset
-fextended-identifiers -finput-charset=charset  -flarge-source-files
-fmacro-prefix-map=old=new -fmax-include-depth=depth
-fno-canonical-system-headers  -fpch-deps  -fpch-preprocess
-fpreprocessed  -ftabstop=width  -ftrack-macro-expansion
-fwide-exec-charset=charset  -fworking-directory -H  -imacros file
-include file -M  -MD  -MF  -MG  -MM  -MMD  -MP  -MQ  -MT
-Mno-modules -no-integrated-cpp  -P  -pthread  -remap -traditional
-traditional-cpp  -trigraphs -Umacro  -undef -Wp,option
-Xpreprocessor option

Note the two weirdos at the bottom: -Wp,option and -Xpreprocessor option โ€” your little smuggling routes for handing something straight to the preprocessor. And -Aquestion=answer / -A-question[=answer] are the assertion ones, in case you were like "wait, -A?" yeah. ๐Ÿ’…


๐Ÿ›  Assembler Options ๐Ÿ› 

Two, count 'em, two. Both are "pass this along to the assembler" moves.

  • -Wa,option โ€” hands option over to the assembler.
  • -Xassembler option โ€” same idea, different spelling, one option per flag.

๐Ÿ”— Linker Options ๐Ÿ”—

This is the section where you and the linker have a little chat about how your program gets put together. ๐Ÿซถ

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

Little tour: object-file-name is literally a file name, -llibrary is your -l flag, and at the end you've got -Wl,option and -Xlinker option for forwarding stuff to the linker itself. There's also -T script, -u symbol, -z keyword, -e entry, --entry=entry โ€” all right there. No cap. ๐Ÿ”ฅ


๐Ÿ“ Directory Options ๐Ÿ“

The "where do I find your stuff" section. Search paths, sysroots, include dirs โ€” all of it. ๐Ÿฆ‹

-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

Careful with -I- โ€” that one's got a trailing dash and it is absolutely not a typo, so don't be out here "cleaning it up". ๐Ÿ™ˆ


๐Ÿงฌ Code Generation Options ๐Ÿงฌ

The nitty-gritty of what the compiler is actually allowed to emit: registers, exceptions, PIC, struct returns, enums, visibility, all that good stuff. It's giving low-level main character. ๐Ÿ‘‘

-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

Yes -fpic, -fPIC, -fpie and -fPIE are all four separate things โ€” case matters, bestie, always. Also -fvisibility=[default|internal|hidden|protected] takes exactly those four values, spelled with a lowercase i in internal. ๐ŸŽ€


๐Ÿงช Developer Options ๐Ÿงช

The dev-only zone. Dumps, logs, debug counters, statistics, timing reports โ€” this is what you turn on when you're like "why is my compiler doing that??" ๐Ÿ˜ญ

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

Tiny heads-up because I know you're gonna squint at these: -fdisable-ipa-pass_name and -fdisable-tree-pass_name use the bare pass_name spelling, while -fdisable-rtl-pass-name=range-list, -fdisable-tree-pass-name=range-list and -fenable-kind-pass=range-list use the =range-list shape. They're different forms, both listed, both real. ๐Ÿ’€

Also: -fchecking and -fchecking=n are two separate entries, -fdump-final-insns[=file] has that optional =file, and -frandom-seed=string wants a string, not a number. And at the very end, -save-temps, -save-temps=cwd, -save-temps=obj and -time[=file] close it out. ๐ŸŒธ


And that's the developer pile done โ€” but bestie, we are so not done. There's more page, more options, more everything. Keep scrolling. ๐Ÿฆ‹

๐Ÿ› ๏ธ Machine-Dependent Options ๐Ÿ› ๏ธ

Ok bestie, brace yourself โ€” this is the big one. Every architecture GCC has ever had opinions about, and every flag that comes with it. It's a lot. Like, a LOT lot. ๐Ÿซ  But no skimming, because this is literally the whole menu, spelled exactly right, so you can ctrl-F your heart out and find your fave. ๐Ÿ’…


๐Ÿ’œ AArch64 Options ๐Ÿ’œ

The 64-bit ARM squad. Absolute main characters.

  • -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 โœจ

Niche? Yes. Iconic? Also yes.

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

A whole three flags. Short king energy, we respect it. ๐Ÿ‘‘

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

๐Ÿฆ‹ ARC Options ๐Ÿฆ‹

This list is long, bestie. Deep breaths.

  • -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 classic. The blueprint. Watch how many times -mcpu, -march and -mtune show up in this one โ€” it's giving recurring guest star. โญ

  • -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 girlies rise up. Note that the last two are -W warnings, not -m flags โ€” don't come for me, that's just how the original rolls. ๐Ÿ™ˆ

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

The -mno- twins are out in full force here. Every vibe has its opposite. ๐Ÿ’ซ

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

Five flags. Five. Honestly? Efficient. We love a minimal aesthetic. โœจ

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

๐Ÿ’€ CRIS Options ๐Ÿ’€

Careful here โ€” -sim and -sim2 are not wearing the m. Copy them exactly, bestie, no autocorrect. ๐Ÿซถ

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

Look at this lineup. -EB and -EL are the short lil nicknames of -mbig-endian and -mlittle-endian here โ€” they're both listed, so both go in the notes. ๐Ÿ“

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

Ok this one is unhinged and I mean that lovingly. It's a whole different dialect โ€” mostly no m prefix at all, plus -F, -gused and -gfull thrown in at the end. And yes, some entries literally repeat in the original (-sectobjectsymbols, -segs_read_only_addr, -segs_read_write_addr each show up twice) โ€” I'm keeping them both times because that's what the page says. Don't @ me. ๐Ÿ˜ญ

  • -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 ๐Ÿ‘‘

-mieee has lore and I refuse to elaborate. Anyway, here's the whole crew:

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

Modern, sleek, kernel-adjacent. Obsessed. ๐Ÿ’–

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

๐ŸŽ€ FR30 Options ๐ŸŽ€

Two flags. That's it. That's the whole personality. ๐ŸŽ€

  • -msmall-model
  • -mno-lsim

๐Ÿฆ‹ FT32 Options ๐Ÿฆ‹

Six little guys, just vibing.

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

๐ŸŒธ FRV Options ๐ŸŒธ

A truly disrespectful number of flags. Respectfully. Look at all those -mno- pairs again โ€” the duality of man. ๐Ÿ’ซ

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

Note -mTLS and -mtls are both there and they are not the same thing โ€” casing matters, bestie, always. ๐Ÿ‘€


๐Ÿ’œ GNU/Linux Options ๐Ÿ’œ

The C-library-and-Android chapter. Also -tno-android-cc and -tno-android-ld are two more of the no-m weirdos. ๐Ÿซถ

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

โœจ H8/300 Options โœจ

Tiny names, big energy. -mh, -ms, -mn โ€” one letter each and they mean business.

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

๐ŸŒˆ HPPA Options ๐ŸŒˆ

The -mno- counterparts are back and they brought friends. Also -nolibdld, -static and -threads are chillin' at the end without the usual prefix. ๐Ÿ’…

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

This is the "min-latency vs max-throughput" and "sched" section and it goes hard. Buckle up. ๐ŸŒช๏ธ

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

Every single one of these ends in -enabled. Consistency queen. ๐Ÿ‘‘

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

๐Ÿ“ LoongArch Options ๐Ÿ“

Another gorgeous long one, and the -mno- twins came to play too. ๐Ÿ’–

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

Ends on a -G num with a space in it, so type it exactly like that. ๐Ÿซถ

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

And we're closing this part out with the cutest tiny list of all. Three flags. Slay. ๐Ÿ’…

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

โ€ฆand yeah we're STILL in the machine-specific options ๐Ÿ’€ like the OPTIONS section never ends and honestly? iconic. Buckle up bestie, the rest of this is basically a tour of every CPU family ever. No cap.


๐ŸŽ€ M680x0 Options ๐ŸŽ€

Motorola 68000 family hours โœจ here's the whole roster, don't make me repeat myself:

  • -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
Heads up: -mno-bitfield and -mnobitfield are both real and they are not the same string. Yes I'm serious. Type carefully ๐Ÿซถ

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

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

Okay so this one is enter-the-group-chat-and-scroll-for-an-hour long ๐Ÿ˜ญ but every single one is real and you need them, so here we go, no skipping:

  • -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
Real talk: -mno-gopt and -mmno-mcu are spelled exactly like that in the list, bestie, and -Gnum is capital-G-no-space. I'm not fixing them, I'm copying them, that's the whole job. ๐Ÿ™ˆ

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

Short and sweet, we love a low-maintenance icon:

  • -meb
  • -mel
  • -mmul.x
  • -mno-crt0
-mmul.x has a literal dot in it. Not a typo on my end, that's the actual string. ๐Ÿ’…

๐ŸŒˆ 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=
Notice the ones ending in a bare =. That's a value slot waiting for you, bestie, don't leave it empty and then act surprised. ๐Ÿ˜ญ

๐Ÿ’œ 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
See that -G num with an actual space? MIPS had -Gnum glued together. Two different worlds, both valid, do not come for me. โญ

๐Ÿ”ฅ Nvidia PTX Options ๐Ÿ”ฅ

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

  • -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 ๐Ÿ‘‘

See RS/6000 and PowerPC Options.

That's it. That's the whole entry. She's a cross-reference and she said "go look over there" ๐Ÿ’€ (and yes, "over there" is literally the next-but-a-few section, keep scrolling babe)


๐ŸŒŸ PRU Options ๐ŸŒŸ

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

๐Ÿฆ‹ RISC-V Options ๐Ÿฆ‹

Okay queen energy, this group is STACKED:

  • -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
The three -mstack-protector-guard* ones are a little family โ€” =guard, -reg=reg, -offset=offset. They travel together, iykyk ๐Ÿซถ

๐Ÿ’€ 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 โšก

Okay. Deep breath. This is the big one, the main character of the architecture list, and I'm giving you every single flag because that's the assignment ๐Ÿ’…

  • -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
  • -msplit-patch-nops
  • -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
Two things I refuse to smooth over: it's -mno-mpower8-fusion but -mno-power8-vector (different, I checked, they really are like that) ๐Ÿ™ˆ and -G num here also has the space, same as Nios II, unlike MIPS's -Gnum. Typing is a skill bestie.

๐ŸŽ€ 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
PSA: -fpu and -nofpu have NO leading m. Everyone else in this whole page has an m. RX woke up and chose chaos and honestly? Respect. ๐Ÿ’…

๐ŸŒˆ S/390 and zSeries Options ๐ŸŒˆ

  • -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
Last one's got a comma in the value โ€” -mhotpatch=halfwords,halfwords, two whole slots. Nobody said this was gonna be easy, bestie ๐Ÿซถ

๐ŸŒธ SH Options ๐ŸŒธ

okay bestie, these are all the SH-flavored -m knobs. they're literally just the names, no blurbs attached โ€” treat it like a aesthetics moodboard for your SH target ๐Ÿ’…

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

โ˜€๏ธ Solaris 2 Options โ˜€๏ธ

solaris squad, your flags are here ๐Ÿซถ

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

๐Ÿ’ซ SPARC Options ๐Ÿ’ซ

the whole SPARC situation, no cap โœจ

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

the x86 list is so long, bestie, it's giving encyclopedia ๐Ÿ˜ญ but every single one is here, untouched:

-mtune=cpu-type  -march=cpu-type
-mtune-ctrl=feature-list  -mdump-tune-features  -mno-default
-mfpmath=unit -masm=dialect  -mno-fancy-math-387 -mno-fp-ret-in-387
-m80387  -mhard-float  -msoft-float -mno-wide-multiply  -mrtd
-malign-double -mpreferred-stack-boundary=num
-mincoming-stack-boundary=num -mcld  -mcx16  -msahf  -mmovbe
-mcrc32 -mmwait -mrecip  -mrecip=opt -mvzeroupper  -mprefer-avx128
-mprefer-vector-width=opt -mmove-max=bits -mstore-max=bits -mmmx
-msse  -msse2  -msse3  -mssse3  -msse4.1  -msse4.2  -msse4  -mavx
-mavx2  -mavx512f  -mavx512pf  -mavx512er  -mavx512cd  -mavx512vl
-mavx512bw  -mavx512dq  -mavx512ifma  -mavx512vbmi  -msha  -maes
-mpclmul  -mfsgsbase  -mrdrnd  -mf16c  -mfma  -mpconfig  -mwbnoinvd
-mptwrite  -mprefetchwt1  -mclflushopt  -mclwb  -mxsavec  -mxsaves
-msse4a  -m3dnow  -m3dnowa  -mpopcnt  -mabm  -mbmi  -mtbm  -mfma4
-mxop -madx  -mlzcnt  -mbmi2  -mfxsr  -mxsave  -mxsaveopt  -mrtm
-mhle  -mlwp -mmwaitx  -mclzero  -mpku  -mthreads  -mgfni  -mvaes
-mwaitpkg -mshstk -mmanual-endbr -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

๐ŸชŸ 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 ๐Ÿ‘‘

head over to S/390 and zSeries Options, bestie โ€” that's where this party's at ๐Ÿซถ


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

okay so compiling? it's a whole journey, not a single step. there are up to four stages, and they always go in this exact order:

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

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 combines all the object files โ€” the ones it just newly compiled and the ones you passed in as input โ€” into an executable file. periodt ๐Ÿ’…


the suffix lore ๐Ÿฆ‹

for any given input file, the file name suffix is what decides which kind of compilation happens. here's the whole vibe check:

  • file.c โ€” C source code that must be preprocessed.
  • file.i โ€” C source code that should not be preprocessed.
  • file.ii โ€” C++ source code that should not be preprocessed.
  • file.m โ€” Objective-C source code. heads up: you must link with the libobjc library to make an Objective-C program actually 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. also 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 (that's the 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. (yes bestie, it's literally listed again โ€” that's what the page says ๐Ÿ˜ญ)
  • 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). these files also get called specs.
  • file.adb โ€” Ada source code file containing a library unit body (a subprogram or package body). these files also get called bodies.
  • file.s โ€” Assembler code.
  • file.S, file.sx โ€” Assembler code that must be preprocessed.
  • other โ€” an object file to be fed straight into linking. any file name with no recognized suffix gets treated this way.

picking your language on purpose ๐Ÿ’…

you can also 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 (exactly like they are if -x has not been used at all).

so if you only want some of the stages โ€” mood, honestly โ€” 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. and ngl, watch out: some combinations (for example, -x cpp-output -E) instruct gcc to do nothing at all ๐Ÿ’€
  • -c โ€” okay so this one is the classic โ€œcompile/assemble but do not linkโ€ girlie ๐Ÿ’…. 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. Lowkey iconic behavior.

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

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 so continuing the dump-prefix saga, because we're still not done, bestie ๐Ÿ’…

When you compile and then link from multiple input files, a dumppfx โ€” whether it's the default one or one you explicitly specified โ€” also goes through that dumpbase- transformation we talked about above (think the compilation of foo.c and bar.c from earlier, but without -c). If neither -dumpdir nor -dumpbase are given, then the linker output base name (minus auxdropsuf if you specified one, or the executable suffix otherwise) plus a dash gets appended to the default dumppfx instead. But heads up โ€” unlike the earlier linking cases:

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

does not append the output name main to dumppfx, because -dumpdir was explicitly specified. The whole goal here is that your explicitly-specified dumppfx may contain the specified output name as part of the prefix if you want it to; only an explicitly-specified -dumpbase gets combined with it, so that a meaningful option doesn't just get straight-up discarded ๐Ÿซถ

When you compile and then link from a single input file, the linker output base name only gets appended to the default dumppfx as described above if it doesn't share the base name with that single input file name. This was already covered in the single-input linking cases above, but not with an explicit -dumpdir that blocks the combination โ€” even if it gets overridden by -save-temps=*:

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 exactly as -save-temps=cwd ultimately requested โœจ

So summing it all up into an intuitive-but-slightly-imprecise data flow, because that's how we roll: the primary output name gets broken into a directory part and a basename part; dumppfx is set to the directory part unless it's overridden by -dumpdir or -save-temps=*; and dumpbase is set to the basename part unless it's overridden by -dumpbase. If there are multiple inputs or you're 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 the suffix, and the auxiliary output suffix; dump output names are only different in that the suffix from dumpbase is retained. Iconic, honestly ๐Ÿ‘‘

Now, 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 โ€” gets passed down with a trailing period replacing the compiler-added dash (if there is one) as a -dumpdir option to lto-wrapper; and since it's involved in linking, this program doesn't normally get any -dumpbase and -dumpbase-ext, and it just ignores them.

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

  • -v โ€” Prints (on standard error output) the commands executed to run the stages of compilation. It also prints the version number of the compiler driver program, plus the version numbers of the preprocessor and the compiler proper. Very "show me your receipts" energy ๐Ÿ”ฅ
  • -### โ€” Like -v, except the commands are not executed and the arguments get quoted unless they contain only alphanumeric characters or ./-_. This one's useful for shell scripts that want to capture the driver-generated command lines. Perfect for the little script girlies ๐Ÿ’…
  • --help โ€” Prints (on standard output) a description of the command-line options that gcc understands. If -v is also specified, then --help also gets passed on to the various processes invoked by gcc, so they can display the command-line options they accept. And if -Wextra has also been specified (prior to the --help option), then command-line options that have no documentation associated with them are also displayed. No option left behind ๐Ÿซถ
  • --target-help โ€” Prints (on standard output) a description of target-specific command-line options for each tool. For some targets, extra target-specific information may also be printed โœจ
  • --help={class|[^]qualifier}[,...] โ€” Prints (on standard output) a description of the command-line options understood by the compiler that fit into all the specified classes and qualifiers. These are the supported classes:
    • optimizers โ€” Display all of the optimization options supported by the compiler.
    • warnings โ€” Display all of the options controlling warning messages produced by the compiler.
    • target โ€” Display target-specific options. Unlike the --target-help option, though, target-specific options of the linker and assembler are not displayed. This is 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.
    • common โ€” Display the options that are common to all languages.

And these are the supported qualifiers:

  • undocumented โ€” Display only those options that are undocumented.
  • joined โ€” Display options taking an argument that appears after an equal sign in the same continuous piece of text, 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
The argument to --help= should not consist solely of inverted qualifiers. Don't do it, bestie ๐Ÿ˜ญ

Combining several classes is possible, although this usually restricts the output so much that there's nothing to display. 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. Each successive use displays its requested class of options, skipping those that have already been displayed. And if --help is also specified anywhere on the command line, then it takes precedence over any --help= option ๐Ÿ‘‘

If the -Q option appears on the command line before the --help= option, then the descriptive text displayed by --help= 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

Literally the diff-your-way-to-truth pipeline, we love to see it ๐ŸŒธ

  • --version โ€” Displays 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 the gcc program instead returns with the numerically highest error produced by any phase that returns an error indication. The C, C++, and Fortran front ends return 4 if an internal compiler error is encountered.
  • -pipe โ€” Uses 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 at all ๐Ÿซถ
  • -specs=file โ€” Processes file after the compiler reads in the standard specs file, in order to override the defaults that the gcc driver program uses when determining what switches to pass to cc1, cc1plus, as, ld, etc. More than one -specs=file can be specified on the command line, and they're processed in order, from left to right โœจ
  • -wrapper โ€” Invokes all subcommands under a wrapper program. The name of the wrapper program and its parameters are passed as a comma-separated list.
gcc -c t.c -wrapper gdb,--args

This invokes all subprograms of gcc under gdb --args, so the invocation of cc1 is gdb --args cc1 .... Very "debug-ception" of it ๐Ÿ’€

  • -ffile-prefix-map=old=new โ€” When compiling files residing in directory old, records 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. See also -fmacro-prefix-map, -fdebug-prefix-map, -fprofile-prefix-map and -fcanon-prefix-map. Queen of not snitching on your home directory ๐ŸŒˆ
  • -fcanon-prefix-map โ€” For the -f*-prefix-map options, normally the comparison of 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 option causes such comparisons to be done on canonicalized paths of old and the referenced filename. Canonicalize first, ask questions never ๐ŸŽ€

  • -fplugin=name.so โ€” 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 when it comes to parsing arguments (peep -fplugin-arg-name-key=value below ๐Ÿ‘‡). Every plugin is supposed to define the callback functions listed in the Plugins API, no cap.
  • -fplugin-arg-name-key=value โ€” defines an argument called key with a value of value, for the plugin called name. That's it, that's the whole vibe ๐ŸŽ€.
  • -fdump-ada-spec[-slim] โ€” for C and C++ source and include files, generates the corresponding Ada specs ๐Ÿ’….
  • -fada-spec-parent=unit โ€” works together with -fdump-ada-spec[-slim] (above) to generate Ada specs as child units of parent unit. Teamwork makes the dream work ๐Ÿซถ.
  • -fdump-go-spec=file โ€” for input files in any language, generates the corresponding Go declarations in file. It spits out Go "const", "type", "var", and "func" declarations, which lowkey can be a really useful way to start writing a Go interface to code that's written in some other language ๐Ÿฆ‹.
  • @file โ€” reads command-line options from file. The options it reads get inserted in place of the original @file option. And if file doesn't exist, or can't be read? Then the option is treated literally and not removed โ€” it just stays there, living its truth ๐Ÿ’€.

Options inside file are separated by whitespace. You can sneak a whitespace character into an option by wrapping the entire option in either single or double quotes ๐ŸŽ€. Any character at all (backslash included!) can be included by prefixing it with a backslash. And plot twist: the file can itself contain additional @file options โ€” any of those get processed recursively ๐ŸŒ€.


๐ŸŒธ Compiling C++ Programs ๐ŸŒธ

C++ source files conventionally use one of these 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 exact same way you would for compiling C programs (usually with the name gcc). Same energy, different language, iykyk ๐Ÿ’ซ.

But bestie, listen โ€” using gcc does not add the C++ library. That's the plot twist nobody warns you about ๐Ÿ˜ญ.

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 under the name c++ ๐ŸŽ€.

When you compile C++ programs, you may specify many of the same command-line options you'd use for compiling programs in any language; or command-line options that are meaningful for C and related languages; or options that are meaningful only for C++ programs. Pick your fighter ๐Ÿ’….


๐Ÿฆ‹ Options Controlling C Dialect ๐Ÿฆ‹

The following options control the dialect of C (or languages derived from C, like C++, Objective-C and Objective-C++) that the compiler accepts. Vibe check for your compiler, basically โญ:

  • -ansi โ€” in C mode, this is equivalent to -std=c90. In C++ mode, it's 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) โ€” things like the "asm" and "typeof" keywords, and predefined macros such as "unix" and "vax" that identify the type of system you're 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. Not them getting cancelled fr.

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's useful to put them in header files that might get 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 you need -Wpedantic in addition to -ansi. It's giving "I'm not gonna snitch unless you ask me to" ๐Ÿ’….

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

Functions that are normally built in but don't have semantics defined by ISO C (such as "alloca" and "ffs") are not built-in functions when -ansi is used. Sorry bestie ๐Ÿ˜ญ.

  • -std= โ€” determines 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 don't contradict it. For example, -std=c90 turns off certain features of GCC that are incompatible with ISO C90, like the "asm" and "typeof" keywords โ€” but not other GNU extensions that have no meaning in ISO C90, like 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 what -Wpedantic uses to identify which features count as GNU extensions for that version of the standard. For example, -std=gnu90 -Wpedantic warns about C++ style // comments, while -std=gnu99 -Wpedantic does not. The receipts matter ๐Ÿ’….

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 info ๐Ÿฆ‹. 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 the 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. 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. 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 โ€” outputs 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 (rude, but okay ๐Ÿ™ˆ).

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. It's giving annotated receipts, and honestly? We stan ๐Ÿซถ.

  • -fno-asm โ€” okay so this one is literally telling GCC "bestie, please stop treating asm, inline and typeof like sacred keywords" ๐Ÿ’… that way your code gets to use those words as plain old identifiers. If you still need the real deal, the blessed spellings __asm__, __inline__ and __typeof__ are always there for you ๐Ÿซถ In C, -ansi implies -fno-asm, so heads up.

In C++, inline is a standard keyword and this switch does not touch it โ€” if that's what you're after, you probably want -fno-gnu-keywords instead, which kills typeof but leaves asm and inline alone. In C99 mode (-std=c99 or -std=gnu99), this switch only affects asm and typeof, because inline is a standard keyword in ISO C99 โœจ And in C2X mode (-std=c2x or -std=gnu2x), it only affects asm, since typeof is a standard keyword in ISO C2X. the way the keyword list keeps growing, honestly ๐Ÿ˜ญ

  • -fno-builtin, -fno-builtin-function โ€” don't recognize built-in functions that don't begin with __builtin_ as a prefix. Simple as that.

Ngl, GCC normally generates special code to handle certain built-in functions more efficiently โ€” for instance, calls to alloca may become single instructions which adjust the stack directly, and calls to memcpy may become inline copy loops ๐Ÿ”ฅ The resulting code is often both smaller and faster, but since the function calls no longer appear as such, you cannot set a breakpoint on those calls, nor can you change the behavior of the functions by linking with a different library. highkey a real tradeoff, bestie ๐Ÿ’€

In addition, when a function is recognized as a built-in function, GCC may use information about that function to warn about problems with calls to that function, or to generate more efficient code, even if the resulting code still contains calls to that function. For example, warnings are given with -Wformat for bad calls to printf when printf is built in and strlen is known not to modify global memory. so it's giving "helpful friend who reads your code over your shoulder" ๐Ÿ‘€

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

#define abs(n)          __builtin_abs ((n))
#define strcpy(d, s)    __builtin_strcpy ((d), (s))

DIY built-ins, we love to see it ๐ŸŽ€

  • -fcond-mismatch โ€” allow conditional expressions with mismatched types in the second and third arguments. The value of such an expression is void. This option is not supported for C++. like, C++ said "no โค๏ธ" politely.
  • -ffreestanding โ€” assert that compilation targets a freestanding environment. This implies -fno-builtin. A freestanding environment is one in which the standard library may not exist, and program startup may not necessarily be at main ๐Ÿ˜ณ The most obvious example is an OS kernel. This is equivalent to -fno-hosted.
  • -fgimple โ€” enable parsing of function definitions marked with __GIMPLE. This is an experimental feature that allows unit testing of GIMPLE passes ๐Ÿงช very "we're in the lab" energy, ngl โ€” experimental, so treat it like a new hyperfixation, not a stable relationship.
  • -fgnu-tm โ€” when this one is specified, the compiler generates code for the Linux variant of Intel's current Transactional Memory ABI specification document (Revision 1.1, May 6 2009). This is an experimental feature whose interface may change in future versions of GCC, as the official specification changes โš ๏ธ Please note that not all architectures are supported for this feature.

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

bestie the manpage just trails off there, I'm not making that up ๐Ÿ’€ anyway โ€” note that the transactional memory feature is not supported with non-call exceptions (-fnon-call-exceptions). incompatible, no cap.
  • -fgnu89-inline โ€” tells GCC to use the traditional GNU semantics for inline functions when in C99 mode. Using this option is roughly equivalent to adding the gnu_inline function attribute to all inline functions โœจ

The option -fno-gnu89-inline explicitly tells GCC to use the C99 semantics for inline when in C99 or gnu99 mode (i.e., it specifies the default behavior). This option is not supported in -std=c90 or -std=gnu90 mode. the preprocessor macros __GNUC_GNU_INLINE__ and __GNUC_STDC_INLINE__ may be used to check which semantics are in effect for inline functions โ€” vibe check your inline, basically ๐Ÿฆ‹

  • -fhosted โ€” assert that compilation targets a hosted environment. This implies -fbuiltin. A hosted environment is one in which the entire standard library is available, and in which main has a return type of int. Examples are nearly everything except a kernel ๐Ÿ‘‘ This is equivalent to -fno-freestanding.
  • -flax-vector-conversions โ€” allow implicit conversions between vectors with differing numbers of elements and/or incompatible element types. This option should not be used for new code ๐Ÿšฉ red flag, bestie, it's giving "legacy code only, do not perceive".
  • -fms-extensions โ€” accept some non-standard constructs used in Microsoft header files. In C++ code, this allows member names in structures to be similar to previous 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. sad for everyone else, but ok ๐ŸŒˆ

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

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

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

look at those target-specific vibes go ๐Ÿ’…โœจ

  • -fopenacc โ€” enable handling of OpenACC directives #pragma acc in C/C++ and !$acc in Fortran. When -fopenacc is specified, the compiler generates accelerated code according to the OpenACC Application Programming Interface v2.6 <https://www.openacc.org> ๐Ÿ”ฅ This option implies -pthread, and thus is only supported on targets that have support for -pthread. no pthread, no party ๐Ÿ˜”
  • -fopenacc-dim=geom โ€” specify default compute dimensions for parallel offload regions that do not explicitly specify. The geom value is a triple of :-separated sizes, in order gang, worker and vector. A size can be omitted, to use a target-specific default value. skipping a size is highkey valid ๐Ÿฆ‹
  • -fopenmp โ€” enable 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. -fopenmp implies -fopenmp-simd, periodt.
  • -fopenmp-simd โ€” enable handling of OpenMP's simd, declare simd, declare reduction, assume, ordered, scan, loop directives and combined or composite directives with simd as constituent with #pragma omp in C/C++, [[omp::directive(...)]] and [[omp::sequence(...)]] in C++ and !$omp in Fortran. Other OpenMP directives are ignored ๐Ÿ™ˆ picky but in a cute way.
  • -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. so check your optimization level before you come for it ๐ŸŽ€

  • -fpermitted-flt-eval-methods=style โ€” ISO/IEC TS 18661-3 defines new permissible values for FLT_EVAL_METHOD that indicate that operations and constants with a semantic type that is an interchange or extended format should be evaluated to the precision and range of that type ๐Ÿงš These new values are a superset of those permitted under C99/C11, which does not specify the meaning of other positive values of FLT_EVAL_METHOD. As such, code conforming to C11 may not have been written expecting the possibility of the new values ๐Ÿ˜ณ plot twist for legacy code.

-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. GNU stays extra, as always ๐Ÿ’œ

  • -fplan9-extensions โ€” accept some non-standard constructs used in Plan 9 code ๐ŸŒธ This enables -fms-extensions, permits passing pointers to structures with anonymous fields to functions that expect pointers to elements of the type of the field, and permits referring to anonymous fields declared using a typedef. This is only supported for C, not C++. C++ girlies, this one's not for you ๐Ÿ˜ญ
  • -fsigned-bitfields, -funsigned-bitfields, -fno-signed-bitfields, -fno-unsigned-bitfields โ€” okay so these four besties decide whether a bit-field is signed or unsigned when the declaration is being lazy and doesn't say signed or unsigned out loud. And the default? Signed, periodt. Why? Because it's consistent โ€” the basic integer types like int are signed types, so it just matches the vibe. โœจ
  • -fsigned-char โ€” makes the type char signed, exactly like signed char. ๐Ÿซถ

Lowkey important note: this is equivalent to -fno-unsigned-char, which is the negative form of -funsigned-char. And likewise? The option -fno-signed-char is equivalent to -funsigned-char. It's giving mirror universe, iykyk. ๐Ÿ’…

  • -funsigned-char โ€” makes the type char 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, unfortunately. ๐Ÿ˜ญ

Ideally, a portable program should always use signed char or unsigned char when it depends on the signedness of an object. But ngl, so many programs out there were written to use plain char and just expect it to be signed, or expect it to be unsigned, depending on the machines they were originally written for. This option, and its inverse, let you make such a program work with the opposite default. Slay, compatibility. ๐Ÿ”ฅ

And the type char is always a distinct type from each of signed char or unsigned char, even though its behavior is always just like one of those two. Main character energy: distinct, but acting identical. ๐Ÿ‘‘

  • -fstrict-flex-arrays โ€” controls when to treat the trailing array of a structure 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, which is the strictest. A trailing array is only treated as a flexible array member when it's actually declared as a flexible array member per C99 standard onwards. The negative form is equivalent to -fstrict-flex-arrays=0, which is the least strict โ€” all trailing arrays of structures get treated as flexible array members. ๐Ÿฆ‹
  • *-fstrict-flex-arrays=level* โ€” same whole deal (when to treat the trailing array of a structure as a flexible array member for the purpose of accessing the elements), except 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 if you want to control this behavior for one specific trailing array field of a structure? Just use the variable attribute strict_flex_array attribute. Iconic, targeted, no collateral. ๐Ÿ’œ

  • *-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 (that's the default). This option is not supported for C++. ๐Ÿ™ˆ
โš ๏ธ Warning: the -fsso-struct switch causes GCC to generate code that is not binary compatible with code generated without it, if the specified endianness is not the native endianness of the target. Like, for real, check yourself before you wreck yourself. ๐Ÿ’€

โœจ Options Controlling C++ Dialect โœจ

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

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

In this example, only -fstrict-enums is an option meant only for C++ programs โ€” you can use the other options with any language supported by GCC. ๐ŸŒˆ

Also FYI, some options for compiling C programs, such as -std, are also relevant for C++ programs.

Here is the 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 get fixed. (Yes, it moves. It's alive. It's growing. ๐Ÿ˜ญ)

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

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

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.

If this option is not provided but -Wabi=n is, that version is used for compatibility aliases. If this option is provided along with -Wabi (without the version), the version from this option is used for the warning. The version-trading here is real. ๐Ÿ’…

  • -fno-access-control โ€” turns off all access checking. This switch is mainly useful for working around bugs in the access control code. Like, it's a "the compiler is wrong, not me" button. ๐Ÿ˜Œ
  • -faligned-new โ€” enables support for C++17 new of types that require more alignment than void* ::operator new(std::size_t) provides. A numeric argument such as -faligned-new=32 can be used to specify how much alignment (in bytes) is provided by that function, but few users will need to override the default of alignof(std::max_align_t). ๐ŸŒธ

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

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

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

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

and introduces new signatures for user-defined literals:

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

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

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

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

See also new (nothrow). ๐Ÿซถ

  • -fconcepts, -fconcepts-ts โ€” okay so this one turns on support for the C++ Concepts feature for constraining template arguments ๐Ÿ’…. With -std=c++20 and above, Concepts are literally part of the language standard, so -fconcepts defaults to on. Slay.

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 -fconcepts-ts โœจ.

  • -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 ๐ŸŒ€. 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. This is a heuristic that trades off compilation speed (when the cache avoids repeated calculations) against memory consumption (when the cache grows very large from highly recursive evaluations) ๐Ÿซถ. The default is 8. Very few users are likely to want to adjust it, but if your code does heavy constexpr calculations you might want to experiment to find which value works best for you ngl.
  • -fconstexpr-fp-except โ€” Annex F of the C standard specifies that IEC559 floating point exceptions encountered at compile time should not stop compilation. C++ compilers have historically not followed this guidance, instead treating floating point division by zero as non-constant even though it has a well defined value ๐Ÿ˜ญ. This flag tells the compiler to give Annex F priority over other rules saying that a particular operation is undefined. Iconic behavior fr.
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. A limit is needed to detect infinite loops during constant expression evaluation ๐Ÿ”. The default is 262144 (1<<18).
  • -fconstexpr-ops-limit=n โ€” sets the maximum number of operations during a single constexpr evaluation. Even when number of iterations of a single loop is limited with the above limit, if there are several nested loops and each of them has many iterations but still smaller than the above limit, or if in a body of some loop or even outside of a loop too many expressions need to be evaluated, the resulting constexpr evaluation might take too long ๐Ÿ’€. The default is 33554432 (1<<25).
  • -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.

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 โš ๏ธ.

  • -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.
  • "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) ๐ŸŒ€.
  • -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. You've been warned bestie โš ๏ธ.
  • -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. Efficient queen behavior.
  • -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 ๐Ÿ˜ญ. Like, seriously, be careful.
  • -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 ๐Ÿ’€. Not a vibe.
  • -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. Sneaky.
  • -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 ๐Ÿ˜ด.
  • -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.
  • -fmodule-only โ€” only spits out the Compiled Module Interface and that's it, no object file at all. Like, it does the one thing and dips. ๐Ÿ’…
  • -fms-extensions โ€” turns off the Wpedantic warnings about stuff used in MFC โ€” think implicit int, and getting a pointer to member function via non-standard syntax. Basically "we know it's not standard, we're doing it anyway, don't @ us."
  • -fnew-inheriting-ctors โ€” enables the P0136 adjustment to the semantics of C++11 constructor inheritance. It's part of C++17 but also counts as a Defect Report against C++11 and C++14. Enabled by default unless you specify -fabi-version=10 or lower. (so if you're on the old ABI, sorry bestie, no adjustment for you ๐Ÿ˜ญ)
  • -fnew-ttp-matching โ€” turns on the P0522 resolution to Core issue 150, template template parameters and default arguments: this lets a template with default template arguments be an argument for a template template parameter that has fewer template parameters. Enabled by default for -std=c++17. ๐ŸŽ€
  • -fno-nonansi-builtins โ€” no built-in declarations of functions that aren't mandated by ANSI/ISO C. The ones getting axed include ffs, alloca, _exit, index, bzero, conjf, and other related functions. bye besties ๐Ÿ‘‹
  • -fnothrow-opt โ€” treats a throw() exception specification like it was a noexcept spec, so it can reduce or eliminate the text size overhead compared to a function with no exception spec at all. And here's the fun bit: if the function has local variables of types with non-trivial destructors, the exception specification actually makes the function smaller, because the EH cleanups for those variables can be optimized away. โญ Semantic effect: an exception thrown out of a function with such a spec results in a call to terminate rather than unexpected.
  • -fno-operator-names โ€” nope, don't treat the operator name keywords and, bitand, bitor, compl, not, or and xor as synonyms for keywords.
  • -fno-optional-diags โ€” kills diagnostics that the standard says the compiler doesn't even need to issue. Currently the only such diagnostic G++ issues is the one for a name having multiple meanings within a class. so like, one singular diagnostic. iconic honestly ๐Ÿ’€
  • -fpermissive โ€” downgrades some diagnostics about nonconformant code from errors to warnings. So yes, with -fpermissive some nonconforming code will actually compile. (chaotic, but valid ๐Ÿ™ˆ)
  • -fno-pretty-templates โ€” okay so normally, when an error message refers to a specialization of a function template, the compiler prints the template's signature followed by the template arguments and any typedefs or typenames in the signature โ€” like void f(T) [with T = int] rather than void f(int) โ€” so it's super clear which template is involved. And when an error message refers to a specialization of a class template, the compiler omits any template arguments that match the default template arguments for that template. If either of these behaviors makes the error message harder to understand instead of easier, use -fno-pretty-templates to disable them. (the name is a lie, it's the un-pretty one ๐Ÿ’…)
  • -fno-rtti โ€” disables generation of the 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, you can save some space with this flag. Heads up: exception handling uses the same information, but G++ generates it as needed. The dynamic_cast operator still works 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. This is useful for user-defined replacement deallocation functions that, for example, use the size of the object to make deallocation faster. Enabled by default under -std=c++14 and above. And -Wsized-deallocation warns about places that might want to add a definition. ๐Ÿ”ฅ

  • -fstrict-enums โ€” lets the compiler optimize on the assumption that a value of enumerated type can only be one of the values of the enumeration (as defined in the C++ standard; basically, a value that can be represented in the minimum number of bits needed to represent all the enumerators). This assumption may not be valid if the program uses a cast to convert an arbitrary integer value to the enumerated type. โš ๏ธ so like, if you're out here casting randoms into enums, this flag will absolutely betray you.
  • -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. -fstrong-eval-order=some enables just the ordering of member access and shift expressions, and is the default without -std=c++17.
  • *-ftemplate-backtrace-limit=n* โ€” sets the max number of template instantiation notes for a single warning or error to n. The default value is 10. (after that, the backtrace just gives up, relatable ๐Ÿซถ)
  • *-ftemplate-depth=n* โ€” sets the max instantiation depth for template classes to n. A limit on template instantiation depth is needed to detect endless recursions during template class instantiation. ANSI/ISO C++ conforming programs must not rely on a maximum depth greater than 17 (changed to 1024 in C++11). The default value is 900, because the compiler can run out of stack space before hitting 1024 in some situations. ๐Ÿ˜ญ
  • -fno-threadsafe-statics โ€” do NOT emit the extra code that uses the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this to shave a little code size in code that doesn't need to be thread-safe. (only if you're sure bestie, only if you're sure ๐Ÿ‘€)
  • -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.
  • -fno-use-cxa-get-exception-ptr โ€” don't use the __cxa_get_exception_ptr runtime routine. This makes std::uncaught_exception incorrect, but it's necessary if the runtime routine isn't available. ๐Ÿ’€
  • -fvisibility-inlines-hidden โ€” this switch declares that the user isn't trying 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 appear in the export table of a DSO and don't require a PLT indirection when used within the DSO. Enabling this can have a dramatic effect on load and link times of a DSO, because it massively reduces the size of the dynamic export table when the library makes heavy use of templates. โœจ

Heads up though: this switch is not quite the same as marking the methods hidden directly, because it doesn't affect static variables local to the function, and it doesn't cause the compiler to deduce that the function is defined in only one shared object.

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

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

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

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 those classes that are intended 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. โš ๏ธ

  • -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++. (so like, genuinely don't ๐Ÿšซ)
  • -fext-numeric-literals (C++ and Objective-C++ only) โ€” accept imaginary, fixed-point, or machine-defined literal number suffixes as GNU extensions. When this option is turned off, those suffixes are treated as C++11 user-defined literal numeric suffixes. 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. 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.)
  • -flang-info-include-translate, -flang-info-include-translate-not, *-flang-info-include-translate=header* โ€” inform of include translation events. The first one notes accepted include translations, the second notes declined include translations. The header form informs of include translations relating to that specific header. If header is of the form user or <system>, it gets resolved to a specific user or system header using the include path. ๐Ÿงš
  • -flang-info-module-cmi, -flang-info-module-cmi=_module_ โ€” bestie, this one is your little spy into Compiled Module Interface pathnames ๐Ÿ‘€. The plain form notes all read CMI pathnames. The =module form won't note reading a specific module's CMI. And module can be a named module or a header-unit (that second one is indicated by either being a pathname containing directory separators, or being enclosed in "<>" or ""). Slay.
  • -stdlib=libstdc++,libc++ โ€” okay so when G++ is configured to support this option, it lets you specify alternate C++ runtime libraries โœจ. Two options are available: libstdc++ (the default, native C++ runtime for G++) and libc++, which is the C++ runtime installed on some operating systems (e.g. Darwin versions from Darwin11 onwards). The option switches G++ to use the headers from the specified library and to emit -lstdc++ or -lc++ respectively, when a C++ runtime is required for linking. Both vibes are valid, iykyk ๐Ÿ’….

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

  • -Wabi-tag (C++ and Objective-C++ only) โ€” warns when a type with an ABI tag is used in a context that does not have that ABI tag. See C++ Attributes for more info about ABI tags ๐Ÿท๏ธ.
  • -Wcomma-subscript (C++ and Objective-C++ only) โ€” warns about uses of a comma expression within a subscripting expression. This usage was deprecated in C++20 and is going to be removed in C++23 ๐Ÿ˜ญ. BUT โ€” a comma expression wrapped in ( ) is not deprecated. Example:
void f(int *a, int b, int c) {
    a[b,c];     // deprecated in C++20, invalid in C++23
    a[(b,c)];   // OK
}

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

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

  • -Wctad-maybe-unsupported (C++ and Objective-C++ only) โ€” warns when you're performing class template argument deduction (CTAD) on a type with no explicitly written deduction guides ๐Ÿ”. This warning points out cases where CTAD succeeded only because the compiler synthesized the implicit deduction guides, which might not be what the programmer intended. Certain style guides allow CTAD only on types that specifically "opt-in"; i.e., on types that are designed to support CTAD. 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 seems unusable because all the constructors or destructors in that class are 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 destructor.
  • -Wdangling-reference (C++ and Objective-C++ only) โ€” warns when a reference is bound to a temporary whose lifetime has ended ๐Ÿ’€. For example:
int n = 1;
const int& r = std::max(n - 1, n + 1); // r is dangling

In the example above, two temporaries are created, one for each argument, and a reference to one of the temporaries is returned. However, both temporaries are destroyed at the end of the full expression, so the reference "r" is dangling. This warning also detects 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 are checked as well, but only their object argument:

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

Certain functions are safe in this respect, for example "std::use_facet": they take and return a reference, but they don't return one of its arguments, which can fool the warning ๐Ÿซ . Such functions can be excluded 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 that contains the call to "std::minmax" ๐Ÿ˜ญ.

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 does not 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. With -Wdeprecated-copy-dtor, also deprecate if the class has a user-provided destructor ๐Ÿ’….
  • -Wno-deprecated-enum-enum-conversion (C++ and Objective-C++ only) โ€” disables the warning about the case when the usual arithmetic conversions are applied on operands where one is of enumeration type and the other is of a different enumeration type. This conversion was deprecated in C++20. For example:
enum E1 { e };
enum E2 { f };
int k = f - e;

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

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

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

  • -Wno-init-list-lifetime (C++ and Objective-C++ only) โ€” do not warn about uses of "std::initializer_list" that are likely to result in dangling pointers. Since the underlying array for an "initializer_list" is handled like a normal C++ temporary object, it is easy to inadvertently keep a pointer to the array past the end of the array's lifetime ๐Ÿ˜ฌ. For example:
    • If a function returns a temporary "initializer_list", or a local "initializer_list" variable, the array's lifetime ends at the end of the return statement, so the value returned has a dangling pointer.
    • If a new-expression creates an "initializer_list", the array only lives until the end of the enclosing full-expression, so the "initializer_list" in the heap has a dangling pointer.
    • When an "initializer_list" variable is assigned from a brace-enclosed initializer list, the temporary array created for the right side of the assignment only lives until the end of the full-expression, so at the next statement the "initializer_list" variable has a dangling pointer. Like so:
// 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 this restriction, so it's possible to have a function or a function template marked "constexpr" for which no invocation satisfies the requirements of a core constant expression.

This warning is enabled as a pedantic warning by default in C++20 and earlier. In C++23, -Winvalid-constexpr can be turned on, in which case it will be an ordinary warning. For 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 all imported macro definitions are valid at the end of compilation โœ…. This is not enabled by default, as it requires additional processing to determine. It may be useful when preparing sets of header-units to ensure consistent macros ๐ŸŽ€.
  • -Wno-literal-suffix (C++ and Objective-C++ only) โ€” do not warn when a string or character literal is followed by a ud-suffix which does not begin with an underscore. As a conforming extension, GCC treats such suffixes as separate preprocessing tokens in order to maintain backwards compatibility with code that uses formatting macros from "<inttypes.h>" ๐Ÿ‘‘. For example:
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>

so this next bit picks up right where the last option left off โ€” here's the little snippet that was being talked about:

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

And in this case, PRId64 is treated as a separate preprocessing token, bestie. That's the whole point.

This same option also controls the warnings you get when a user-defined literal operator is declared with a literal suffix identifier that doesn't start with an underscore. And why do we care? Because literal suffix identifiers that don't begin with an underscore are reserved for future standardization ๐Ÿ‘€ โ€” so touching them is asking for trouble.

These warnings are enabled by default. Lucky you ๐ŸŽ€


  • -Wno-narrowing (C++ and Objective-C++ only) โ€” okay so for C++11 and later standards, narrowing conversions get diagnosed by default, as the standard literally requires. A narrowing conversion from a constant produces an error, and a narrowing conversion from a non-constant produces a warning โ€” but -Wno-narrowing suppresses that diagnostic entirely. Important tho: this does not affect the meaning of well-formed code; narrowing conversions are still considered ill-formed in SFINAE contexts. Don't get it twisted ๐Ÿ’…

With -Wnarrowing in C++98, it warns when a narrowing conversion prohibited by C++11 happens inside { }, like this:

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

This flag is included in -Wall and -Wc++11-compat.

  • -Wnoexcept (C++ and Objective-C++ only) โ€” warns when a noexcept-expression evaluates to false because of a call to a function that 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 knows things, and it's gonna tell you ๐Ÿงš
  • -Wnoexcept-type (C++ and Objective-C++ only) โ€” warns if the C++17 feature making "noexcept" part of a function type changes the mangled name of a symbol relative to C++14. Enabled by -Wabi and -Wc++17-compat. As an example:
template <class T> void f(T t) { t(); };
void g() noexcept;
void h() { f(g); }

In C++14, "f" calls "f<void(*)()>", but in C++17 it calls "f<void(*)()noexcept>". Tiny difference, huge consequences, iykyk ๐Ÿ˜ญ

  • -Wclass-memaccess (C++ and Objective-C++ only) โ€” warns when the destination of a call to a raw memory function like "memset" or "memcpy" is an object of class type, and when writing into such an object might bypass the class's non-trivial or deleted constructor or copy assignment, violate const-correctness or encapsulation, or corrupt virtual table pointers. Modifying the representation of such objects can violate invariants maintained by member functions of the class. For example, the "memset" call 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.
std::string str = "abc";
memset (&str, 0, sizeof str);

The -Wclass-memaccess option is enabled by -Wall. And hey โ€” 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. Slay โœจ

  • -Wnon-virtual-dtor (C++ and Objective-C++ only) โ€” warns when a class has virtual functions and an accessible non-virtual destructor, either in itself or in an accessible polymorphic base class โ€” in which case it's 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. Prefer the better one, bestie ๐Ÿซถ
  • -Wregister (C++ and Objective-C++ only) โ€” warns on uses of the "register" storage class specifier, except when it's part of the GNU Explicit Register Variables extension. The use of the "register" keyword as a storage class specifier has been deprecated in C++11 and removed in C++17. Enabled by default with -std=c++17. It's giving "we don't do that anymore" ๐Ÿ’€
  • -Wreorder (C++ and Objective-C++ only) โ€” warns when the order of member initializers given in the code doesn't match the order in which they must actually 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, and emits a warning to that effect. This warning is enabled by -Wall. The compiler said "not the order you wrote, bestie" ๐Ÿ™ˆ

  • -Wno-pessimizing-move (C++ and Objective-C++ only) โ€” this warning yells at you when a call to "std::move" prevents copy elision. A typical scenario where copy elision can occur is when returning in a function with a class return type, when the expression being returned is the name of a non-volatile automatic object, and is not a function parameter, and has the same type as the function return type.
struct T {
...
};
T fn()
{
  T t;
  ...
  return std::move (t);
}

But in this example, the "std::move" call prevents copy elision. Big oof. This warning is enabled by -Wall.

  • -Wno-redundant-move (C++ and Objective-C++ only) โ€” this warning is 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. And because G++ implements Core Issue 1579, another example is:

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

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

  • -Wrange-loop-construct (C++ and Objective-C++ only) โ€” warns when a C++ range-based for-loop is 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. (Sixty-four! A very specific number. Respect it ๐Ÿ“)

This warning also warns when a loop variable in a range-based for-loop is initialized with a value of a different type, resulting in a copy. For example:

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

In the example above, in every iteration of the loop a temporary value of type "double" is created and destroyed, to which the reference const double & is bound. Every. Single. Iteration. ๐Ÿ˜ญ This warning is enabled by -Wall.

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

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

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

Context is everything, periodt ๐Ÿ‘‘

  • -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. Here's the why: 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. And the compiler doesn't give this warning for types defined in the main .C file, since those are unlikely to have multiple definitions. -Wsubobject-linkage is enabled by default. Okay so we love a well-explained caveat ๐Ÿ’œ
  • -Weffc++ (C++ and Objective-C++ only) โ€” warns about violations of the following style guidelines from Scott Meyers' Effective C++ series of books:
    • Define a copy constructor and an assignment operator for classes with dynamically-allocated memory.
    • Prefer initialization to assignment in constructors.
    • Have "operator=" return a reference to *this.
    • Don't try to return a reference when you must return an object.
    • Distinguish between prefix and postfix forms of increment and decrement operators.
    • Never overload "&&", "||", or ",".

This option also enables -Wnon-virtual-dtor, which is also one of the effective C++ recommendations. However, the check is extended to warn about the lack of a virtual destructor in accessible non-polymorphic base 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. Not kidding, you'll need it ๐Ÿงš
  • -Wno-exceptions (C++ and Objective-C++ only) โ€” disables the warning about the case when an exception handler is shadowed by another handler, which can point out a wrong ordering of exception handlers. Sometimes you just want the compiler to hush ๐Ÿคซ
  • -Wstrict-null-sentinel (C++ and Objective-C++ only) โ€” warns about the use of an uncasted "NULL" as a 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's guaranteed to be of the same size as a pointer. But this use is not portable across different compilers โ€” so like, it works until it doesn't ๐ŸŒˆ
  • -Wno-non-template-friend (C++ and Objective-C++ only) โ€” turns off the warning you get when non-template friend functions get declared inside a template. Here's the lore: in very old versions of GCC (like, pre-ISO-standard ancient), a declaration like friend int foo(int), where the friend's name is an unqualified-id, could get read as a specific specialization of a template function ๐Ÿ˜ญ. The warning exists purely to diagnose compatibility drama โ€” and it's on by default, bestie.
  • -Wold-style-cast (C++ and Objective-C++ only) โ€” yells at you if you use an old-style (C-style) cast to a non-void type inside a C++ program ๐Ÿ’…. The new-style casts (dynamic_cast, static_cast, reinterpret_cast, and const_cast) are way less vulnerable to unintended effects and so much easier to search for. It's giving glow-up, honestly.
  • -Woverloaded-virtual / -Woverloaded-virtual=n (C++ and Objective-C++ only) โ€” warns when a function declaration hides virtual functions from a base class. Classic example, look:
        struct A {
          virtual void f();
        };

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

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

        B* b;
        b->f();

fails to compile ๐Ÿ’€. When the different signatures aren't an accident, the simplest fix is adding a using-declaration to the derived class to un-hide the base function โ€” e.g. add using A::f; to B ๐Ÿซถ.

The optional level suffix controls behavior when all the declarations in the derived class override virtual functions in the base class, even if not all of the 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 that the base class semantics for some of the overloads are fine.

At level 1, this case does not warn; at level 2, it does. -Woverloaded-virtual by itself selects level 2. And level 1 is included in -Wall โœจ.

  • -Wno-pmf-conversions (C++ and Objective-C++ only) โ€” disables the diagnostic for converting a bound pointer to member function into a plain pointer. That's it, that's the vibe ๐Ÿ™ˆ.
  • -Wsign-promo (C++ and Objective-C++ only) โ€” warns when overload resolution picks a promotion from unsigned or enumerated type to a signed type, over a conversion to an unsigned type of the same size ๐Ÿ‘€. Previous versions of G++ tried to preserve unsignedness, but the standard mandates the current behavior. Standards said what they said ๐Ÿ’….
  • -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 one can still use the STL. One may also instantiate or specialize templates โ€” those are fine, no cap.
  • -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 โ€” plus 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 โ€” -Wmismatched-tags is just here to help achieve a consistent style of class declarations โœจ. In code 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.

  • -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 โ€” loophole found, bestie ๐Ÿฆ‹.
  • -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.
  • -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. Like, only turn this off if you actually know what you're doing, fr fr.
  • -Wnamespaces โ€” warns when a namespace definition is opened ๐Ÿ‘€. Some coding rules disallow namespaces, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also use using directives and qualified names โ€” those aren't definitions, so they slay through unaffected โœจ.
  • -Wno-terminate (C++ and Objective-C++ only) โ€” disables the warning about a throw-expression that will immediately result in a call to terminate ๐Ÿ’€. (RIP to that throw, it never stood a chance.)
  • -Wno-vexing-parse (C++ and Objective-C++ only) โ€” warns about the most vexing parse syntactic ambiguity ๐Ÿ˜ญ. This warns about 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.

  • -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 it's lowkey pointless, but also harmless.
  • -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.

  • -Wzero-as-null-pointer-constant (C++ and Objective-C++ only) โ€” warns when a literal 0 is used as a null pointer constant ๐Ÿ‘€. This can be useful to facilitate the conversion to nullptr in C++11. Like, 0 is not the moment anymore, nullptr is the main character โœจ.
  • -Waligned-new โ€” warns about a new-expression of a type that requires greater alignment than alignof(std::max_align_t) but uses an allocation function without an explicit alignment parameter ๐Ÿ”ฅ. This option is enabled by -Wall.

Normally this only warns about global allocation functions, but -Waligned-new=all also warns about class member allocation functions ๐Ÿ‘‘

  • -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 level 2 is where it gets extra. Same diagnostics as level 1, plus it also yells at you for placement new expressions that construct an object in the last member of a structure โ€” when that member's type is an array of a single element and its size is less than the size of the object you're constructing. So yeah, the example above would totally get flagged. But the version below uses the flexible member array extension to dodge the warning at level 2. Sneaky. Love that for them. ๐Ÿ’…
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's about catch handlers that refuse to catch via reference. Rude of them, honestly. With -Wcatch-value=1 (or just -Wcatch-value for short) it warns about polymorphic class types that get caught by value. With -Wcatch-value=2 it warns about all class types caught by value. With -Wcatch-value=3 it warns about every type that isn't caught by reference. And heads up: -Wcatch-value is enabled by -Wall.
  • -Wconditionally-supported (C++ and Objective-C++ only) โ€” warns you about conditionally-supported constructs (C++11 [intro.defs]). That's it, that's the whole vibe. โœจ
  • -Wno-delete-incomplete (C++ and Objective-C++ only) โ€” turns OFF the warning you get when you delete a pointer to an incomplete type โ€” which, btw, may cause undefined behavior at runtime. So like, you're allowed to silence it, but the compiler is judging you. This warning is enabled by default.
  • -Wextra-semi (C++, Objective-C++ only) โ€” warns about redundant semicolons after in-class function definitions. Extra semis, bestie. We see them. ๐Ÿซถ
  • -Wno-inaccessible-base (C++, Objective-C++ only) โ€” this one controls warnings for when a base class is inaccessible in a class derived from it due to ambiguity. Enabled by default. Quick note tho: the warning for ambiguous virtual bases is enabled by the -Wextra option instead, not this one.
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 you inherited from has a C variadic constructor. The warning is on by default, because the ellipsis is not inherited. That's the whole reason. ๐Ÿ˜ญ
  • -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. That said, in existing C++ implementations "offsetof" typically gives you meaningful results anyway. So this flag is for the users who know they're writing nonportable code and deliberately chose to ignore the warning about it. Main character energy, honestly. ๐Ÿ‘‘

Also, the restrictions on "offsetof" may be relaxed in a future version of the C++ standard. So like, watch this space.

  • -Wsized-deallocation (C++ and Objective-C++ only) โ€” warns you when you define an unsized deallocation function:
void operator delete (void *) noexcept;
void operator delete[] (void *) noexcept;

โ€ฆwithout also defining the corresponding sized deallocation function:

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

โ€ฆor the other way around (sized without unsized). Either direction, it clocks it. Enabled by -Wextra along with -fsized-deallocation.

  • -Wsuggest-final-types โ€” warns about types with virtual methods where your code quality would literally improve 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 this warning is more effective with link-time optimization, where the info about the class hierarchy graph is more complete.
  • -Wsuggest-final-methods โ€” same energy but for virtual methods: warns when 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. Again, more effective with link-time optimization for the same class-hierarchy-graph reasons. Pro tip from the manual itself: it's recommended you first consider the suggestions of -Wsuggest-final-types and then rebuild with 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 not that hard. ๐Ÿ’…
  • -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. Enabled at all optimization levels, but ngl it may yield different results with optimization than without. ๐Ÿ”ฅ
    • -Wuse-after-free=1 โ€” at level 1 the warning only tries to diagnose unconditional uses of pointers made indeterminate by a deallocation call or a successful call to "realloc" โ€” regardless of whether the call actually resulted in a reallocation of memory. This includes double-"free" calls, plus uses in arithmetic and relational expressions. 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 unconditional uses, it also diagnoses conditional uses of pointers made indeterminate by a deallocation call. As at level 2, uses in equality (or inequality) expressions are not diagnosed. For example, the second call to "free" in this function 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 โ€” level 3 goes there: it also diagnoses uses of indeterminate pointers in equality expressions. All uses of indeterminate pointers are undefined, 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 to help legacy code gradually transition to safe alternatives. Example โ€” the equality test in this function is diagnosed at this level:
void adjust_pointers (int**, int);

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

Want to dodge the warning at this level? Store offsets into the allocated memory instead of pointers. That approach obviates needing to adjust the stored pointers after reallocation. Clean. โœจ

-Wuse-after-free=2 is included in -Wall. So you're getting it whether you asked or not, bestie.
  • -Wuseless-cast (C++ and Objective-C++ only) โ€” warns when an expression is cast to its own type. Kinda pointless, hence the name, get it? This warning does not fire when a class object is converted to a non-reference type, because that's actually a 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) โ€” don't warn for conversions between "NULL" and non-pointer types. For the record, -Wconversion-null is enabled by default.

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

(NOTE: this manual does not describe the Objective-C and Objective-C++ languages themselves. We're just doing the flags, diva.)

This section is all about the command-line options that are only meaningful for Objective-C and Objective-C++ programs. Good news tho: you can also use most of the language-independent GNU compiler options. Like, 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 GCC supports. ๐Ÿฆ‹

Also, since Objective-C is an extension of the C language, Objective-C compilations may also use options specific to the C front-end (e.g., -Wtraditional). Similarly, Objective-C++ compilations may use C++-specific options (e.g., -Wabi). They contain multitudes. ๐Ÿ’œ

Here's the list of options that are only for compiling Objective-C and Objective-C++ programs:

  • -fconstant-string-class=_class-name_ โ€” use class-name as the name of the class to instantiate for each literal string 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, bestie, it's coming). On Darwin (macOS, MacOS X) platforms, the -fconstant-cfstrings option, if also present, overrides the -fconstant-string-class setting, and causes "@"..."" literals to be laid out as constant CoreFoundation strings. Note that -fconstant-cfstrings is an alias for the target-specific -mconstant-cfstrings equivalent. ๐ŸŒธ
  • -fgnu-runtime โ€” generate object code compatible with the standard GNU Objective-C runtime. This is the default for most types of systems. The classic. ๐Ÿซถ
  • -fnext-runtime โ€” generate output compatible with the NeXT runtime. This is the default for NeXT-based systems, including Darwin and Mac OS X. And the macro "__NEXT_RUNTIME__" is predefined if (and only if) this option is used. If and only if, no cap. โญ
  • -fno-nil-receivers โ€” assume that all Objective-C message dispatches ("[receiver message:arg]") in this translation unit ensure that the receiver is not "nil". Why would you do that? Because it allows more efficient entry points in the runtime to be used. ๐Ÿ’… This option is only available in conjunction with the NeXT runtime and ABI version 0 or 1. Just so you know.
  • -fobjc-abi-version=n โ€” picks version n of the Objective-C ABI for whichever runtime you've got going on. Heads up: this is currently only a NeXT-runtime thing. So like, on NeXT: Version 0 is the traditional (32-bit) ABI, no support for properties or the other Objective-C 2.0 additions. Version 1 is the traditional (32-bit) ABI with support for properties and the rest of the Objective-C 2.0 additions. Version 2 is the modern (64-bit) ABI. Don't specify anything and the default is Version 0 on 32-bit target machines, and Version 2 on 64-bit target machines. ๐Ÿ’…
  • -fobjc-call-cxx-cdtors โ€” okay so for each Objective-C class, this checks if any of its instance variables is a C++ object with a non-trivial default constructor. If it finds one, it synthesizes a special - (id) .cxx_construct instance method that runs those non-trivial default constructors on all such instance variables, in order, and then returns self. Same deal for destructors: it checks whether any instance variable is a C++ object with a non-trivial destructor, and if so synthesizes a special - (void) .cxx_destruct method that runs all such default destructors, in reverse order. โœจ

Important: the - (id) .cxx_construct and - (void) .cxx_destruct methods generated this way only operate on instance variables declared in the current Objective-C class โ€” not the ones inherited from superclasses. It's the Objective-C runtime's job to invoke all such methods across an object's inheritance hierarchy. The - (id) .cxx_construct methods get invoked by the runtime 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. This one is required if you want 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 in conjunction with the NeXT runtime on Mac OS X 10.2 and earlier). ๐Ÿ˜ญ
  • -fobjc-gc โ€” enables garbage collection (GC) in Objective-C and Objective-C++ programs. Only available with the NeXT runtime; the GNU runtime has a different garbage collection implementation that does not require special compiler flags. ๐Ÿ—‘๏ธโœจ
  • -fobjc-nilcheck โ€” for the NeXT runtime with version 2 of the ABI, this checks for a nil receiver in method invocations before doing the actual method call. This is the default, and you can disable it using -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 this option is used with the Objective-C or Objective-C++ compiler, any Objective-C syntax that isn't recognized by GCC 4.0 is 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 in conjunction with the Fix-and-Continue debugging mode, where the object file in question may be recompiled and dynamically reloaded in the course of program execution, without 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 name of the class is known at compile time) with static class references that get initialized at load time, which improves run-time performance. Specifying the -fzero-link flag suppresses this behavior and causes calls to objc_getClass("...") to be retained. This is useful in Zero-Link debugging mode, since it allows for individual class implementations to be modified during program execution. The GNU runtime currently always retains calls to objc_get_class("...") regardless of command-line options. ๐Ÿงš
  • -fno-local-ivars โ€” by default, instance variables in Objective-C can be accessed as if they were local variables from within the methods of the class they're declared in. This can lead to shadowing between instance variables and other variables declared either locally inside a class method or globally with the same name. Specifying the -fno-local-ivars flag disables this behavior, thus avoiding variable shadowing issues. ๐Ÿ’œ
  • -fivar-visibility=[public|protected|private|package] โ€” sets the default instance variable visibility to the specified option, so instance variables declared outside the scope of any access modifier directives default to that visibility.
  • -gen-decls โ€” dumps interface declarations for all classes seen in the source file to a file named sourcename.decl. ๐Ÿ“„
  • -Wassign-intercept (Objective-C and Objective-C++ only) โ€” warns whenever an Objective-C assignment is being intercepted by the garbage collector.
  • -Wno-property-assign-default (Objective-C and Objective-C++ only) โ€” 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 is performed on the list of methods in the final stage of compilation. Additionally, a check is performed for each selector appearing in a @selector(...) expression, and a corresponding method for that selector has been found during compilation. Because these checks scan the method table only at the end of compilation, these warnings are not produced if the final stage of compilation 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

Traditionally, diagnostic messages have been formatted irrespective of the output device's aspect (e.g. its width, ...). You can use the options described below to control the formatting algorithm for diagnostic messages โ€” like how many characters per line, how often source location information should be reported. Just know that some language front ends may not honor these options. ๐Ÿ™ˆ

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

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

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

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

  • -fdiagnostics-show-location=once โ€” okay so this one only does anything in line-wrapping mode (iykyk). It tells the diagnostic reporter to drop the source location once โ€” like, if the message is too long to fit on one physical line and has to wrap, the source location won't keep getting re-emitted as a prefix over and over on every continuation line. Which is literally the default behavior, bestie. ๐ŸŽ€
  • -fdiagnostics-show-location=every-line โ€” again, only meaningful in line-wrapping mode. This one says: yes, actually, emit that same source location info (as a prefix) on every physical line that comes out of breaking up a message that's too long for a single line. Consistent, if a lil repetitive. ๐Ÿ’…
  • -fdiagnostics-color[=WHEN], -fno-diagnostics-color โ€” use color in diagnostics, periodt. WHEN is never, always, or auto. The default depends on how the compiler was 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 standard error is a terminal, and when it's not executing in an emacs shell. And 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 โ€” check the docs for your text terminal for the permitted values and what they mean as character attributes. Those substring values are integers in decimal representation and you can concatenate them 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, bestie:

  • "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, iconic behavior honestly. 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 standard error is a terminal, and when it's not executing in an emacs shell or any graphical terminal which is known to be incompatible with this feature โ€” see below, bestie. ๐Ÿ‘€

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

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

However, even with -fdiagnostics-urls=always the behavior is dependent on those environment variables: If GCC_URLS is set to empty or no, do not embed URLs in diagnostics. If set to st, URLs use ST escape sequences. If set to bel, the default, URLs use BEL escape sequences. Any other non-empty value enables the feature. If GCC_URLS is not set, use TERM_URLS as a fallback. Note: ST is an ANSI escape sequence, string terminator ESC \, BEL is an ASCII character, CTRL-G that usually sounds like a beep. ๐Ÿ“Ÿ

At this time GCC 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 the -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, that is). Specifying the -fno-diagnostics-show-option flag suppresses that behavior. Poof, gone. ๐Ÿ™ˆ
  • -fno-diagnostics-show-caret โ€” by default, each diagnostic emitted includes the original source line and a caret ^ indicating the column. This option suppresses that info. 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. No numbers, no margin, no problem. ๐Ÿซถ
  • -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. Bestie, that's the whole flag. ๐Ÿ˜Œ
  • -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 โ€” okay so picture this: the C++ frontend is printing diagnostics showing mismatching template types, and it hits you with something like:
                     could not convert 'std::map<int, std::vector<double> >()'
                       from 'map<[...],vector<double>>' to 'map<[...],vector<float>>

This flag is the little glow-up that enables printing a tree-like structure showing the common and differing parts of the types, like:

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

The parts that differ are highlighted with color (double and float in this case). Itโ€™s giving โ€œmap of the chaosโ€ and honestly? Obsessed. ๐Ÿ’…โœจ

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

Specifying the -fno-elide-type flag suppresses that behavior. This flag also affects the output of the -fdiagnostics-show-template-tree flag. No more mystery [...], bestie โ€” weโ€™re seeing it all. ๐Ÿซถ

  • -fdiagnostics-path-format=KIND โ€” this one says how to print paths of control-flow events for diagnostics that have such a path associated with them. KIND is none, separate-events, or inline-events โ€” and inline-events is the default.

none means to not print diagnostic paths. Simple. Iconic. Minimal.

separate-events means to print a separate โ€œnoteโ€ diagnostic for each event within the diagnostic. For example:

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

inline-events means to print the events โ€œinlineโ€ within the source code. This view attempts to consolidate the events into runs of sufficiently-close events, printing them as labelled ranges within the source.

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

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

Interprocedural control flow is shown by grouping the events by stack frame, and using indentation to show how stack frames are nested, pushed, and popped. The drama of it all! ๐ŸŒ€

For example:

                     'test': events 1-2
                       |
                       |  133 | {
                       |      | ^
                       |      | |
                       |      | (1) entering 'test'
                       |  134 |   boxed_int *obj = make_boxed_int (i);
                       |      |                    ~~~~~~~~~~~~~~~~~~
                       |      |                    |
                       |      |                    (2) calling 'make_boxed_int'
                       |
                       +--> 'make_boxed_int': events 3-4
                              |
                              |  120 | {
                              |      | ^
                              |      | |
                              |      | (3) entering 'make_boxed_int'
                              |  121 |   boxed_int *result = (boxed_int *)wrapped_malloc (sizeof (boxed_int));
                              |      |                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                              |      |                                    |
                              |      |                                    (4) calling 'wrapped_malloc'
                              |
                              +--> 'wrapped_malloc': events 5-6
                                     |
                                     |    7 | {
                                     |      | ^
                                     |      | |
                                     |      | (5) entering 'wrapped_malloc'
                                     |    8 |   return malloc (size);
                                     |      |          ~~~~~~~~~~~~~
                                     |      |          |
                                     |      |          (6) calling 'malloc'
                                     |
                       <-------------+
                       |
                    'test': event 7
                       |
                       |  138 |   free_boxed_int (obj);
                       |      |   ^~~~~~~~~~~~~~~~~~~~
                       |      |   |
                       |      |   (7) calling 'free_boxed_int'
                       |
                   (etc)
  • -fdiagnostics-show-path-depths โ€” this option provides additional information when printing control-flow paths associated with a diagnostic.

If this option is provided, then the stack depth will be printed for each run of events within -fdiagnostics-path-format=inline-events. If provided with -fdiagnostics-path-format=separate-events, then the stack depth and function declaration will be appended when printing each event.

This is intended for use by GCC developers and plugin developers when debugging diagnostics that report interprocedural control flow. Very โ€œdevs only, but make it forensic.โ€ ๐Ÿ”๐Ÿ’œ

  • -fno-show-column โ€” do not print column numbers in diagnostics. This may be necessary if diagnostics are being scanned by a program that does not understand the column numbers, such as dejagnu. Sometimes the tooling just isnโ€™t ready for the column lore. ๐Ÿ˜ญ
  • -fdiagnostics-column-unit=UNIT โ€” select the units for the column number. This affects traditional diagnostics (in the absence of -fno-show-column), as well as JSON format diagnostics if requested.

The default UNIT, display, considers the number of display columns occupied by each character. This may be larger than the number of bytes required to encode the character, in the case of tab characters, or it may be smaller, in the case of multibyte characters. For example, the character โ€œGREEK SMALL LETTER PI (U+03C0)โ€ occupies one display column, and its UTF-8 encoding requires two bytes; the character โ€œSLIGHTLY SMILING FACE (U+1F642)โ€ occupies two display columns, and its UTF-8 encoding requires four bytes. Unicode said โ€œI contain multitudes,โ€ and GCC said โ€œbestie, same.โ€ ๐ŸŒธ

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

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

This option controls how such bytes should be escaped.

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

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

          before<U+03C0><BF>after

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

          before<CF><80><BF>after
  • -fdiagnostics-format=FORMAT โ€” select a different format for printing diagnostics. FORMAT is text, 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 is emitted to stderr, whereas with json-file it is 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, without formatting; the examples below have been formatted for clarity.

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 that "note" is literally a child of the "warning", bestie, like it's holding its hand ๐Ÿซถ

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

A diagnostic can have zero or more locations โ€” yes, zero, it's giving minimalist ๐Ÿ’…. Each location has an optional "label" string plus up to three positions inside it: a "caret" position and optional "start" and "finish" positions. A position is described by a "file" name, a "line" number, and three numbers telling you the column position:

  • "display-column" โ€” counts display columns, and it does account for tabs and multibyte characters โœจ
  • "byte-column" โ€” counts raw bytes, no vibes, just bytes
  • "column" โ€” equal to one of the previous two, whichever the -fdiagnostics-column-unit option dictates ๐Ÿ‘‘

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

So like, check out 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}

It has three locations, no cap. Its primary location is at the + token at column 23, and 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". Tiny detail, huge slay ๐Ÿ’…

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. Stacked like your iced coffee order, honestly ๐Ÿงš

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). It's literally just a little heads-up ๐ŸŽ€


โœจ 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 runs, but it's giving "this is fine" meme energy.

The following language-independent options do not enable specific warnings but control the kinds of diagnostics produced by GCC. Main character options only ๐Ÿ‘‘

  • -fsyntax-only โ€” Check the code for syntax errors, but don't do anything beyond that. Just a lil vibe check on your syntax, then it dips โœŒ๏ธ
  • -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 โ€” go off, infinite chaos ๐Ÿ˜ญ. If -Wfatal-errors is also specified, then -Wfatal-errors takes precedence over this option. Periodt.
  • -w โ€” Inhibit all warning messages. Not me silencing the haters ๐Ÿ™ˆโœจ
  • -Werror โ€” Make all warnings into errors. Glow-up gone wrong: every warning now has main-character stakes ๐Ÿ’€๐Ÿ”ฅ

ok so next we have the glow-up where warnings get promoted to errors ๐Ÿ’…

  • -Werror= โ€” makes the warning you name into a full-on error. You just tack the specifier onto the end, like -Werror=switch turns all those -Wswitch warnings into errors. And bestie, it's got a negative form too, for when you want to un-error one specific warning: -Wno-error=switch makes -Wswitch warnings not be errors, even when -Werror is out here being all dramatic and in effect.

Every controllable warning's message shows you which option controls it โ€” that's the whole point โ€” so you can take that option straight back to -Werror= or -Wno-error= like we just talked about. (You can hide the option from the message with the -fno-diagnostics-show-option flag if you're feeling shy. ๐Ÿ™ˆ)

Heads up though: -Werror=foo automatically implies -Wfoo. But -Wno-error=foo implies literally nothing. Not a single thing. It's giving "no thoughts, head empty." ๐Ÿ’€

  • -Wfatal-errors โ€” the compiler just โœจgives upโœจ on the first error instead of trying to keep going and printing a whole pile more error messages. No cap, this one's for when you can't handle the secondhand embarrassment of a hundred errors at once.

so there's a whole genre of options that start with -W, and you can request a ton of specific warnings that way โ€” -Wimplicit, for instance, asks for warnings on implicit declarations. Every one of these specific warning options has a negative twin that starts with -Wno-, which turns it off (-Wno-implicit, iconic behaviour). This manual only lists one of the two forms โ€” whichever one isn't the default โ€” so don't come for me when you only see half the set. ๐Ÿซถ

For language-specific stuff, go check out C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. And more warnings can be produced by enabling the static analyzer;

ok and this next bit is important, so pay attention bestie ๐ŸŽ€ โ€” some options, like -Wall and -Wextra, turn on other options, like -Wunused, which then turn on further options, like -Wunused-value. It's a whole chain of enabling, very main character energy. The combined effect of positive and negative forms is that more specific options have priority over less specific ones, regardless of where they sit on the command line. For options of the same specificity, the last one takes effect (last one wins, as per usual). And options enabled or disabled via pragmas take effect as if they appeared at the end of the command-line. ๐Ÿฆ‹

Now, when you request an unrecognized warning option (say -Wunknown-warning), GCC hits you with a diagnostic saying the option is not recognized. But the -Wno- form is quirky: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are being produced anyway. Why? So you can use shiny new -Wno- options with old compilers. And if something goes wrong, the compiler will warn you that an unrecognized option is present. Balance. โญ

Also real talk: some warnings only hit different when optimizations are on too. -Wsuggest-final-types is way more effective with link-time optimization, and some other warnings may not be issued at all unless optimization is enabled. Optimizing generally improves the efficacy of control- and data-flow-sensitive warnings, but in some cases it may also cause false positives. ๐Ÿ™ƒ It's giving "trade-offs."


๐Ÿ’œ the pedantic zone ๐Ÿ’œ

  • -Wpedantic, -pedantic โ€” issues all the warnings demanded by strict ISO C and ISO C++, rejects all programs that use forbidden extensions, and rejects some other programs that don't follow ISO C and ISO C++. For ISO C, it follows whichever version of the ISO C standard your -std option specified.

Valid ISO C and ISO C++ programs should compile properly with or without this option (a rare few do need -ansi or a -std option specifying the required version of ISO C). But without this option, certain GNU extensions and traditional C and C++ features are supported too. With this option, they get rejected. ๐Ÿšซ

-Wpedantic does not throw warnings for the alternate keywords whose names begin and end with __. That alternate format also works to disable warnings for non-ISO __intN types, i.e. __intN__. Pedantic warnings are also disabled in the expression that follows "__extension__". But โ€” and I cannot stress this enough โ€” 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 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, plus some others for which diagnostics have been added. ๐Ÿ˜ญ

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

Where the standard specified with -std represents a GNU extended dialect of C, such as gnu90 or gnu99, there's a corresponding base standard โ€” the version of ISO C the GNU extended dialect is based on. Warnings from -Wpedantic are given where the base standard requires them. (It wouldn't make sense to give them only for features not in the specified GNU C dialect, because by definition the GNU dialects of C include all features the compiler supports with the given option, and there'd be nothing to warn about. ๐Ÿงš)

  • -pedantic-errors โ€” throws an error whenever the base standard (see -Wpedantic) requires a diagnostic, in some cases where there's undefined behavior at compile-time, and in some other cases that don't prevent compilation of programs that are valid according to the standard. And no, it is not equivalent to -Werror=pedantic โ€” there are errors enabled by this option and not by that one, and vice versa. They're different girlies. ๐Ÿ’…

๐Ÿ”ฅ -Wall ๐Ÿ”ฅ

This enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify so the warning stops), even when you're working with macros. It 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 users generally don't consider questionable, but which occasionally you might want to check for anyway; others warn about constructions that are necessary or hard to avoid in some cases, and there's no simple way to modify the code to suppress the warning. Some of them get enabled by -Wextra, but many of them have to be enabled individually. Sorry, no bundle deal on those. ๐Ÿ˜”

๐ŸŒˆ -Wextra ๐ŸŒˆ

This enables some extra warning flags that -Wall didn't already scoop up. (This option used to be called -W. The older name is still supported, but the newer name is more descriptive โ€” a glow-up, if you will. โœจ)

-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. That 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 only warns about C++ ABI compatibility problems if there's a check added later in a release series for an ABI issue discovered since the initial release. -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. See, it's all connected. ๐Ÿ•ธ๏ธ

Although an effort has been made to warn you about all of these cases, bestie, there are probably still some sneaky ones that aren't warned about even though G++ is literally out here generating incompatible code ๐Ÿ˜ญ. And yeah โ€” there are also cases where warnings get emitted even though the generated code is actually compatible. Life's messy like that.

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

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

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

This was fixed in -fabi-version=3.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

"union U" is now always passed in memory.

-Wno-changes-meaning (C++ and Objective-C++ only)

Okay so C++ is very particular about names ๐Ÿ’…: it requires that unqualified uses of a name within a class have the same meaning in the complete scope of the class. Which means declaring the name after using 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 you if an array subscript has type "char". This is a super common cause of error because programmers constantly forget that this type is signed on some machines ๐Ÿ™ˆ. This warning is enabled by -Wall.

-Wno-coverage-mismatch

Warns you if feedback profiles do not match when you're using the -fprofile-use option. If a source file gets 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 literally 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 you in case a function ends earlier than it begins, because of 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. That's it, that's the whole thing ๐ŸŽ€.

-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". Why do we care? Because 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 genuinely 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". Sneaky, right? ๐Ÿ‘‘

-Wduplicate-decl-specifier (C and Objective-C only)

Warns you if a declaration has a 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 the arguments you supplied have types appropriate to the format string you specified, and that the conversions specified in the format string actually 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. Cool of it, honestly ๐Ÿฆ‹.

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

-Wformat-overflow

-Wformat-overflow=level

Warns you about calls to formatted input/output functions such as "sprintf" and "vsprintf" that might overflow the destination buffer ๐Ÿ˜ฌ. When the exact number of bytes written by a format directive cannot be determined at compile-time it is estimated based on heuristics that depend on the level argument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives. Ngl, that's just how it goes ๐Ÿ’€.

  • -Wformat-overflow, -Wformat-overflow=1 โ€” level 1 of -Wformat-overflow, which is what you get when -Wformat is on, is the cautious bestie of the family: it only yells about calls that most likely overflow the buffer. At this level, numeric arguments to format directives with unknown values are assumed to have the value of one, and strings of unknown length are 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, are assumed to take on the value within the range that results in the most bytes on output. Like, for example, the call to sprintf below gets diagnosed because even with both a and b equal to zero, the terminating NUL character ('\0') appended by the function to the destination buffer will be written past its end. Bumping the buffer size up by a single byte is enough to dodge the warning, though it may not be enough to dodge the overflow itself. ๐Ÿซถ
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 trust issues (affectionate). It also warns about calls that might overflow the destination buffer given an argument of sufficient length or magnitude. At level 2, unknown numeric arguments are assumed to have the minimum representable value for signed types with a precision greater than 1, and the maximum representable value otherwise. Unknown string arguments whose length cannot be assumed to be bounded either by the directive's precision, or by a finite set of string literals they may evaluate to, or the character array they may point to, are assumed to be 1 character long.

At level 2, the call in the example above is again diagnosed โ€” but this time because with a equal to a 32-bit INT_MIN, the first %i directive will write some of its digits beyond the end of the destination buffer. To make the call safe regardless of the values of the two variables, the size of the destination buffer must be increased to at least 34 bytes. GCC literally includes the minimum size of the buffer in an informational note following the warning. ๐Ÿ˜ญ

An alternative to increasing the size of the destination buffer is to constrain the range of formatted values. The maximum length of string arguments can be bounded by specifying the precision in the format directive. When numeric arguments of format directives can be assumed to be bounded by less than the precision of their type, choosing an appropriate length modifier to the format specifier will reduce the required buffer size. For example, if a and b in the example above can be assumed to be within the precision of the short int type, then using either the %hi format directive or casting the argument to short reduces the maximum required size of the buffer to 24 bytes. 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, do not warn about zero-length formats. The C standard says zero-length formats are allowed, so like, let them live. โœจ
  • -Wformat-nonliteral โ€” if -Wformat is specified, also warn if the format string is not a string literal and so cannot be checked โ€” unless the format function takes its format arguments as a va_list.
  • -Wformat-security โ€” if -Wformat is specified, also warn about uses of format functions that represent possible security problems. At present, this warns about calls to printf and scanf functions where the format string is not a string literal and there are no format arguments, as in printf (foo);. This may be a security hole if the format string came from untrusted input and contains %n. ๐Ÿšจ (This is currently a subset of what -Wformat-nonliteral warns about, but in future warnings may be added to -Wformat-security that are not included in -Wformat-nonliteral โ€” so don't go assuming they're the same thing, bestie.)
  • -Wformat-signedness โ€” if -Wformat is specified, also warn if the format string requires an unsigned argument and the argument is signed, and vice versa. signed vs unsigned drama, caught in 4K ๐ŸŽ€
  • -Wformat-truncation, -Wformat-truncation=level โ€” warn about calls to formatted input/output functions such as snprintf and vsnprintf that might result in output truncation. When the exact number of bytes written by a format directive cannot be determined at compile-time, it is estimated based on heuristics that depend on the level argument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives โ€” no cap, it's a tradeoff. Except as noted otherwise, the option uses the same logic as -Wformat-overflow.
    • -Wformat-truncation, -Wformat-truncation=1 โ€” level 1 of -Wformat-truncation, enabled by -Wformat, employs a conservative approach that warns only about calls to bounded functions whose return value is unused and that will most likely result in output truncation.
    • -Wformat-truncation=2 โ€” level 2 warns also about calls to bounded functions whose return value is used and that might result in truncation given an argument of sufficient length or magnitude. ๐Ÿ”ฅ
  • -Wformat-y2k โ€” if -Wformat is specified, also warn about strftime formats that may yield only a two-digit year. it's giving Y2K panic and honestly? valid ๐Ÿ’€
  • -Wnonnull โ€” warn about passing a null pointer for arguments marked as requiring a non-null value by the nonnull function attribute. -Wnonnull is included in -Wall and -Wformat. It can be disabled with the -Wno-nonnull option.
  • -Wnonnull-compare โ€” warn when comparing an argument marked with the nonnull function attribute against null inside the function. -Wnonnull-compare is included in -Wall. It can be disabled with the -Wno-nonnull-compare option.
  • -Wnull-dereference โ€” warn if the compiler detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer. This option is only active when -fdelete-null-pointer-checks is active, which is enabled by optimizations in most targets. The precision of the warnings depends on the optimization options used. ๐Ÿ™ˆ
  • -Winfinite-recursion โ€” warn about infinitely recursive calls. The warning is effective at all optimization levels but requires optimization in order to detect infinite recursion in calls between two or more functions. -Winfinite-recursion is included in -Wall.

Compare with -Wanalyzer-infinite-recursion, which provides a similar diagnostic but is implemented in a different way (as part of -fanalyzer). same vibe, different machinery ๐ŸŒ€

  • -Winit-self (C, C++, Objective-C and Objective-C++ only) โ€” warn about uninitialized variables that are initialized with themselves. Note this option can only be used with the -Wuninitialized option.

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

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

This warning is enabled by -Wall in C++. (i = i is not the self-care we were talking about, bestie ๐Ÿ˜ญ)

  • -Wno-implicit-int (C and Objective-C only) โ€” this option controls warnings when a declaration does not specify a type. This warning is enabled by default in C99 and later dialects of C, and also by -Wall.
  • -Wno-implicit-function-declaration (C and Objective-C only) โ€” this option controls warnings when a function is used before being declared. This warning is enabled by default in C99 and later dialects of C, and also by -Wall. The warning is made into an error by -pedantic-errors. โš ๏ธ
  • -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. matchy matchy ๐ŸŽ€
  • -Wimplicit-fallthrough=n โ€” warn when a switch case falls through. For example:
switch (cond)
  {
  case 1:
    a = 1;
    break;
  case 2:
    a = 2;
  case 3:
    a = 3;
    break;
  }

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

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

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

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

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

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

Okay so 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. Like this:

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 if the return type of a function has a type qualifier such as const. For ISO C, that kind of qualifier has no effect, since the value returned by a function is not an lvalue. For C++, the warning is only emitted for scalar types or void. ISO C prohibits qualified void return types on function definitions, so those return types always get a warning even without this option. This warning is also enabled by -Wextra.
  • -Wno-ignored-attributes (C and C++ only) โ€” controls warnings when an attribute is ignored. This is different from -Wattributes: it warns whenever the compiler decides to drop an attribute, not that the attribute is unknown, used in the wrong place, etc. This warning is enabled by default.
  • -Wmain โ€” warns if the type of main is suspicious. main should be a function with external linkage, returning int, taking either zero arguments, two, or three arguments of appropriate types. This warning is enabled by default in C++ and is enabled by either -Wall or -Wpedantic.
  • -Wmisleading-indentation (C and C++ only) โ€” warns when the indentation of the code does not reflect the block structure. Specifically, a warning is issued for if, else, while, and for clauses with a guarded statement that does not use braces, followed by an unguarded statement with the same indentation. In this 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 this example:

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

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

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

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

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

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

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

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

This warning is enabled by -Wall.

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

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

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

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

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

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

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

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

  • -Wparentheses โ€” warns if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about.

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

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

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

  • -Wno-self-move (C++ and Objective-C++ only) โ€” this one clocks when a value gets moved to itself with std::move. and like... that move does literally nothing, bestie. it's giving "I did something" but nothing happened ๐Ÿ˜ญ
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 in the C and C++ standards. ok so this is the messy one, let me explain ๐Ÿ’…

The C and C++ standards define the order expressions get evaluated in terms of sequence points โ€” which are basically a partial ordering between parts of your program: the stuff that runs before the sequence point, and the stuff that runs 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) gets evaluated, before a function is called (but after its arguments and the expression naming the called function get 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 โ€” like, if two functions get called in one expression with no sequence point between them, nobody's specifying which one goes first. however!! the standards committee ruled that function calls don't overlap. no cap ๐Ÿ”ฅ

It's also not specified when, between sequence points, modifications to object values actually take effect. programs that depend on that have undefined behavior. the C and C++ standards say: "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 ๐Ÿ’€

examples of code with undefined behavior: a = a++;, a[n] = b[n++] and a[i++] = i;. some more complicated cases don't get diagnosed by this option, and it might give you the occasional false positive, but overall it's been found pretty effective at catching this sort of problem โœจ

the C++17 standard defines the order of evaluation in more cases: specifically it requires the right-hand side of an assignment to be evaluated before the left-hand side, so the examples above stop being undefined. but this option still warns about them, to help people avoid writing code that's undefined in C and earlier revisions of C++. so it's a "for your own good" situation ๐Ÿ™ˆ

the standard is worded confusingly, so there's some debate over what the sequence point rules precisely mean in subtle cases. links to discussions of the problem (including proposed formal definitions) live 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 โ€” don't warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns. (which is, like, a little scary but ok, your call bestie ๐Ÿ’€)
  • -Wreturn-type โ€” warn whenever a function is defined with a return type that defaults to int. also warns about any return statement with no return value in a function whose return type is not void (falling off the end of the function body counts as returning without a value ๐Ÿ‘€).

For C only: warn about a return statement with an expression in a function whose return type is void, unless the expression type is also void. as a GNU extension, that latter case is accepted without a warning unless -Wpedantic is used. attempting to use the return value of a non-void function other than main that flows off the end by reaching the closing curly brace that terminates the function? 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 isn't used. rude but true.

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

  • -Wno-shift-count-negative โ€” controls warnings if a shift count is negative. 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. enabled by default.
  • -Wshift-negative-value โ€” warn if you're left shifting a negative value. enabled by -Wextra in C99 (and newer) and C++11 to C++17 modes ๐ŸŒธ
  • -Wno-shift-overflow, -Wshift-overflow=n โ€” these two control warnings about left shift overflows. levels below, bestie โฌ‡๏ธ
    • -Wshift-overflow=1 โ€” this is the warning level of -Wshift-overflow and it's enabled by default in C99 and C++11 modes (and newer). this 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), because signed left shifts always wrap. slay ๐ŸŽ€
    • -Wshift-overflow=2 โ€” this level also warns about left-shifting 1 into the sign bit, unless C++14 mode (or newer) is active.
  • -Wswitch โ€” warn whenever a switch statement has an index of enumerated type and is missing 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's a default label. enabled by -Wall โญ
  • -Wswitch-default โ€” warn whenever a switch statement doesn't have a default case. simple as that ๐Ÿ’…
  • -Wswitch-enum โ€” warn whenever a switch statement has an index of enumerated type and is missing a case for one or more of the named codes of that enumeration. case labels outside the enumeration range also provoke warnings here too. the only difference between -Wswitch and this option: this one warns about an omitted enumeration code even if there's a default label. so it's the strict one ๐Ÿ‘‘
  • -Wno-switch-bool โ€” don't warn when a switch statement has an index of boolean type and the case values are outside the range of a boolean type. you can suppress this warning by casting the controlling expression to a type other than bool. like so:
switch ((int) (a == 4))
  {
  ...
  }

this warning is enabled by default for C and C++ programs โœจ

  • -Wno-switch-outside-range โ€” controls warnings when a switch case has a value outside of its respective type range. enabled by default for C and C++ programs.
  • -Wno-switch-unreachable โ€” don't warn when a switch statement contains statements between the controlling expression and the first case label, which will never be executed. example time:
switch (cond)
  {
   i = 15;
  ...
   case 5:
  ...
  }

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

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

this warning is enabled by default for C and C++ programs ๐Ÿฆ‹

  • -Wsync-nand (C and C++ only) โ€” warn when the __sync_fetch_and_nand and __sync_nand_and_fetch built-in functions get used. these functions changed semantics in GCC 4.4, so like... watch out ๐Ÿ‘€
  • -Wtrivial-auto-var-init โ€” warn when -ftrivial-auto-var-init can't initialize the automatic variable. a common situation is an automatic variable declared between the controlling expression and the first case label of a switch statement.
  • -Wunused-but-set-parameter โ€” warn whenever a function parameter is assigned to but otherwise unused (aside from its declaration). to suppress this warning, use the unused attribute. this warning is also enabled by -Wunused together with -Wextra ๐Ÿ’œ
  • -Wunused-but-set-variable โ€” warn whenever a local variable is assigned to but otherwise unused (aside from its declaration). enabled by -Wall. to suppress it, use the unused attribute. this warning is also enabled by -Wunused, which is enabled by -Wall. (yes, double-enabled, it's that serious ๐Ÿ˜ค)
  • -Wunused-function โ€” warn whenever a static function is declared but not defined, or a non-inline static function is unused. enabled by -Wall ๐ŸŽ€
  • -Wunused-label โ€” warn whenever a label is declared but not used. enabled by -Wall. to suppress this warning, use the unused attribute.
  • -Wunused-local-typedefs (C, Objective-C, C++ and Objective-C++ only) โ€” warn when a typedef locally defined in a function isn't used. enabled by -Wall ๐ŸŒˆ
  • -Wunused-parameter โ€” warn whenever a function parameter is unused aside from its declaration. to suppress this warning, use the unused attribute.
  • -Wno-unused-result โ€” don't warn if a caller of a function marked with the warn_unused_result attribute doesn't use its return value. the default is -Wunused-result.
  • -Wunused-variable โ€” warn whenever a local or static variable is unused aside from its declaration. this option implies -Wunused-const-variable=1 for C, but not for C++. 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 literally just vibing and contributing nothing. So -Wunused-const-variable=1 gets switched on by -Wunused-variable for C, but not for C++. In C this declares variable storage, but in C++ this is not an error since const variables take the place of #defines.

To suppress this warning use the unused attribute.

  • -Wunused-const-variable=1 โ€” this is the warning level that is enabled by -Wunused-variable for C. It warns only about unused static const variables defined in the main compilation unit, but not about static const variables declared in any header.
  • -Wunused-const-variable=2 โ€” this warning level also warns for unused constant static variables in headers (excluding system headers). This is the warning level of -Wunused-const-variable and must be explicitly requested since in C++ this isn't an error and in C it might be harder to clean up all headers included. โœจ

  • -Wunused-value โ€” warns whenever a statement computes a result that is explicitly not used ๐Ÿ™ˆ like, why did you even compute it then. To suppress this warning cast the unused expression to void. This includes an expression-statement or the left-hand side of a comma expression that contains no side effects. For example, an expression such as x[i,j] causes a warning, while x[(void)i,j] does not. iykyk ๐Ÿ’…

This warning is enabled by -Wall.

  • -Wunused โ€” all the above -Wunused options combined. the whole squad, together ๐Ÿซถ

In order to get a warning about an unused function parameter, you must either specify -Wextra -Wunused (note that -Wall implies -Wunused), or separately specify -Wunused-parameter. no cap.

  • -Wuninitialized โ€” warns if an object with automatic or allocated storage duration is used without having been initialized ๐Ÿ˜ญ In C++, also warn if a non-static reference or non-static const member appears in a class without constructors.

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

If you want to warn about code that uses the uninitialized value of the variable in its own initializer, use the -Winit-self option.

These warnings occur for individual uninitialized elements of structure, union or array variables as well as for variables that are uninitialized as a whole. They do not occur for variables or elements declared volatile. Because these warnings depend on optimization, the exact variables or elements for which there are warnings depend on the precise optimization options and version of GCC used. โญ

Note that there may be no warning about a variable that is used only to compute a value that itself is never used, because such computations may be deleted by data flow analysis before the warnings are printed. the compiler literally deletes the evidence first ๐Ÿ’€

In C++, this warning also warns about using uninitialized objects in member-initializer-lists. For example, GCC warns about b being uninitialized in the following 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 with a memory consistency argument that 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 โ€” okay so for an object with automatic or allocated storage duration, if there exists a path from the function entry to a use of the object that is initialized, but there exist some other paths for which the object is not initialized, the compiler emits a warning if it cannot prove the uninitialized paths are not executed at run time. "maybe" is doing so much heavy lifting here ๐Ÿ˜ญ

In addition, passing a pointer (or in C++, a reference) to an uninitialized object to a const-qualified function argument is also diagnosed by this warning. (-Wuninitialized is issued for built-in functions known to read the object.) Annotating the function with attribute access (none) indicates that the argument isn't used to access the object and avoids the warning. cute little escape hatch ๐ŸŽ€

These warnings are only possible in optimizing compilation, because otherwise GCC does not keep track of the state of variables.

These warnings are made optional because GCC may not be able to determine when the code is correct in spite of appearing to have an error. Here is one example of how this can happen:

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

If the value of y is always 1, 2 or 3, then x is always initialized, but GCC doesn't know this. To suppress the warning, you need to provide a default case with assert(0) or similar code. GCC is not a mind reader bestie, it needs receipts ๐Ÿงš

This option also warns when a non-volatile automatic variable might be changed by a call to longjmp. The compiler sees only 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. As a result, you may get a warning even when there is in fact no problem because longjmp cannot in fact be called at the place that would cause a problem. ๐Ÿ’€ structural paranoia, 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 is encountered that is not understood by GCC ๐Ÿฆ‹ If this command-line option is used, warnings are even issued for unknown pragmas in system header files. This is not the case if the warnings are only enabled by the -Wall command-line option. so -Wall is chill about system headers, but this flag is like "no, all of them" ๐Ÿ’…
  • -Wno-pragmas โ€” do not warn about misuses of pragmas, such as incorrect parameters, invalid syntax, or conflicts between pragmas. See also -Wunknown-pragmas. the "mind your own business" setting ๐Ÿ™ˆ
  • -Wno-prio-ctor-dtor โ€” do not warn if a priority from 0 to 100 is used for constructor or destructor ๐ŸŒˆ The use of constructor and destructor attributes allow you to assign a priority to the constructor/destructor to control its order of execution before main is called or after it returns. The priority values must be greater than 100 as the compiler reserves priority values between 0--100 for the implementation. so 0โ€“100 is the compiler's VIP section, stay out of it โœจ

  • -Wstrict-aliasing โ€” this option is only active when -fstrict-aliasing is active. It warns about code that might break the strict aliasing rules that the compiler is using for optimization ๐Ÿ”ฅ The warning does not catch all cases, but does attempt to catch the more common pitfalls. It is included in -Wall. It is equivalent to -Wstrict-aliasing=3.
  • -Wstrict-aliasing=n โ€” this option is only active when -fstrict-aliasing is active. It warns about code that might break the strict aliasing rules that the compiler is using for optimization. Higher levels correspond to higher accuracy (fewer false positives). Higher levels also correspond to more effort, similar to the way -O works. -Wstrict-aliasing is equivalent to -Wstrict-aliasing=3.
    • Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels do not warn but -fstrict-aliasing still breaks the code, as it has very few false negatives. However, it has many false positives. Warns for all pointer conversions between possibly incompatible types, even if never dereferenced. Runs in the front end only. it's giving "snitch about everything and let god sort it out" ๐Ÿ’€
    • Level 2: Aggressive, quick, not too precise. May still have many false positives (not as many as level 1 though), and few false negatives (but possibly more than level 1). Unlike level 1, it only warns when an address is taken. Warns about incomplete types. Runs in the front end only.
    • Level 3 (default for -Wstrict-aliasing): Should have very few false positives and few false negatives. Slightly slower than levels 1 or 2 when optimization is enabled. Takes care of the common pun+dereference pattern in the front end: *(int*)&some_float. If optimization is enabled, it also runs in the back end, where it deals with multiple statement cases using flow-sensitive points-to information. Only warns when the converted pointer is dereferenced. Does not warn about incomplete types. the balanced icon, the main character ๐ŸŒŸ

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

An optimization that assumes that signed overflow does not occur is perfectly safe if the values of the variables involved are such that overflow never does, in fact, occur. Therefore this warning can easily give a false positive: a warning about code that is not actually a problem ๐Ÿ˜ญ To help focus on important issues, several warning levels are defined. No warnings are issued for the use of undefined signed overflow when estimating how many iterations a loop requires, in particular when determining whether a loop will be executed at all.

  • -Wstrict-overflow=1 โ€” warn about cases that are both questionable and easy to avoid. For example the compiler simplifies x + 1 > x to 1. This level of -Wstrict-overflow is enabled by -Wall; higher levels are not, and must be explicitly requested. ๐Ÿ’…
  • -Wstrict-overflow=2 โ€” bestie this one's extra: it also clocks other cases where a comparison gets folded into a constant. Like abs (x) >= 0 โ€” iconic simplification, but only legit when signed integer overflow is undefined, because abs (INT_MIN) overflows right back to INT_MIN, which is literally less than zero ๐Ÿ˜ญ. And btw, -Wstrict-overflow with no level at all is the same as -Wstrict-overflow=2.
  • -Wstrict-overflow=3 โ€” now we're warning about other comparisons getting simplified too, fr fr. Example: x + 1 > 1 becomes x > 0. Cute, but we're watching you ๐Ÿ‘€.
  • -Wstrict-overflow=4 โ€” and now also any simplifications not covered by the cases above. Example: (x * 10) / 5 gets simplified to x * 2. Math girlies stay winning ๐Ÿ’….
  • -Wstrict-overflow=5 โ€” the most dramatic level ๐Ÿ”ฅ. Warns when the compiler shrinks the magnitude of a constant involved in a comparison. Example: x + 2 > y becomes x + 1 >= y. Heads up though โ€” this is only reported at the highest warning level because this simplification applies to so many comparisons, so this level gives you a very large number of false positives. Not me getting spammed ๐Ÿ™ˆ.
  • -Wstring-compare โ€” warns on calls to strcmp and strncmp whose result is already determined to be either zero or non-zero in equality tests, because one argument's length is bigger than the size of the array the other one lives in (or bigger than the bound, in strncmp's case). Basically these calls could be mistakes ๐Ÿšฉ. Look at this poor strcmp down here โ€” it gets diagnosed because its result is necessarily non-zero no matter what's actually in the array a:
extern char a[4];
void f (char *d)
{
  strcpy (d, "string");
  ...
  if (0 == strcmp (a, d))   // cannot be true
    puts ("a and d are the same");
}

Also, -Wstring-compare is enabled by -Wextra โœจ.

  • -Wno-stringop-overflow
  • -Wstringop-overflow
  • -Wstringop-overflow=*type* โ€” this trio warns 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 destination's size. That argument is only meaningful 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 bigger than the largest possible object, or at most SIZE_MAX / 2 bytes. It gives its best results with optimization on, but it can still catch a small subset of simple buffer overflows even without optimization in calls to GCC built-in functions like __builtin_memcpy that correspond to the standard functions. Either way, the option only warns about a subset of the buffer overflows that the corresponding overflow-checking built-ins detect. For example, it flags the strcpy call below because it copies at least 5 characters (the string "blue", terminating NUL included) into a buffer of size 4:
enum Color { blue, purple, yellow };
const char* f (enum Color clr)
{
  static char buf [4];
  const char *str;
  switch (clr)
    {
      case blue: str = "blue"; break;
      case purple: str = "purple"; break;
      case yellow: str = "yellow"; break;
    }

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

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

  • -Wstringop-overflow
  • -Wstringop-overflow=1 โ€” the -Wstringop-overflow=1 option uses type-zero Object Size Checking to determine the sizes of destination objects. At this setting it does not warn for writes past the end of subobjects of larger objects accessed by pointers, unless the size of the largest surrounding object is known. When the destination could be one of several objects, it assumes it's the largest of them. On Linux systems, with optimization 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 โ€” the -Wstringop-overflow=2 option uses type-one Object Size Checking to determine the sizes of destination objects. At this setting it warns about overflows when writing to members of the largest complete objects whose exact size is known. But it does not warn for excessive writes to those same members of unknown objects referenced by pointers, since those pointers may point to arrays with an unknown number of elements ๐Ÿคท. This is the default setting of the option.
  • -Wstringop-overflow=3 โ€” the -Wstringop-overflow=3 option uses type-two Object Size Checking to determine the sizes of destination objects. At this setting it warns about overflowing the smallest object or data member. This is the most restrictive setting of the option that may result in warnings for safe code โ€” so like, it will call out your innocent code sometimes ๐Ÿ˜ญ.
  • -Wstringop-overflow=4 โ€” the -Wstringop-overflow=4 option uses type-three Object Size Checking to determine the sizes of destination objects. At this setting it warns about overflowing any data members, and when the destination is one of several objects it uses the size of the largest of them to decide whether to warn. Same energy as -Wstringop-overflow=3: this setting may also 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 ๐Ÿ‘€๐Ÿ“–. Also: option -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 ๐Ÿค.

In this next example, the call to strncat specifies a bound that's less than the length of the source string. So the copy of the source gets truncated, and 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);
}

Another example: this strncpy call copies into 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 gets diagnosed. If you're not expecting a NUL-terminated result, call memcpy instead to avoid the warning:

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

And in this one, the strncpy call uses the size of the destination buffer as the bound. If the source string's length is equal to or greater than that size, the copy won't be NUL-terminated. So yeah, also diagnosed ๐Ÿ’€. To avoid it, 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, when a character array is genuinely meant to store a sequence of bytes with no terminating NUL, you can annotate that array with the attribute nonstring to avoid this warning. But heads up bestie: those arrays are not suitable arguments to functions that expect NUL-terminated strings ๐Ÿšซ. To help catch accidental misuse of such 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 a structure's trailing array field if that attribute's available โ€” otherwise according to the level of the option -fstrict-flex-arrays=level.

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

  • when level=1, warnings get 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 get 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 get 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 a glow-up โœจ. The attributes currently supported are listed below.
    • -Wsuggest-attribute=pure
    • -Wsuggest-attribute=const
    • -Wsuggest-attribute=noreturn
    • -Wmissing-noreturn
    • -Wsuggest-attribute=malloc โ€” these warn about functions that might be candidates for the pure, const, noreturn or malloc attributes. The compiler only warns for functions visible in other compilation units, or (in the pure and const case) if it can't prove the function returns normally. A function counts as returning normally if it doesn't contain an infinite loop and doesn't return abnormally by throwing, calling abort, or trapping ๐Ÿชค. This analysis needs option -fipa-pure-const, which is enabled by default at -O and higher. Higher optimization levels improve the accuracy of the analysis ๐Ÿ“ˆ.
  • -Wsuggest-attribute=format, -Wmissing-format-attribute โ€” bestie, this one points at function pointers that might be candidates for format attributes. Keyword: might. These are only possible candidates, not absolute ones, okay? ๐Ÿ˜Œ GCC's lil guess is that function pointers with format attributes that get used in assignment, initialization, parameter passing or return statements should have a corresponding format attribute in the resulting type. Translating to human: 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, not a verdict. GCC guesses 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 for which format attributes are appropriate may not be detected. So it's giving vibes-based matching, not certainty. ๐Ÿฆ‹

  • -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 leads to a call to another cold function โ€” think wrappers of C++ throw or fatal error reporting functions leading to abort. ๐Ÿ’€
  • -Walloc-zero โ€” warns about calls to allocation functions decorated with attribute alloc_size that specify zero bytes, including those to the built-in forms of the functions aligned_alloc, alloca, calloc, malloc, and realloc. Why do we care? Because the behavior of these functions when called with a zero size differs among implementations (and in the case of realloc has been deprecated), so relying on it may result in subtle portability bugs and should be avoided. ๐Ÿ™ˆ no cap, don't do it.
  • -Walloc-size-larger-than=<byte-size> โ€” warns about calls to functions decorated with attribute alloc_size that attempt to allocate objects larger than the specified number of bytes, or where the result of the size computation in an integer type with infinite precision would exceed the value of PTRDIFF_MAX on the target. -Walloc-size-larger-than=PTRDIFF_MAX is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of SIZE_MAX or more or by -Wno-alloc-size-larger-than. ๐ŸŽ€
  • -Wno-alloc-size-larger-than โ€” 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. ๐Ÿ‘‘
  • -Walloca-larger-than=<byte-size> โ€” warns on calls to alloca with an integer argument whose value is either zero, or that is not bounded by a controlling predicate that limits its value to at most byte-size. It also warns for calls to alloca where the bound value is unknown. 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. However, if -Walloca-larger-than=500 were passed, the compiler would emit a warning. see, context matters bestie ๐Ÿ’–

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

Note, that even seemingly correct code involving signed integers could cause a warning:

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

In the above example, n could be negative, causing a larger than expected argument to be implicitly cast into the alloca call. ๐Ÿ’€

This option also warns when alloca is used in a loop. ๐Ÿ”ฅ

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

See also -Wvla-larger-than=<byte-size>. ๐ŸŒˆ

  • -Wno-alloca-larger-than โ€” 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 B<-Wconversion>
  c = c + 1; // only warns with B<-Warith-conversion>
}
  • -Warray-bounds, -Warray-bounds=<n> โ€” warns about out of bounds subscripts or offsets into arrays. This warning is enabled by -Wall. It is more effective when -ftree-vrp is active (the default for -O2 and above) but a subset of instances are issued even without optimization. โญ

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

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

โ€ฆand the attributes it's clocking are alloc_align, alloc_size, cold, const, hot, leaf, malloc, nonnull, noreturn, nothrow, pure, returns_nonnull, and returns_twice. Bestie that's the whole guest list ๐Ÿ’…

-Wattribute-alias is literally just -Wattribute-alias=1, and that's the default, no cap. Wanna mute it? Either -Wno-attribute-alias or -Wattribute-alias=0, pick your fighter โœจ

  • -Wbidi-chars=[none|unpaired|any|ucn] โ€” okay this one is kinda spooky ๐Ÿ‘ป it warns you about possibly-misleading UTF-8 bidirectional control characters chilling in comments, string literals, character constants, and identifiers. These little gremlins can flip left-to-right writing direction into right-to-left (and vice versa), which causes chaos between the logical order and the visual order. It can be actually dangerous โ€” like, it might look like a chunk of code isn't commented out when it fr fr is. ๐Ÿ˜ญ

GCC supports three levels of this warning. The default is -Wbidi-chars=unpaired, which warns about improperly terminated bidi contexts. -Wbidi-chars=none turns the whole thing off. -Wbidi-chars=any warns about any use of bidirectional control characters. ๐Ÿšฉ

By default this warning does not warn about UCNs. But you can turn that checking on with -Wbidi-chars=unpaired,ucn or -Wbidi-chars=any,ucn. And heads up: -Wbidi-chars=ucn is valid, and it's equivalent to -Wbidi-chars=unpaired,ucn โ€” but only if you didn't already specify a previous -Wbidi-chars=any. iykyk ๐Ÿงš

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

Enabled by -Wall. โœ…

  • -Wbool-operation โ€” warns about suspicious operations on boolean-typed expressions. Bitwise negation of a boolean? Very likely a bug in your program, ngl ๐Ÿ’€. For C, this one also warns about incrementing or decrementing a boolean, which rarely makes sense. (In C++, decrementing a boolean is always invalid. Incrementing a boolean is invalid in C++17, and deprecated otherwise.) ๐Ÿšซ

Enabled by -Wall.

  • -Wduplicated-branches โ€” warns when an if-else has identical branches. It catches cases like:
if (p != NULL)
  return 0;
else
  return 0;

It does not warn when both branches contain just a null statement. It also warns for conditional operators:

int i = x ? *p : *p;

like girl why ๐Ÿ˜ญ both sides are the same thing.

  • -Wduplicated-cond โ€” warns about duplicated conditions in an if-else-if chain. For instance, it'll warn on this:
if (p->q != NULL) { ... }
else if (p->q != NULL) { ... }

ma'am you already checked that ๐Ÿ’…

  • -Wframe-address โ€” warns when __builtin_frame_address or __builtin_return_address is called with an argument greater than 0. Those calls may return indeterminate values or straight-up crash the program ๐Ÿ˜ฌ. Included in -Wall.
  • -Wno-discarded-qualifiers (C and Objective-C only) โ€” don't warn if type qualifiers on pointers are being discarded. Typically the compiler yells when a const char * variable gets passed to a function that takes a char * parameter. This option suppresses that warning. ๐Ÿซถ
  • -Wno-discarded-array-qualifiers (C and Objective-C only) โ€” don't warn if type qualifiers on arrays that are pointer targets are being discarded. Typically the compiler warns when a const int (*)[] variable gets passed to a function taking an int (*)[] parameter. Use this to suppress it.
  • -Wno-incompatible-pointer-types (C and Objective-C only) โ€” don't warn when there's a conversion between pointers with incompatible types. This one's for cases that -Wno-pointer-sign doesn't cover โ€” that one handles pointer argument passing or assignment with different signedness.
  • -Wno-int-conversion (C and Objective-C only) โ€” don't warn about incompatible integer-to-pointer and pointer-to-integer conversions. Note this is about implicit conversions; for explicit ones you'd reach for -Wno-int-to-pointer-cast and -Wno-pointer-to-int-cast. ๐ŸŽ€
  • -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 are 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. โœจ

  • -Wno-div-by-zero โ€” don't warn about compile-time integer division by zero. Floating-point division by zero is not warned about, since it can be a totally legitimate way of obtaining infinities and NaNs. ๐ŸŒˆ
  • -Wsystem-headers โ€” print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed, based on the assumption that they usually don't indicate real problems and would only 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. However โ€” note that using -Wall together with this option does not warn about unknown pragmas in system headers. For that, -Wunknown-pragmas must also be used. gotcha ๐Ÿซก
  • -Wtautological-compare โ€” warns if a self-comparison always evaluates to true or false. It catches all kinds of mistakes 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. ๐Ÿ’€

Enabled by -Wall.

  • -Wtrampolines โ€” warns about trampolines generated for pointers to nested functions. A trampoline is 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 and thus needs no special treatment. But for most targets it's made up of code, and thus requires the stack to be made executable for the program to work properly. ๐Ÿ˜ณ no cap, that's a whole security vibe.
  • -Wfloat-equal โ€” warns if floating-point values are used in equality comparisons. ๐Ÿšฉ

The idea behind this: sometimes it's convenient (for the programmer) to consider floating-point values as approximations to infinitely precise real numbers. If that's what you're doing, then you need to compute โ€” by analyzing the code, or in some other way โ€” the maximum or likely maximum error the computation introduces, and allow for it when performing comparisons (and when producing output, but that's a whole different problem). In particular, instead of testing for equality, you should check whether the two values have ranges that overlap โ€” and that's done with the relational operators. So equality comparisons are probably mistaken. periodt ๐Ÿ’…

  • -Wtraditional (C and Objective-C only) โ€” warns about certain constructs that behave differently in traditional C vs ISO C. Also warns about ISO C constructs that have no traditional C equivalent, and/or problematic constructs that should be avoided. Buckle up bestie, it'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 didn't 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 # doesn't appear as the first character on the line. It also suggests you hide directives like #pragma that traditional C doesn't understand by indenting them. Some traditional implementations don't recognize #elif, so this option suggests avoiding it altogether.
    • A function-like macro that appears without arguments.
    • The unary plus operator.
    • The U integer constant suffix, or the F or L floating-point constant suffixes. (Traditional C does support the L suffix on integer constants.) Note that these suffixes appear in macros defined in the system headers of most modern systems, e.g. the _MIN/_MAX macros in <limits.h>. Use of these macros in user code might normally lead to spurious warnings โ€” however, GCC's integrated preprocessor has enough context to avoid warning in these cases. ๐Ÿซถ
    • A function declared external in one block and then used after the end of the block.
    • A switch statement has an operand of type long.
    • A non-static function declaration follows a static one. This construct is not accepted by some traditional C compilers.
    • The ISO type of an integer constant has a different width or signedness from its traditional type. This warning is only issued if the base of the constant is ten. I.e. hexadecimal or octal values, which typically represent bit patterns, are not warned about.
    • Usage of ISO string concatenation is detected.
    • Initialization of automatic aggregates.
    • Identifier conflicts with labels. Traditional C lacks a separate namespace for labels.
    • Initialization of unions. If the initializer is zero, the warning is omitted. This is done under the assumption that the zero initializer in user code appears conditioned on e.g. __STDC__ to avoid missing initializer warnings, and relies on default initialization to zero in the traditional C case.
  • Prototype conversions between fixed/floating-point values and vice versa โ€” okay so if a prototype makes a type conversion happen that wouldnโ€™t happen without the prototype, thatโ€™s a whole vibe check fail ๐Ÿ˜ญ. The absence of these prototypes when compiling with traditional C causes serious problems. This is a subset of the possible conversion warnings; for the full set use -Wtraditional-conversion.
    • Use of ISO C style function definitions โ€” yes this warns about that, but it intentionally does not fire for prototype declarations or variadic functions, because these ISO C features show up in your code when you use libibertyโ€™s traditional C compatibility macros, PARAMS and VPARAMS ๐Ÿซถ. This warning is also bypassed for nested functions because that feature is already a GCC extension and thus not relevant to traditional C compatibility.
  • -Wtraditional-conversion (C and Objective-C only) โ€” warns if a prototype causes a type conversion that is different from what would happen to the same argument in the absence of a prototype โœจ. This includes conversions of fixed point to floating and vice versa, and conversions changing the width or signedness of a fixed-point argument except when the same as the default promotion.
  • -Wdeclaration-after-statement (C and Objective-C only) โ€” warns when a declaration is found after a statement in a block ๐ŸŽ€. This construct, known from C++, was introduced with ISO C99 and is by default allowed in GCC. It is not supported by ISO C90.
  • -Wshadow โ€” warns whenever a local variable or type declaration shadows another variable, parameter, type, class member (in C++), or instance variable (in Objective-C), or whenever a built-in function is shadowed ๐Ÿ‘€. Note that in C++, the compiler warns if a local variable shadows an explicit typedef, but not if it shadows a struct/class/enum. If this warning is enabled, it includes also all instances of local shadowing. This means that -Wno-shadow=local and -Wno-shadow=compatible-local are ignored when -Wshadow is used. Same as -Wshadow=global.
  • -Wno-shadow-ivar (Objective-C only) โ€” do not warn whenever a local variable shadows an instance variable in an Objective-C method ๐Ÿ™ˆ.
  • -Wshadow=global โ€” warns for any shadowing. Same as -Wshadow ๐Ÿ’….
  • -Wshadow=local โ€” warns when a local variable shadows another local variable or parameter ๐ŸŒธ.
  • -Wshadow=compatible-local โ€” warns when a local variable shadows another local variable or parameter whose type is compatible with that of the shadowing variable ๐Ÿฆ‹. In C++, type compatibility here means the type of the shadowing variable can be converted to that of the shadowed variable. The creation of this flag (in addition to -Wshadow=local) is based on the idea that when a local variable shadows another one of incompatible type, it is most likely intentional, not a bug or typo, as shown in the following example:
for (SomeIterator i = SomeObj.begin(); i != SomeObj.end(); ++i)
{
  for (int i = 0; i < N; ++i)
  {
    ...
  }
  ...
}

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

This warning is also enabled by -Wshadow=local โœจ.

  • -Wlarger-than=byte-size โ€” warns whenever an object is defined whose size exceeds byte-size ๐Ÿ”ฅ. -Wlarger-than=PTRDIFF_MAX is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of SIZE_MAX or more or by -Wno-larger-than.

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

  • -Wno-larger-than โ€” disables -Wlarger-than= warnings ๐Ÿ’€. The 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 ๐ŸŽ€. The computation done to determine the stack frame size is approximate and not conservative. The actual requirements may be somewhat greater than byte-size even if you do not get a warning. In addition, any space allocated via alloca, variable-length arrays, or related constructs is not included by the compiler when determining whether or not to issue a warning.

-Wframe-larger-than=PTRDIFF_MAX is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of SIZE_MAX or more or by -Wno-frame-larger-than.

  • -Wno-frame-larger-than โ€” disables -Wframe-larger-than= warnings ๐ŸŒˆ. The option is equivalent to -Wframe-larger-than=SIZE_MAX or larger.
  • -Wfree-nonheap-object โ€” warns when attempting to deallocate an object that was either not allocated on the heap, or by using 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 is 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. Any space allocated via alloca, variable-length arrays, or related constructs is included by the compiler when determining whether or not to issue a warning.

The message is in keeping 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 the option can be disabled either by specifying byte-size of SIZE_MAX or more or by -Wno-stack-usage.

  • -Wno-stack-usage โ€” disables -Wstack-usage= warnings ๐Ÿ’…. The option is equivalent to -Wstack-usage=SIZE_MAX or larger.
  • -Wunsafe-loop-optimizations โ€” warns if the loop cannot be optimized because the compiler cannot assume anything on the bounds of the loop indices ๐Ÿ‘€. With -funsafe-loop-optimizations warn if the compiler makes such assumptions.
  • -Wno-pedantic-ms-format (MinGW targets only) โ€” when used in combination with -Wformat and -pedantic without GNU extensions, this option disables the warnings about 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++, warn also 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 ๐Ÿ™ˆ. This usually means that the pointer was meant to be dereferenced. For example:
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 due to the limited range of the data type, but do 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 is 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 get the other -Wall warnings, use -trigraphs -Wall -Wno-trigraphs.

  • -Wundef โ€” warns if an undefined identifier is evaluated in an #if directive โœจ. Such identifiers are 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 is used if it is 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.

Built-in macros, macros defined on the command line, and macros defined in include files are not warned about. slay, they get a pass ๐Ÿ’…

Heads up bestie: if a macro is actually used, but only used in skipped conditional blocks, then the preprocessor reports it as unused ๐Ÿ˜ญ to dodge the warning in that case, you might improve the scope of the macro's definition by, for example, moving it into the first skipped block. Alternatively, you could provide a dummy use with something like:
#if defined the_macro_causing_the_warning
#endif
  • -Wno-endif-labels โ€” do not warn whenever an "#else" or an "#endif" are followed by text. This sometimes happens in older programs with code of the form
#if FOO
...
#else FOO
...
#endif FOO

The second and third "FOO" should be in comments. This warning is on by default. iykyk

  • -Wbad-function-cast (C and Objective-C only) โ€” warn when a function call is cast to a non-matching type. For example, warn if a call to a function returning an integer type is cast to a pointer type. sir that is not the same thing ๐Ÿ˜ญ
  • -Wc90-c99-compat (C and Objective-C only) โ€” warn about features not present in ISO C90, but present in ISO C99. For instance, warn about use of variable length arrays, "long long" type, "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__". time-travel vibes, but backwards ๐Ÿ•ฐ๏ธ
  • -Wc99-c11-compat (C and Objective-C only) โ€” warn about features not present in ISO C99, but present in ISO C11. For instance, warn about use of anonymous structures and unions, "_Atomic" type qualifier, "_Thread_local" storage-class specifier, "_Alignas" specifier, "Alignof" operator, "_Generic" keyword, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows "__extension__".
  • -Wc11-c2x-compat (C and Objective-C only) โ€” warn about features not present in ISO C11, but present in ISO C2X. For instance, warn about omitting the string in "_Static_assert", use of [[]] syntax for attributes, use of decimal floating-point types, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows "__extension__". the future is now and it's judging your old code โœจ
  • -Wc++-compat (C and Objective-C only) โ€” warn about ISO C constructs that are outside of the common subset of ISO C and ISO C++, e.g. request for implicit conversion from "void *" to a pointer to non-"void" type. caught in 4K crossing the language border ๐Ÿฆ‹
  • -Wc++11-compat (C++ and Objective-C++ only) โ€” warn 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) โ€” warn about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014. This warning is enabled by -Wall.
  • -Wc++17-compat (C++ and Objective-C++ only) โ€” warn about C++ constructs whose meaning differs between ISO C++ 2014 and ISO C++ 2017. This warning is enabled by -Wall.
  • -Wc++20-compat (C++ and Objective-C++ only) โ€” warn about C++ constructs whose meaning differs between ISO C++ 2017 and ISO C++ 2020. This warning is enabled by -Wall. the glow-up timeline continues ๐Ÿ‘‘
  • -Wno-c++11-extensions (C++ and Objective-C++ only) โ€” do not warn about C++11 constructs in code being compiled using 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 using 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 using 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 using 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 using an older C++ standard. Even without this option, some C++23 constructs will only be diagnosed if -Wpedantic is used. five of these in a row, she ate ๐Ÿ’€
  • -Wcast-qual โ€” warn 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 *". literally stripping a qualifier, rude ๐Ÿ’…

Also warn when making a cast that introduces a type qualifier in an unsafe way. For example, casting "char **" to "const char **" is unsafe, as 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';
  • -Wcast-align โ€” warn 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. alignment check, bestie ๐Ÿ”
  • -Wcast-align=strict โ€” warn 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 exceptions, we're not playing ๐Ÿ™ˆ
  • -Wcast-function-type โ€” warn 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. "void (*) (void)" is the main character that gets along with everyone ๐Ÿซถ
  • -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 have been very careful about using "const" in declarations and prototypes. Otherwise, it is just a nuisance. This is why we did not make -Wall request these warnings. ngl, that last line is such a mood ๐Ÿ˜ญ

When compiling C++, warn about the deprecated conversion from string literals to "char *". This warning is enabled by default for C++ programs.

  • -Wclobbered โ€” warn for variables that might be changed by "longjmp" or "vfork". This warning is also enabled by -Wextra. your variable got jump-scared ๐Ÿ’€
  • -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. mixing C++ and Fortran in one command is giving chaotic group project energy ๐ŸŒ€

  • -Wconversion โ€” warn 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. implicit conversions are lowkey sneaky, keep an eye on them ๐Ÿ‘€

  • -Wdangling-else โ€” warn about constructions where there may be confusion to which "if" statement an "else" branch belongs. Here is 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 indentation the programmer chose. When there is 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 is 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. the braces are the boundaries bestie, set them ๐ŸŽ€

  • -Wdangling-pointer
  • -Wdangling-pointer=n โ€” okay bestie, this one's a whole vibe check on pointers (or C++ references) to objects with automatic storage duration that you're out here using after their lifetime has ended ๐Ÿ’€. That includes local variables declared in nested blocks, compound literals, and other unnamed temporary objects. It also warns you about stashing the address of such objects in escaped pointers. The warning is enabled at all optimization levels, but ngl it may yield different results with optimization than without.

-Wdangling-pointer=1

At level 1 the warning diagnoses only unconditional uses of dangling pointers. 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';
        }

In the following function the store of the address of the local variable x in the escaped pointer *p also triggers the warning.

        void g (int **p)
        {
          int x = 7;
          // warning: storing the address of a local variable in *p
          *p = &x;
        }

-Wdangling-pointer=2

At level 2, in addition to unconditional uses the warning also diagnoses conditional uses of dangling pointers.

For example, because the array a in the following function is out of scope when the pointer s that was set to point is 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");
          ...
        }

-Wdangling-pointer=2 is included in -Wall. slay, free coverage ๐Ÿซถ

  • -Wdate-time โ€” warns when macros __TIME__, __DATE__ or __TIMESTAMP__ show up, because they might prevent bit-wise-identical reproducible compilations ๐Ÿ˜ญ. Your builds can't be twins if the timestamps keep changing, yk?
  • -Wempty-body โ€” warns if an empty body occurs in an if, else or do while statement. 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++ enumerated type mismatches in conditional expressions are also diagnosed and the warning is enabled by default. In C this warning is enabled by -Wall.
  • -Wenum-conversion โ€” warns when a value of enumerated type is implicitly converted to a different enumerated type. This warning is enabled by -Wextra in C.
  • -Wenum-int-mismatch (C and Objective-C only) โ€” warns about mismatches between an enumerated type and an integer type in declarations. 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. However, since the choice of the underlying type of an enumerated type is implementation-defined, such 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 ๐Ÿ‘€. This only warns about variables that are initialized when they are declared. This warning is only supported for C and Objective-C; in C++ this sort of branch is an error in any case.

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

  • -Wsign-compare โ€” warns when a comparison between signed and unsigned values could produce an incorrect result when the signed value is converted to unsigned. In C++, this warning is also enabled by -Wall. In C, it 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 ๐Ÿ”‡. In C, this option is enabled also by -Wconversion.
  • -Wfloat-conversion โ€” warns for implicit conversions that reduce the precision of a real value. This includes conversions from real to integer, and from higher precision real to lower precision real values ๐Ÿ“. This option is also enabled by -Wconversion.
  • -Wno-scalar-storage-order โ€” do not warn on suspicious constructs involving reverse scalar storage order.
  • -Wsizeof-array-div โ€” warns about divisions of two sizeof operators when the first one is applied to an array and the divisor does not equal the size of the array element. In such a case, the computation will not yield the number of elements in the array, which is likely what the user intended ๐Ÿ˜ญ. This warning warns e.g. about
        int fn ()
        {
          int arr[10];
          return sizeof (arr) / sizeof (short);
        }

This warning is enabled by -Wall.

  • -Wsizeof-pointer-div โ€” warns for suspicious divisions of two sizeof expressions that divide the pointer size by the element size, which is the usual way to compute the array size but won't work out correctly with pointers. This warning warns e.g. about sizeof (ptr) / sizeof (ptr[0]) if ptr is not an array, but a pointer. This warning is enabled by -Wall. classic gotcha fr fr ๐Ÿ’…
  • -Wsizeof-pointer-memaccess โ€” warns for suspicious length parameters to certain string and memory built-in functions if the argument uses sizeof. This warning triggers for example for memset (ptr, 0, sizeof (ptr)); if ptr is not an array, but a pointer, and suggests a possible fix, or about memcpy (&foo, ptr, sizeof (&foo));.

-Wsizeof-pointer-memaccess also warns about calls to bounded string copy functions like strncat or strncpy that specify as the bound a sizeof expression of the source array. For example, in the following function the call to strncat specifies the size of the source string as the bound. That is almost certainly a mistake and so the call is diagnosed.

        void make_file (const char *name)
        {
          char path[PATH_MAX];
          strncpy (path, name, sizeof path - 1);
          strncat (path, ".text", sizeof ".text");
          ...
        }

The -Wsizeof-pointer-memaccess option is enabled by -Wall.

  • -Wno-sizeof-array-argument โ€” do not warn when the sizeof operator is applied to a parameter that is declared as an array in a function definition. This warning is enabled by default for C and C++ programs.
  • -Wmemset-elt-size โ€” warns for suspicious calls to the memset built-in function, if the first argument references an array, and the third argument is a number equal to the number of elements, but not equal to the size of the array in memory ๐Ÿคจ. This indicates that 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 is an expression that is folded to zero, or a cast of zero to some type, it is far less likely that the arguments have been mistakenly transposed and no warning is emitted. This warning is enabled by -Wall.
  • -Waddress โ€” warns about suspicious uses of 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 packed member of 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. Also warns when the operands of a logical operator are the same:
        extern int a;
        if (a < 0 && a < 0) { ... }

like bestieโ€ฆ that's the same check 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 so you can hush that warning by wrapping the LHS in parentheses, like this:

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

This warning is enabled by -Wall.

  • -Waggregate-return โ€” Warn if any functions that return structures or unions are defined or called. (In languages where you can return an array, this also elicits a warning.) like, noted, bestie ๐Ÿ’…
  • -Wno-aggressive-loop-optimizations โ€” Warn if in a loop with constant number of iterations the compiler detects undefined behavior in some statement during one or more of the iterations. compiler said โ€œI saw what you did thereโ€ ๐Ÿ˜ญ
  • -Wno-attributes โ€” Do not warn if an unexpected "__attribute__" is used, such as unrecognized attributes, function attributes applied to variables, etc. This does not stop errors for incorrect use of supported attributes. so it mutes the vibe check, not the actual errors, got it

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. not me thinking they were the same thing ๐Ÿ™ˆ

  • -Wno-builtin-declaration-mismatch โ€” Warn 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);
}

header files really said โ€œinclude me or catch these warningsโ€ ๐Ÿ˜ญ

  • -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__. macro glow-up, no questions asked โœจ
  • -Wstrict-prototypes (C and Objective-C only) โ€” Warn 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.) old-school vibes but make it typed
  • -Wold-style-declaration (C and Objective-C only) โ€” Warn 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. the C Standard said โ€œmove, static goes firstโ€ ๐Ÿ’€
  • -Wold-style-definition (C and Objective-C only) โ€” Warn 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. standards really be moving the goalposts, fr fr
  • -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. K&R said โ€œtrust meโ€ and the compiler said โ€œabsolutely notโ€ ๐Ÿซถ

  • -Wmissing-prototypes (C and Objective-C only) โ€” Warn 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++. prototype bestie check ๐Ÿ’–
  • -Wmissing-declarations โ€” Warn 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. the header file said โ€œyou forgot to introduce meโ€ ๐Ÿ˜ญ
  • -Wmissing-field-initializers โ€” Warn 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. selective hearing, but for warnings ๐Ÿ’…

  • -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. bestie really forgot the second requires and the compiler noticed ๐Ÿ˜ญ

  • -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. parentheses are the original โ€œno thoughts just vibesโ€ fix ๐ŸŽ€

  • -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. implementation-defined values said โ€œdonโ€™t put me 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. LITERALLY impossible to see. not me being dramatic, thatโ€™s the manpage ๐Ÿ˜ญ

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. confusable characters are the original catfish ๐Ÿ’…

  • -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. warning about a warning? iconic behavior, honestly
  • -Wno-deprecated โ€” Do not warn about usage of deprecated features. let them live their deprecated little life ๐Ÿฆ‹
  • -Wno-deprecated-declarations โ€” Do not warn about uses of functions, variables, and types marked as deprecated by using the "deprecated" attribute. deprecated but make it quiet ๐Ÿคซ
  • -Wno-overflow โ€” Do not warn about compile-time overflow in constant expressions. math said โ€œoverflowโ€ and you said โ€œnot todayโ€ ๐Ÿ’€
  • -Wno-odr โ€” lowkey the compiler will call out One Definition Rule violations while it's doing link-time optimization. It's on by default, so like, it's already watching ๐Ÿ‘€
  • -Wopenacc-parallelism โ€” warns you when your OpenACC parallelism choices are giving "could be better, bestie" energy. Potentially suboptimal = it's not mad, it's just disappointed ๐Ÿซถ
  • -Wopenmp-simd โ€” fires when the vectorizer cost model straight-up overrides the OpenMP simd directive you set. Rude tbh. If you wanna loosen the cost model, the -fsimd-cost-model=unlimited option is right there โœจ
  • -Woverride-init (C and Objective-C only) โ€” warns you when a field that was initialized and has no side effects gets overridden by your designated initializers. Like, why did you even write the first one ๐Ÿ’€

This one is folded into -Wextra. Want all the other -Wextra goodies but not this one? Just do -Wextra -Wno-override-init. Problem solved ๐ŸŽ€

  • -Wno-override-init-side-effects (C and Objective-C only) โ€” the opposite vibe: don't warn when an initialized field with side effects gets overridden via designated initializers. This warning is enabled by default ๐Ÿ”ฅ
  • -Wpacked โ€” warns when a struct gets the packed attribute but the attribute literally changes nothing about the layout or size. Those structs can end up mis-aligned for basically zero benefit. Case in point: here, f.x inside struct bar is misaligned even though struct bar itself doesn't have the packed attribute:
        struct foo {
          int x;
          char a, b, c, d;
        } __attribute__((packed));
        struct bar {
          char z;
          struct foo f;
        };
  • -Wnopacked-bitfield-compat โ€” story time ๐Ÿงš the GCC 4.1, 4.2 and 4.3 series ignore the packed attribute on bit-fields of type char. That got fixed in GCC 4.4, but the fix can shift your structure layout around. GCC tells you when the offset of such a field changed in GCC 4.4. For example, there's no longer 4 bits of padding between field a and b in this struct:
        struct foo
        {
          char a:4;
          char b:8;
        } __attribute__ ((packed));

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

  • -Wpacked-not-aligned (C, C++, Objective-C and Objective-C++ only) โ€” warns when a struct field with explicitly specified alignment, sitting inside a packed struct or union, ends up misaligned. So on struct S below you'd get something like warning: alignment 1 of 'struct S' is less than 8:
        struct __attribute__ ((aligned (8))) S8 { char a[8]; };
        struct __attribute__ ((packed)) S {
          struct S8 s8;
        };

This warning is enabled by -Wall.

  • -Wpadded โ€” warns when padding sneaks into a struct, whether it's there to align an element or to align the whole struct. Sometimes you can rearrange the fields to shrink the padding and make the struct smaller โ€” so this is basically a free glow-up hint ๐Ÿ’…
  • -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. Redundant = not the main character ๐ŸŒธ
  • -Wrestrict โ€” warns when an object referenced by a restrict-qualified parameter (or, in C++, a __restrict-qualified parameter) gets aliased by another argument, or when copies between such objects overlap. Example: this strcpy call is trying to truncate the string by replacing its first characters with the last four โ€” but because the call writes the terminating NUL into a[4], the copies overlap and the call gets diagnosed:
        void foo (void)
        {
          char a[] = "abcd1234";
          strcpy (a, a + 4);
          ...
        }

-Wrestrict catches some simple-overlap instances even with no optimization, but it's at its 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. Nested externs, in this economy? ๐Ÿ˜ญ
  • -Winline โ€” warns when a function declared inline doesn't actually get inlined. Even with this option on, the compiler stays quiet about failures to inline functions declared in system headers.

The compiler runs a whole bunch of heuristics to decide whether to inline something โ€” it factors in the size of the function being inlined, and how much inlining has already happened in the current function. So like, seemingly tiny changes in your source can make -Winline warnings appear or vanish out of nowhere. It's giving chaos ๐Ÿฆ‹

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

This variable is meant for controlling class layout, so you can dodge 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 storing to one won't force accesses to the other to reload the cache line ๐Ÿ”ฅ

By default, --param destructive-interference-size and --param constructive-interference-size get set based on whatever -mtune option is active โ€” typically the L1 cache line size for that particular target CPU, and 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, bestie.

If ABI stability matters to you โ€” 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.

If you're confident your use of the variable doesn't affect ABI outside a single build of your project, you can kill the warning with -Wno-interference-size โœจ

  • -Wint-in-bool-context โ€” warns about suspicious use of integer values where boolean values are expected. Think conditional expressions (?:) using non-boolean integer constants in boolean context, like if (a <= b ? 2 : 3). Or left shifting signed integers in boolean context, like for (a = 0; 1 << a; a++);. Same deal for all kinds of multiplications regardless of data type. Enabled by -Wall ๐Ÿ’€
  • -Wno-int-to-pointer-cast โ€” suppresses warnings from casts to pointer type of an integer of a different size. In C++, casting to a pointer type of smaller size is an error. Wint-to-pointer-cast is enabled by default.
  • -Wno-pointer-to-int-cast (C and Objective-C only) โ€” suppresses warnings from casts from a pointer to an integer type of a different size.
  • -Winvalid-pch โ€” warns if a precompiled header is chillin' in the search path but can't be used. It's there, it's just not serving ๐Ÿ™ˆ
  • -Winvalid-utf8 โ€” warns if an invalid UTF-8 character is found. This one's on by default for C++23 if -finput-charset=UTF-8 is used, and it gets turned into an error with -pedantic-errors โญ
  • -Wno-unicode โ€” don't diagnose invalid forms of delimited or named escape sequences that get 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. Wanna silence it? -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 inhibit the warning messages, use -Wno-variadic-macros.
  • -Wno-varargs โ€” don't warn about questionable usage of the macros used to handle variable arguments, like va_start. These warnings are enabled by default.
  • -Wvector-operation-performance โ€” warns when a vector operation isn't implemented through the SIMD capabilities of the architecture. Mainly your go-to for performance tuning. A vector operation can be implemented:
    • "piecewise" โ€” the scalar operation is performed on every vector element
    • "in parallel" โ€” the vector operation uses scalars of wider type, which normally is more performance efficient
    • "as a single scalar" โ€” the vector fits into a scalar type
  • -Wvla โ€” warns if a variable-length array is used in the code. And -Wno-vla prevents the -Wpedantic warning about the variable-length array. Teamwork ๐Ÿซถ
  • -Wvla-larger-than=byte-size โ€” with this on, 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. Works similarly to how -Walloca-larger-than=byte-size works, except, y'know, with variable-length arrays.

Heads up: GCC may optimize small variable-length arrays of a known value into plain arrays, so the warning might not fire for those ones.

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

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

  • -Wno-vla-larger-than โ€” disables -Wvla-larger-than= warnings. This 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 via 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. Fail to provide arguments of sufficient size, or access more than the maximum number of elements, and you may get diagnosed ๐Ÿ’…

So like, for example, the warning pops off for these redeclarations โ€” because the first one lets you pass an array of literally any size to f, and then the second one is like "no bestie, that array argument needs at least n elements." Plus, if you call f and the VLA bound parameter you hand it is bigger than the actual VLA bound? Yeah, that warns too. ๐Ÿ™ˆ

        void f (int n, int[n]);
        // warning: argument 2 previously declared as a VLA
        void f (int, int[]);

        void g (int n)
        {
            if (n > 4)
              return;
            int a[n];
            // warning: access to a by f may be out of bounds
            f (sizeof a, a);
          ...
        }

-Wvla-parameter is included in -Wall. And the -Warray-parameter option triggers warnings for similar problems but with ordinary array arguments (iykyk). โœจ

  • -Wvolatile-register-var โ€” warns you if a register variable is declared volatile. Lowkey important: that volatile modifier does not stop all the optimizations that might eliminate reads and/or writes to register variables. So don't think it's a magic shield, bestie. ๐Ÿ’… This warning is enabled by -Wall.
  • -Wxor-used-as-pow (C, C++, Objective-C and Objective-C++ only) โ€” warns about uses of ^, the exclusive or operator, where it looks like the user meant exponentiation. Specifically, the warning fires when the left-hand side is the decimal constant 2 or 10 and the right-hand side is also a decimal constant.

Real talk: in C and C++, ^ means exclusive or, whereas in some other languages (e.g. TeX and some versions of BASIC) it means exponentiation. So 2^8 is giving... not 256, babe. ๐Ÿ˜ญ

This warning is enabled by default. You can silence it by converting one of the operands to hexadecimal โ€” cute little escape hatch. ๐ŸŽ€

  • -Wdisabled-optimization โ€” warns if a requested optimization pass is disabled. Ngl, this generally does not mean there's anything wrong with your code; it just means GCC's optimizers couldn't handle your code effectively. Usually the problem is your code is too big or too complex โ€” GCC straight up refuses to optimize programs when the optimization itself is likely to take inordinate amounts of time. It's not you, it's the compile time. ๐Ÿ’€
  • -Wpointer-sign (C and Objective-C only) โ€” warns for pointer argument passing or assignment with different signedness. Only supported for C and Objective-C, bestie. It's implied by -Wall and by -Wpedantic, and you can turn it off with -Wno-pointer-sign.
  • -Wstack-protector โ€” this option is only active when -fstack-protector is active. It warns about functions that are not protected against stack smashing. ๐Ÿ›ก๏ธ
  • -Woverlength-strings โ€” warns about string constants that are longer than the "minimum maximum" length specified in the C standard. Modern compilers generally allow string constants that are much longer than the standard's minimum limit, but very portable programs should avoid using longer strings. Portable queen behavior only. ๐Ÿ‘‘

The limit applies after string constant concatenation, and it does not count the trailing NUL. In C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 does not specify a normative minimum maximum, so we do not diagnose overlength strings in C++. Not us forgetting, it's just not specified. ๐Ÿซถ

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

  • -Wunsuffixed-float-constants (C and Objective-C only) โ€” issues a warning for any floating constant that does not have a suffix. When used together with -Wsystem-headers it warns about such constants in system header files too. This can be useful when preparing code to use with the FLOAT_CONST_DECIMAL64 pragma from the decimal floating-point extension to C99. Get those suffixes in order, bestie. ๐Ÿ“
  • -Wno-lto-type-mismatch โ€” during the link-time optimization, do not warn about type mismatches in global declarations from different compilation units. Requires -flto to be enabled. Enabled by default.
  • -Wno-designated-init (C and Objective-C only) โ€” suppresses warnings when a positional initializer is used to initialize a structure that has been marked with the designated_init attribute.

๐ŸŒˆ Options That Control Static Analysis ๐ŸŒˆ

  • -fanalyzer โ€” this option enables a static analysis of program flow which looks for "interesting" interprocedural paths through the code, and issues warnings for problems found on them. It's the drama-detector of compiler flags. ๐Ÿ”

Heads up though: this analysis is much more expensive than other GCC warnings. Like, highkey expensive. ๐Ÿ˜ญ

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 is a bug-finding tool, rather than a tool for proving program correctness. So don't come for it when it's wrong sometimes โ€” that's literally the deal. ๐Ÿ’…

The analyzer is only suitable for use on C code in this release. C only, bestie. Periodt.

Enabling this option 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. Check your build, bestie. ๐Ÿงš

  • -Wanalyzer-too-complex โ€” if -fanalyzer is enabled, the analyzer uses various heuristics to attempt to explore the control flow and data flow in the program, but these can be defeated by sufficiently complicated code. (Rude, honestly.)

By default, the analysis silently stops if the code is too complicated for the analyzer to fully explore and it reaches an internal limit. The -Wanalyzer-too-complex option warns if this occurs. So you actually find out instead of it ghosting you. ๐Ÿ‘ป

  • -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). Math not mathing, basically. ๐Ÿงฎ

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, suggesting that the pointer could have been NULL. Such cases suggest that the check for NULL is either redundant, or that it needs to be moved to before the pointer is dereferenced. Bestie. Check first. Then dereference. The order is the whole point. ๐Ÿ˜ญ

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

This diagnostic is unlikely to be reported when any level of optimization is enabled, as GCC's optimization logic will typically consider such checks for NULL as being redundant, and optimize them away before the analyzer "sees" them. Hence optimization should be disabled when attempting to trigger this diagnostic. Ironic, I know. ๐Ÿ’€

  • -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. One close per file, babe, that's the rule. ๐Ÿ™ˆ

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. Double-free is giving main character energy in the worst way. ๐Ÿ”ฅ

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 (such as writing a password to a log file). Bestie. Not the password in the log file. ๐Ÿ˜ญ Please.

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 (such as code within an OS kernel that copies a partially-initialized struct on the stack to user space). Uninit struct goes on a little field trip to user space. Not the vibe. ๐Ÿšจ

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. Read the file you opened for reading, bestie. It's literally in the name. ๐Ÿ’…

โ€ฆand it also drags you for code paths where a function with attribute fd_arg_read (N) gets called with a file descriptor that was opened O_WRONLY at referenced argument N, or a function with attribute fd_arg_write (N) gets called with an fd opened O_RDONLY at referenced argument N. Like babe, you opened it read-only and now you're trying to write to it?? the audacity ๐Ÿ˜ญ

  • -Wno-analyzer-fd-double-close โ€” this one needs -fanalyzer to be on (it's enabled by it), so use -Wno-analyzer-fd-double-close to turn it back off ๐Ÿ’…

It warns about paths through your code where a file descriptor can get closed more than once. double-dipping. not it.

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

  • -Wno-analyzer-fd-leak โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-fd-leak to disable it ๐Ÿซถ

Warns about paths through your code where an open file descriptor justโ€ฆ gets leaked. gone. never closed. absolutely ghosted you ๐Ÿ‘ป

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 โœจ

Warns about paths through your code where you try to do an operation in the wrong phase of a file descriptor's lifetime. iconic example: trying to call accept on a stream socket that hasn't had listen successfully called on it yet. girl it's not 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 ๐ŸŒธ

Warns about paths through your code where you do an operation on the wrong type of file descriptor. Example: trying socket operations on a file descriptor you got from open, or trying to use a stream socket operation on a datagram socket. bestie those are two completely different vibes ๐Ÿ˜ญ

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

Warns about paths through your code where a read or write is called on a closed file descriptor. she's closed, bestie, move on.

It also warns about paths where a function with attribute fd_arg (N), fd_arg_read (N) or fd_arg_write (N) gets 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 ๐Ÿ”ฅ

Warns about paths through your code where a file descriptor is used without being checked for validity. no vibe check at all. rude.

Also warns about paths where a function with attribute fd_arg (N), fd_arg_read (N) or fd_arg_write (N) gets 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 ๐Ÿฆ‹

Warns about paths through the code where a <stdio.h> FILE * stream object gets leaked.

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

Warns about paths through the code where free gets called on a non-heap pointer โ€” like an on-stack buffer, or a global. you cannot free the stack, bestie, that is not how any of this works ๐Ÿ˜ญ

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

Warns about paths through the code where floating-point arithmetic is used in places where you actually need precise computation. rn it only warns on floating-point operands used inside the calculation of an allocation size. just so you know ๐Ÿ‘‘

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

Warns about paths through the code that look like they lead to infinite recursion. we're going in circles and nobody's leaving ๐Ÿ”

Specifically: when the analyzer "sees" a recursive call, it compares the state of memory at the entry to the new frame against the memory 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 the recursion terminating, which suppresses the warning.

Heads up: this diagnostic is likely to miss cases of infinite recursion that the optimizer converts into iteration before the analyzer "sees" them. So optimization should be disabled when you're trying to trigger this diagnostic. fr fr ๐Ÿ’…

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

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

Warns about paths through the code where a NULL function pointer gets called. there's nothing there. void. empty. nobody's home. ๐Ÿ’€

  • -Wno-analyzer-malloc-leak โ€” requires -fanalyzer, which enables it; use -Wno-analyzer-malloc-leak to disable it ๐Ÿ’œ

Warns about paths through the code where a pointer allocated via an allocator gets leaked โ€” either malloc, or a function marked with attribute malloc. allocate then abandon. classic ๐Ÿ™ˆ

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

Warns about paths through the code where the wrong deallocation function gets called on a pointer value, based on which function allocated it. It'll flag mismatches between free, scalar delete and vector delete[], plus anything marked as allocator/deallocator pairs using attribute malloc. you don't get to break up with someone using a different breakup method, that's not how it works ๐Ÿ’”

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

Warns about paths through the code where a buffer is definitely read or written out-of-bounds. It applies to cases where the analyzer can work out a constant offset, and to accesses past the end of a buffer with a constant capacity too. It also does limited checking for accesses past the end when the offset and the capacity are 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 ๐Ÿซถ

Warns about paths through the code where a possibly-NULL value gets passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. "possibly" is doing a lot of heavy lifting there bestie ๐Ÿ˜ญ

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 โœจ

Warns about paths through the code where a possibly-NULL value gets dereferenced.

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

Warns about paths through the code where a value known to be NULL gets passed to a function argument marked with __attribute__((nonnull)) as requiring a non-NULL value. known. confirmed. no doubt. and you did it anyway ๐Ÿ’€

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

Warns about paths through the code where a value known to be NULL gets dereferenced.

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

Warns about paths through the code where a call to putenv gets passed a pointer to an automatic variable or an on-stack buffer. that memory is not sticking around, bestie, it's leaving the function ๐Ÿ’…

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

Warns about paths through the code where a shift is attempted with a negative count. shifting by negative amounts?? into the past?? ๐Ÿ˜ญ It's basically the same idea as the -Wshift-count-negative diagnostic that lives in the C/C++ front ends, except this one is built on analyzing interprocedural paths instead of just parsing the syntax tree. Tiny caveat though: the analyzer doesn't prioritize finding these paths, so false negatives are more likely here than with other warnings. ngl she's not really looking for this one ๐Ÿ‘€

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

This one's about shifts, bestie โ€” specifically the cursed kind ๐Ÿ’€ It flags paths through your code where a shift happens with a count that's greater than or equal to the precision of the operand's type. It's basically the same energy as the -Wshift-count-overflow diagnostic the C/C++ front ends have, except this one is built on analyzing interprocedural paths instead of just parsing the syntax tree โ€” way more detective work ๐Ÿ”. Lowkey important caveat though: the analyzer does not prioritize hunting these down, so false negatives are more likely here than with other warnings. Not it being a little lazy ๐Ÿ™ˆ

  • -Wno-analyzer-stale-setjmp-buffer โ€” ok so this one needs -fanalyzer to be enabled at all (that's what turns it on); use -Wno-analyzer-stale-setjmp-buffer to turn it off. It warns about paths through the code where longjmp gets called to rewind to a jmp_buf that relates to a setjmp call in a function that has already returned ๐Ÿ˜ญ

Here's the lore: when setjmp is called on a jmp_buf to record a rewind location, it records the stack frame. That stack frame becomes invalid the moment the function containing the setjmp call returns. So trying to rewind to it via longjmp would reference a stack frame that no longer exists โ€” and that likely leads to a crash (or worse). ๐Ÿซ 

  • -Wno-analyzer-tainted-allocation-size โ€” this warning requires both -fanalyzer and -fanalyzer-checker=taint to enable it; use -Wno-analyzer-tainted-allocation-size to disable it. It warns for paths where a value that could be under an attacker's control gets used as the size of an allocation without being sanitized ๐Ÿ˜ฑ meaning an attacker could inject an excessively large allocation and potentially cause a denial of service attack.

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

  • -Wno-analyzer-tainted-assertion โ€” requires both -fanalyzer and -fanalyzer-checker=taint; use -Wno-analyzer-tainted-assertion to disable. It warns for paths where a value that could be attacker-controlled is used as part of a condition without being sanitized first โ€” and that condition guards a call to a function marked with attribute noreturn (like the function __builtin_unreachable). Those functions typically signal abnormal termination of the program, e.g. assertion failure handlers. 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 ๐Ÿ˜ฌ
Heads up bestie: when assertion-checking is disabled, the assertions are typically 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. iykyk.

For the purpose of this warning, any function marked with attribute noreturn counts as a possible assertion failure handler, including __builtin_unreachable. And ngl, these functions are sometimes removed by the optimizer before the analyzer "sees" them โ€” so optimization should be disabled when you're trying to trigger this diagnostic. ๐Ÿงš

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

It can also report problematic constructions like

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

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

even though, strictly speaking, the above isn't an assertion failure. Periodt ๐Ÿ’…

  • -Wno-analyzer-tainted-array-index โ€” requires both -fanalyzer and -fanalyzer-checker=taint; use -Wno-analyzer-tainted-array-index to disable. It warns for paths where a value that could be attacker-controlled 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 โ€” requires both -fanalyzer and -fanalyzer-checker=taint; use -Wno-analyzer-tainted-divisor to disable. It warns for paths where a value that could be attacker-controlled 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 โ€” requires both -fanalyzer and -fanalyzer-checker=taint; use -Wno-analyzer-tainted-offset to disable. It warns for paths where a value that could be attacker-controlled 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 โ€” requires both -fanalyzer and -fanalyzer-checker=taint; use -Wno-analyzer-tainted-size to disable. It warns for paths where a value that could be attacker-controlled 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 โ€” needs -fanalyzer (which enables it); use -Wno-analyzer-unsafe-call-within-signal-handler to disable. It warns for paths where a function known to be async-signal-unsafe (like fprintf) is 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 (which enables it); use -Wno-analyzer-use-after-free to disable. It warns for paths where a pointer is used after a deallocator is called on it โ€” either free, or a deallocator referenced by attribute malloc ๐Ÿ˜ต

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 (which enables it); use -Wno-analyzer-use-of-pointer-in-stale-stack-frame to disable. It warns for paths where a pointer is dereferenced that points to a variable in a stale stack frame ๐Ÿซ 
  • -Wno-analyzer-va-arg-type-mismatch โ€” needs -fanalyzer (which enables it); use -Wno-analyzer-va-arg-type-mismatch to disable. It warns for interprocedural paths through the code where the analyzer detects an attempt to use va_arg to extract a value passed to a variadic call, but using a type that does not match the type of the expression 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 (which enables it); use -Wno-analyzer-va-list-exhausted to disable. It warns for interprocedural paths where the analyzer detects an attempt to use va_arg to access the next value passed to a variadic call โ€” except all of the values in the va_list have already been consumed ๐Ÿ˜ญ empty. gone. nothing left.

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 (which enables it); use -Wno-analyzer-va-list-leak to disable. It warns for interprocedural paths where the analyzer detects that va_start or va_copy has been called on a va_list without a corresponding call to va_end ๐Ÿ’ง
  • -Wno-analyzer-va-list-use-after-va-end โ€” needs -fanalyzer (which enables it); use -Wno-analyzer-va-list-use-after-va-end to disable. It warns for interprocedural paths where the analyzer detects an attempt to use a va_list after va_end has been called on it. va_list.
  • -Wno-analyzer-write-to-const โ€” needs -fanalyzer (which enables it); use -Wno-analyzer-write-to-const to disable. It warns for paths where the analyzer detects an attempt to write through a pointer to a const object ๐Ÿšซ But โ€” same caveat as before โ€” the analyzer doesn't prioritize detection of these paths, so false negatives are more likely relative to other warnings. ๐Ÿ™ƒ
  • -Wno-analyzer-write-to-string-literal โ€” needs -fanalyzer (which enables it); use -Wno-analyzer-write-to-string-literal to disable. It warns for paths where the analyzer detects an attempt to write through a pointer to a string literal ๐Ÿ˜ฑ (yes, the thing that lives in read-only memory, bestie, please don't). And again: the analyzer doesn't prioritize detection of such paths, so false negatives are more likely relative to other warnings.
  • -Wno-analyzer-use-of-uninitialized-value โ€” needs -fanalyzer (which enables it); use -Wno-analyzer-use-of-uninitialized-value to disable. It warns for paths through the code in which an uninitialized value is used ๐Ÿ‘ป

See CWE-457: Use of Uninitialized Variable (https://cwe.mitre.org/data/definitions/457.html).


The analyzer has hardcoded knowledge about the behavior of the following memory-management functions: ๐Ÿ‘€

  • alloca
  • 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 like, these ones for doing stuff with file descriptors:

  • open
  • close
  • creat
  • dup, dup2 and dup3
  • isatty
  • pipe, and pipe2
  • read
  • write
  • socket, bind, listen, accept, and connect

and the <stdio.h> stream girlies:

  • 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

aaaaand these besties too:

  • 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

Plus โ€” plot twist โ€” there's a whole bunch of functions with an __analyzer_ prefix that mean something special to the analyzer. Those are documented in the GCC Internals manual, iykyk ๐Ÿงš


Now for the lil knobs that control how far the exploration goes, we got these pertinent parameters:

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

  • -fanalyzer-call-summaries โ€” simplifies interprocedural analysis by computing the effect of certain calls instead of exploring, like, every single path through the function 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). Lowkey efficient.
  • -fanalyzer-checker=name โ€” restricts the analyzer to run just the named checker, and enables it. Some checkers are disabled by default (even with -fanalyzer), like the taint checker that implements -Wanalyzer-tainted-array-index, and you need this option to turn them on.
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's for the analyzer developers, periodt. By default the analyzer verifies that there's a feasible control flow path for each diagnostic it emits: that the conditions that hold aren't mutually exclusive. Diagnostics with no feasible path get 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, each statement gets its own edge. So granular, we love to see it โœจ
  • -fanalyzer-show-duplicate-count โ€” analyzer-dev coded: if multiple diagnostics have been detected as being duplicates of each other, it emits a note when reporting the best diagnostic, giving the number of additional diagnostics that were suppressed by the deduplication logic. Iconic, honestly.
  • -fno-analyzer-state-merge โ€” analyzer developers only, bestie. By default the analyzer tries to simplify analysis by merging sufficiently similar states at each program point as it builds its "exploded graph". With -fno-analyzer-state-merge this merging can be suppressed, for debugging state-handling issues.
  • -fno-analyzer-state-purge โ€” another dev-only one. By default the analyzer tries to simplify analysis by purging aspects of state at a program point that appear to no longer be relevant โ€” e.g. the values of locals that aren't accessed later in the function and which aren't relevant to leak analysis. With -fno-analyzer-state-purge this purging of state can be suppressed, for debugging state-handling issues.
  • -fno-analyzer-suppress-followups โ€” dev option again. By default the analyzer stops exploring an execution path after encountering certain diagnostics, to avoid potentially issuing a 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 will keep exploring such paths even after those diagnostics, which may be helpful for debugging issues in the analyzer, or for microbenchmarks for detecting undefined behavior. Chaotic but valid.

  • -fanalyzer-transitivity โ€” enables transitivity of constraints within the analyzer. Math girl summer ๐Ÿ’…
  • -fno-analyzer-undo-inlining โ€” analyzer developers, this way please. -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, leading to the interprocedural execution paths emitted by the analyzer containing function frames that don't correspond to those 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 this attempt to reconstruct the original frame information can be disabled, which may help when debugging issues in the analyzer.
  • -fanalyzer-verbose-edges โ€” analyzer developers only. It enables more verbose, lower-level detail in the descriptions of control flow within diagnostic paths. Spicy detail.
  • -fanalyzer-verbose-state-changes โ€” also dev-coded. 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. Note that -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. Your terminal is gonna be chatty.
  • -fdump-analyzer-callgraph โ€” dumps a representation of the call graph suitable for viewing with GraphViz to file.callgraph.dot. Aesthetic AND functional ๐ŸŒธ
  • -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. Fr it's giving art.
  • -fdump-analyzer-exploded-nodes โ€” emits diagnostics showing where nodes in the "exploded graph" are in relation to the program source.
  • -fdump-analyzer-exploded-nodes-2 โ€” dumps a textual representation of the "exploded graph" to file.eg.txt.
  • -fdump-analyzer-exploded-nodes-3 โ€” dumps a textual representation of the "exploded graph" to one dump file per node, to file.eg-id.txt. This is typically a large number of dump files. Like, a LOT of files. You've been warned ๐Ÿ’€
  • -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 internals into file.analyzer.json.gz. bestie i cannot stress this enough: the precise format is subject to change, so don't go building your whole personality around parsing it, mwah ๐Ÿ’…
  • -fdump-analyzer-state-purge โ€” so, same energy as -fdump-analyzer-supergraph (dump a representation of the "supergraph" that's suitable for viewing with GraphViz), except it also annotates the graph with info on what state will be purged at each node โœจ the graph gets written to file.state-purge.dot.
  • -fdump-analyzer-supergraph โ€” dumps representations of the "supergraph" suitable for viewing with GraphViz to file.supergraph.dot and to file.supergraph-eg.dot ๐Ÿฆ‹ these show all of the control flow graphs in the program, with interprocedural edges for calls and returns. The second dump contains annotations showing nodes in the "exploded graph" plus the diagnostics associated with them. it's giving โœจwhole program visionโœจ
  • -fdump-analyzer-untracked โ€” emits custom warnings with internal details, and those details are intended for analyzer developers ๐Ÿซถ so like, iykyk. not really a you-and-me situation, it's a them situation.

๐ŸŒธ Options for Debugging Your Program ๐ŸŒธ

okay so the whole vibe here: to tell GCC to emit extra information for use by a debugger, in almost all cases you need only to add -g to your other options ๐ŸŽ€ and 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. slay, they can share the aux ๐Ÿ’–

GCC allows you to use -g with -O. and the shortcuts taken by optimized code may occasionally be surprising, which is honestly so real of it ๐Ÿ˜ญ like: some variables you declared may not exist at all; flow of control may briefly move where you did not expect it; some statements may not be executed because they compute constant results or their values are already at hand; some statements may execute in different places because they have been moved out of loops. Nevertheless it is possible to debug optimized output โ€” which is why it's reasonable to use the optimizer for programs that might have bugs ๐Ÿ‘‘

If you are not using some other optimization option, consider using -Og with -g. With no -O option at all, some compiler passes that collect information useful for debugging do not run at all, so -Og may result in a better debugging experience. lowkey a glow-up, fr fr โœจ

  • -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 ๐Ÿ’€ so if you want to control for certain whether to generate the extra information, use -gvms (see below, it's right there).

  • -ggdb โ€” produces debugging information for use by GDB ๐ŸŽ€ which means: use the most expressive format available (DWARF, stabs, or the native format if neither of those are supported), including GDB extensions if at all possible. she's doing the most for you and honestly? icon behavior.
  • -gdwarf, -gdwarf-version โ€” produces debugging information in DWARF format (if that is supported) ๐Ÿฆ‹ the value of version may be either 2, 3, 4 or 5; the default version for most targets is 5 (with the exception of VxWorks, TPF and Darwin/Mac OS X, which default to version 2, and AIX, which defaults to version 4).

note that with DWARF Version 2, some ports require and always use some non-conflicting DWARF 3 extensions in the unwind tables ๐ŸŒˆ

Version 4 may require GDB 7.0 and -fvar-tracking-assignments for maximum benefit. Version 5 requires GDB 8.0 or higher. so like, check your GDB's vibe before you commit ๐Ÿ™ˆ

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. don't let the names gaslight you bestie, they're just old ๐ŸŽ€

  • -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. two formats, one queen, no drama ๐Ÿ’…
  • -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. ghosted, gone, nothing.
  • Level 1 produces CTF information for tracebacks only. This includes callsite information, but does not include type information. light info, just the receipts of who called whom ๐Ÿซถ
  • Level 2 produces type information for entities (functions, data objects etc.) at file-scope or global-scope only. the whole menu, but only at file/global scope, not going all nosy into locals.
  • -gvms โ€” produces debugging information in Alpha/VMS debug format (if that is supported) โญ this is the format used by DEBUG on Alpha/VMS systems. vintage! iconic! niche!
  • -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. yes bestie, the off switch ๐Ÿ’€
    • 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. it's giving โœจjust the highlightsโœจ
    • Level 3 includes extra information, such as all the macro definitions present in the program. Some debuggers support macro expansion when you use -g3 ๐Ÿ”ฅ she's an over-sharer and we love her for it.

If you use multiple -g options, with or without level numbers, the last such option is the one that is effective. last one wins, no take-backs, 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 ๐Ÿซถ no sneaky smooshing the two together, keep them separate like a healthy situationship.

  • -fno-eliminate-unused-debug-symbols โ€” by default, no debug information is produced for symbols that are not actually used. Use this option if you want debug information for all symbols ๐ŸŒˆ all of them. every last one. main character energy for the unused symbols too ๐Ÿ’…
  • -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, do it for compatibility, not for fun.
  • -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. so this flag is the "actually, don't smush them" option ๐Ÿ’…
  • -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. the "my paths are none of your business" tech, iykyk ๐ŸŽ€
  • -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. so it's already doing its thing, no need to micromanage ๐Ÿ‘‘

  • -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 ๐Ÿ˜ญ so like, all that effort and then she just lets it go. 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. so like, package it up and ship it separately, but make sure your debugger can actually open the parcel ๐Ÿ’…
  • -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. so it's the classic trade: small and universally adored, or big and occasionally misunderstood ๐Ÿ˜ญ
  • -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 โœจ giving the nameless entities a little name tag, we love to see it ๐Ÿซถ
  • -gpubnames โ€” generates DWARF .debug_pubnames and .debug_pubtypes sections ๐ŸŽ€ the girlies love an index.
  • -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. so like, check your linker's credentials first, otherwise it's giving "bought the outfit, nowhere to wear it" ๐Ÿ’€
  • -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 ๐Ÿ˜ญ so like, it's giving efficiency and risk, your call bestie, no cap.
  • -grecord-gcc-switches โ€” okay so this switch causes the command-line options used to invoke the compiler that may affect code generation to be appended to the DW_AT_producer attribute in DWARF debugging information. The options are concatenated with spaces separating them from each other and from the compiler version. It is enabled by default. See also -frecord-gcc-switches for another way of storing compiler options into the object file.
  • -gno-record-gcc-switches โ€” the nope version: don't append those command-line options to DW_AT_producer.
  • -gstrict-dwarf โ€” Disallow using extensions of later DWARF standard version than selected with -gdwarf-version. On most targets using non-conflicting DWARF extensions from later standard versions is allowed.
  • -gno-strict-dwarf โ€” Allow using extensions of later DWARF standard version than selected with -gdwarf-version.
  • -gas-loc-support โ€” Inform the compiler that the assembler supports .loc directives. It may then use them for the assembler to generate DWARF2+ line number tables.

This is generally desirable, because assembler-generated line-number tables are a lot more compact than those the compiler can generate itself.

This option will be enabled by default if, at GCC configure time, the assembler was found to support such directives.

  • -gno-as-loc-support โ€” Force GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are to be generated.
  • -gas-locview-support โ€” Inform the compiler that the assembler supports "view" assignment and reset assertion checking in .loc directives.

This option will be enabled by default if, at GCC configure time, the assembler was found to support them.

  • -gno-as-locview-support โ€” Force GCC to assign view numbers internally, if -gvariable-location-views are explicitly requested.
  • -gcolumn-info โ€” Emit location column information into DWARF debugging information, rather than just file and line. This option is enabled by default.
  • -gno-column-info โ€” nah, don't emit location column info; just file and line.
  • -gstatement-frontiers โ€” This option causes GCC to create markers in the internal representation at the beginning of statements, and to keep them roughly in place throughout compilation, using them to guide the output of "is_stmt" markers in the line number table. This is enabled by default when compiling with optimization (-Os, -O1, -O2, ...), and outputting DWARF 2 debug information at the normal level.
  • -gno-statement-frontiers โ€” the off switch: skip those statement-frontier markers.
  • -gvariable-location-views โ€” Augment variable location lists with progressive view numbers implied from the line number table. This enables debug information consumers to inspect state at certain points of the program, even if no instructions associated with the corresponding source locations are present at that point. If the assembler lacks support for view numbers in line number tables, this will cause the compiler to emit the line number table, which generally makes them somewhat less compact. The augmented line number tables and location lists are fully backward-compatible, so they can be consumed by debug information consumers that are not aware of these augmentations, but they won't derive any benefit from them either.

This is enabled by default when outputting DWARF 2 debug information at the normal level, as long as there is assembler support, -fvar-tracking-assignments is enabled and -gstrict-dwarf is not. When assembler support is not available, this may still be enabled, but it will force GCC to output internal line number tables, and if -ginternal-reset-location-views is not enabled, that will most certainly lead to silently mismatching location views.

  • -gvariable-location-views=incompat5 โ€” There is a proposed representation for view numbers that is not backward compatible with the location list format introduced in DWARF 5, that can be enabled with -gvariable-location-views=incompat5. This option may be removed in the future, is only provided as a reference implementation of the proposed representation.
heads up bestie: debug information consumers are not expected to support this extended format, and they would be rendered unable to decode location lists using it. ๐Ÿ˜ญ
  • -gno-variable-location-views โ€” Turn off that variable-location-view augmentation completely.
  • -ginternal-reset-location-views โ€” Attempt to determine location views that can be omitted from location view lists. This requires the compiler to have very accurate insn length estimates, which isn't always the case, and it may cause incorrect view lists to be generated silently when using an assembler that does not 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.
  • -gno-internal-reset-location-views โ€” Don't attempt that internal location-view omission thing.
  • -ginline-points โ€” Generate extended debug information for inlined functions. Location view tracking markers are inserted at inlined entry points, so that address and view numbers can be computed and output in debug information. 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 is only enabled by default if location views are enabled.
  • -gno-inline-points โ€” Don't generate extended debug information for inlined functions.
  • -gz[=type] โ€” Produce compressed debug sections in DWARF format, if that is supported. If type is not 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. Otherwise, if the assembler does not support them, -gz is silently ignored when producing object files.
  • -femit-struct-debug-baseonly โ€” Emit debug information for struct-like types only when the base name of the compilation source file matches the base name of file in which the struct is defined.

This option substantially reduces the size of debugging information, but at significant potential loss in type information to the debugger. See -femit-struct-debug-reduced for a less aggressive option. See -femit-struct-debug-detailed for more detailed control.

This option works only with DWARF debug output.

  • -femit-struct-debug-reduced โ€” Emit debug information for struct-like types only when the base name of the compilation source file matches the base name of file in which the type is defined, unless the struct is a template or defined in a system header.

This option significantly reduces the size of debugging information, with some potential loss in type information to the debugger. See -femit-struct-debug-baseonly for a more aggressive option. See -femit-struct-debug-detailed for more detailed control.

This option works only with DWARF debug output.

  • -femit-struct-debug-detailed[=spec-list] โ€” Specify the struct-like types for which the compiler generates debug information. The intent is to reduce duplicate struct debug information between different object files within the same program.

This option is a detailed version of -femit-struct-debug-reduced and -femit-struct-debug-baseonly, which serves for most needs.

A 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 is 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 does not yet implement them.

The third word specifies the source files for those structs for which the compiler should emit debug information. 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 information 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 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 is useful to have GCC emit debugging information for all types declared in a compilation unit, regardless of whether or not they are actually used in that compilation unit, for example if, in the debugger, you want to cast a value to a type that is not 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. like, the whole optimization menu, bestie.

Without any optimization option, the compiler's goal is to reduce the cost of compilation and to make debugging produce the expected results. Statements are independent: if you stop the program with a breakpoint between statements, you can then assign a new value to any variable or change the program counter to any other statement in the function and get exactly the results you expect from the source code.

Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program. trade-offs, babes.

okay so real talk โ€” the compiler is out here doing actual detective work. It performs optimization based on the knowledge it has of the program, and honestly? It's kind of a genius move: compiling multiple files at once to a single output file mode allows the compiler to use information gained from all of the files when compiling each of them. Bestie is connecting dots across the whole squad. ๐Ÿ•ต๏ธโ€โ™€๏ธโœจ

But heads up โ€” not all optimizations are controlled directly by a flag. Only optimizations that have a flag are listed in this section. So if you're like "where's the flag for X," it might just not have one, no cap.

Also super important, don't skip this: most optimizations are completely disabled at -O0 or if an -O level is not set on the command line, even if individual optimization flags are specified. Yeah. You can hand-write fifty -f flags and if there's no -O level in the mix, most of them are just gonna sit there doing nothing. ๐Ÿ˜ญ Similarly, -Og suppresses many optimization passes โ€” it's just built different.

And depending on the target and how GCC was configured, a slightly different set of optimizations may be enabled at each -O level than those listed here. So like, don't come for me if your build differs. You can invoke GCC with -Q --help=optimizers to find out the exact set of optimizations that are enabled at each level. That's your vibe check tool, periodt. ๐Ÿ”


๐Ÿ”ฅ the -O levels, ranked by chaos

  • -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. Like, actually go read it, bestie. It's giving important.
  • -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. No thoughts, just vibes, and the vibes are slow but predictable. ๐Ÿข
  • -Os โ€” Optimize for size. -Os enables all -O2 optimizations except those that often increase code size:
-falign-functions  -falign-jumps -falign-labels  -falign-loops
-fprefetch-loop-arrays  -freorder-blocks-algorithm=stc

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

  • -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.
๐Ÿšจ This one is literally disregarding strict standards compliance. Read that again. If your program needs to be standards-compliant, this is not the vibe. Also the -fstack-arrays and -fmax-stack-var-size bits are Fortran-specific, so don't get confused if you're a C girlie.
  • -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

Honestly? The edit-compile-debug cycle needs her. ๐Ÿ’…

  • -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.
๐Ÿซถ If you use multiple -O options, with or without level numbers, the last such option is the one that is effective. Last one wins, always. Don't argue with the order.

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. It's giving DIY, iykyk. โœจ

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. This is the artisan, small-batch, hand-selected part of the menu. ๐Ÿงš


  • -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. Efficiency queen. ๐Ÿ‘‘
  • -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 โ€” okay so the style here is the whole point:
    • -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. Sad, but true.

โš ๏ธ 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. So like, don't count on it as a guarantee, bestie.

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. "not me, not today" energy. ๐Ÿ™ˆ

  • -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. She's everywhere. ๐ŸŒˆ

  • -finline-functions-called-once โ€” Consider all static functions called once for inlining into their caller even if they are not marked inline. If a call to a given function is integrated, then the function is not output as assembler code in its own right.

Enabled at levels -O1, -O2, -O3 and -Os, but not -Og. ๐ŸŽ€

  • -fearly-inlining โ€” bestie, this one does the inlining early, before all the heavy stuff. It inlines functions marked always_inline plus any function whose body looks smaller than the overhead of just calling it, and it does this before the -fprofile-generate instrumentation and before the real inlining pass kicks in. The result? Profiling gets significantly cheaper, and inlining is usually faster on programs that have big chains of nested wrapper functions. Wrapper city, honestly. โœจ

Enabled by default. ๐Ÿซถ

  • -fipa-sra โ€” this does interprocedural scalar replacement of aggregates, removes unused parameters, and swaps parameters passed by reference for parameters passed by value. It's giving "why carry the whole suitcase when you only need the passport". ๐Ÿ’…

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

  • -finline-limit=n โ€” okay so by default GCC limits the size of functions it'll inline, and this flag gives you coarse control over that limit. n is the size of functions that can be inlined, measured in number of pseudo instructions.

Inlining is actually controlled by a bunch of parameters, which you can set individually with --param name=value. This option sets some of them like so:

  • max-inline-insns-single โ€” is set to n/2.
  • max-inline-insns-auto โ€” is set to n/2.

See below for documentation of the individual parameters controlling inlining and their defaults. ๐Ÿ‘€

Note: there may be no value to -finline-limit that results in default behavior. ๐Ÿ˜ญ
Note: pseudo instruction here means an abstract measurement of a function's size. It absolutely does not represent a count of assembly instructions, and its exact meaning might change from one release to another. So don't come for me if it shifts. ๐Ÿ’€
  • -fno-keep-inline-dllexport โ€” a more fine-grained version of -fkeep-inline-functions, which applies only to functions declared using the dllexport attribute or declspec. Little laser-focused icon. ๐ŸŽฏ
  • -fkeep-inline-functions โ€” in C, this emits static functions declared inline into the object file, even if the function has been inlined into all of its callers. Note that 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. Keeping them around, main character energy. ๐Ÿ‘‘
  • -fkeep-static-functions โ€” emits static functions into the object file even if the function is never used. Rude to leave them out, honestly. ๐ŸŒธ
  • -fkeep-static-consts โ€” emits 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 on โ€” use the -fno-keep-static-consts option. ๐Ÿฆ‹

  • -fmerge-constants โ€” attempts to merge identical constants (string constants and floating-point constants) across compilation units. Dedupe slay. โœจ

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 that, it also considers things like even constant initialized arrays or initialized constant variables with integral or floating-point types. But bestie, listen: 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. โš ๏ธ

Fr fr, that's a standards violation. Use with intention.
  • -fmodulo-sched โ€” performs swing modulo scheduling immediately before the first scheduling pass. This pass looks at innermost loops and reorders their instructions by overlapping different iterations. Loops getting a whole glow-up. ๐Ÿ”ฅ
  • -fmodulo-sched-allow-regmoves โ€” performs more aggressive SMS-based modulo scheduling with register moves allowed. Setting this flag deletes certain anti-dependences edges, which triggers generation of reg-moves based on the life-range analysis. This option is effective only with -fmodulo-sched enabled. Teamwork, iykyk. ๐Ÿ’œ
  • -fno-branch-count-reg โ€” disables the optimization pass that scans for chances 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. ๐Ÿ“
Note: -fno-branch-count-reg doesn't remove the decrement and branch instructions from the generated instruction stream introduced by other optimization passes.

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

  • -fno-function-cse โ€” do not put function addresses in registers; make each instruction that calls a constant function contain the function's address explicitly. ๐ŸŽ€

This option results in less efficient code, but some strange hacks that alter the assembler output may get confused by the optimizations performed when this option is not used. Strange hacks, we see you. ๐Ÿ™ˆ

The default is -ffunction-cse.

  • -fno-zero-initialized-in-bss โ€” if the target supports a BSS section, GCC by default puts variables initialized to zero into BSS. This can save space in the resulting code. Neat. โœจ

This option turns that behavior off, because some programs explicitly rely on variables going to the data section โ€” e.g., so the resulting executable can find the beginning of that section and/or make assumptions based on that. Honestly, valid.

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

  • -fthread-jumps โ€” performs optimizations that check whether a jump branches to a location where another comparison subsumed by the first is found. If so, the first branch is redirected to either the destination of the second branch or a point immediately following it, depending on whether the condition is known to be true or false. Jump hopscotch. ๐Ÿฆ‹

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

  • -fsplit-wide-types โ€” when you're using a type that occupies multiple registers, like long long on a 32-bit system, this splits the registers apart and allocates them independently. Normally it generates better code for those types, but it may make debugging more difficult. Trade-offs, babes. ๐Ÿ˜ญ

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

  • -fsplit-wide-types-early โ€” fully splits wide types early, instead of very late. This option has no effect unless -fsplit-wide-types is turned on. Early bird gets the split. ๐Ÿฃ

This is the default on some targets.

  • -fcse-follow-jumps โ€” in common subexpression elimination (CSE), scan through jump instructions when the target of the jump isn't reached by any other path. For example, when CSE encounters an if statement with an else clause, CSE follows the jump when the condition tested is false. Following the plot. ๐Ÿ“–

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

  • -fcse-skip-blocks โ€” similar to -fcse-follow-jumps, but it makes CSE follow jumps that conditionally skip over blocks. When CSE encounters a simple if statement with no else clause, -fcse-skip-blocks makes CSE follow the jump around the body of the if. Hop around it, periodt. ๐Ÿ’…

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

  • -frerun-cse-after-loop โ€” re-runs common subexpression elimination after loop optimizations are performed. Round two, let's go. ๐Ÿ”

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

  • -fgcse โ€” performs a global common subexpression elimination pass. This pass also does global constant and copy propagation. ๐ŸŒ
Note: when compiling a program using computed gotos, a GCC extension, you may get better run-time performance if you disable the global common subexpression elimination pass by adding -fno-gcse to the command line.

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

  • -fgcse-lm โ€” when enabled, global common subexpression elimination attempts to move loads that are only killed by stores into themselves. This lets a loop containing a load/store sequence get changed to a load outside the loop, and a copy/store inside the loop. Loop glow-up achieved. โญ

Enabled by default when -fgcse is enabled.

  • -fgcse-sm โ€” when enabled, a store motion pass runs after global common subexpression elimination. This pass attempts to move stores out of loops. Used together with -fgcse-lm, loops containing a load/store sequence can be changed to a load before the loop and a store after the loop. Iconic combo. ๐Ÿ‘‘

Not enabled at any optimization level.

  • -fgcse-las โ€” when enabled, the global common subexpression elimination pass eliminates redundant loads that come after stores to the same memory location (both partial and full redundancies). Redundancy found crying in the club. ๐Ÿ’€

Not enabled at any optimization level.

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

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

  • -faggressive-loop-optimizations โ€” this tells the loop optimizer to use language constraints to derive bounds for the number of iterations of a loop. It assumes the loop code does not invoke undefined behavior โ€” for example, by causing signed integer overflows or out-of-bound array accesses. Those derived bounds are used to guide loop unrolling and peeling and loop exit test optimizations. This option is enabled by default. Aggressive but in a confident way. ๐Ÿ”ฅ
Bestie, do not feed it UB. It will trust you and it will be wrong.
  • -funconstrained-commons โ€” this 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. Don't assume the bounds, babe. ๐ŸŒธ
  • -fcrossjumping โ€” performs the cross-jumping transformation. This transformation unifies equivalent code and saves code size. Heads up: the resulting code may or may not perform better than without cross-jumping. Smaller, not necessarily faster. Ngl. ๐Ÿ’œ

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

  • -fauto-inc-dec โ€” combines increments or decrements of addresses with memory accesses. This pass is always skipped on architectures that don't have instructions to support it. Enabled by default at -O1 and higher on architectures that support this. ๐ŸŽ€
  • -fdce โ€” performs dead code elimination (DCE) on RTL. Enabled by default at -O1 and higher. Bye bye dead code, you're not invited to the group chat. ๐Ÿ‘‹
  • -fdse โ€” performs dead store elimination (DSE) on RTL. Enabled by default at -O1 and higher. Same energy, but for stores. ๐Ÿ—‘๏ธ
  • -fif-conversion โ€” okay so this one tries to turn conditional jumps into branch-less equivalents โœจ and it's giving so many tricks: conditional moves, min, max, set flags, abs instructions, plus some cute stuff you can do with standard arithmetics. Whether it actually uses conditional execution on chips where that exists is controlled by -fif-conversion2, bestie. Enabled at levels -O1, -O2, -O3, -Os, but not with -Og.
  • -fif-conversion2 โ€” uses conditional execution (where available, iykyk) to transform conditional jumps into branch-less equivalents. Enabled at levels -O1, -O2, -O3, -Os, but not with -Og.
  • -fdeclone-ctor-dtor โ€” the C++ ABI requires multiple entry points for constructors and destructors, and it's lowkey a lot: one for a base subobject, one for a complete object, and one for a virtual destructor that calls operator delete afterwards. For a hierarchy with virtual bases, the base and complete variants are clones, which means you literally get two copies of the function ๐Ÿ˜ญ. With this option, the base and complete variants get changed into thunks that call a common implementation. Enabled by -Os. Slay.
  • -fdelete-null-pointer-checks โ€” assumes programs cannot safely dereference null pointers, and that no code or data element resides at address zero. This option enables simple constant folding optimizations at all optimization levels. On top of that, other optimization passes in GCC use this flag to control global dataflow analyses that eliminate useless checks for null pointers; those assume 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. Periodt.
โš ๏ธ Note however that in some environments this assumption is not true. Use -fno-delete-null-pointer-checks to disable this optimization for programs that depend on that behavior.

This option is enabled by default on most targets. On Nios II ELF, it defaults to off. On AVR and MSP430, this option is completely disabled ๐Ÿ™ˆ. Passes that use the dataflow information are enabled independently at different optimization levels.

  • -fdevirtualize โ€” attempt to convert calls to virtual functions into direct calls ๐Ÿ’…. This is done 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 โ€” attempt to convert calls to virtual functions into speculative direct calls ๐Ÿ”ฅ. Based on the analysis of the type inheritance graph, it figures out 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, such as inlining. When they seem useless after further optimization, they're converted back into their original form. Cute, right?
  • -fdevirtualize-at-ltrans โ€” streams extra information needed for aggressive devirtualization when running the link-time optimizer in local transformation mode. This option enables more devirtualization but significantly increases the size of streamed data ๐Ÿ’€. For this reason it is disabled by default.
  • -fexpensive-optimizations โ€” perform a number of minor optimizations that are relatively expensive. Enabled at levels -O2, -O3, -Os.
  • -free โ€” attempt to remove redundant extension instructions. This is especially helpful for the x86-64 architecture, which implicitly zero-extends in 64-bit registers after writing to their lower 32-bit half. Enabled for Alpha, AArch64 and x86 at levels -O2, -O3, -Os. Iconic.
  • -fno-lifetime-dse โ€” in C++, the value of an object is only affected by changes within its lifetime: when the constructor begins, the object has an indeterminate value, and any changes during the lifetime of the object are dead when the object is destroyed. Normally dead store elimination will take advantage of this; 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 โ€” attempt 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 ๐Ÿ‘‘
  • -fira-region=region โ€” use the specified regions for the integrated register allocator. The region argument should be one of the following:
    • all โ€” use all loops as register allocation regions. This can give the best results for machines with a small and/or irregular register set.
    • mixed โ€” use all loops except for loops with small register pressure as the regions. This value usually gives the best results in most cases and for most architectures, and is enabled by default when compiling with optimization for speed (-O, -O2, ...).
    • one โ€” use all functions as a single region. This typically results in the smallest code size, and is enabled by default for -Os or -O0.
  • -fira-hoist-pressure โ€” use IRA to evaluate register pressure in the code hoisting pass for decisions to hoist expressions. This option usually results in smaller code, but it can slow the compiler down. 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. 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 โœจ. Enabled at levels -O2, -O3, -Os.
  • -fdelayed-branch โ€” if supported for the target machine, attempt to reorder instructions to exploit instruction slots available after delayed branch instructions. Enabled at levels -O1, -O2, -O3, -Os, but not at -Og.
  • -fschedule-insns โ€” if supported for the target machine, attempt 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 ๐Ÿ”ฅ. 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. Usage of this option can improve the generated code and decrease its size by preventing register pressure increase above the number of available hard registers and subsequent spills in register allocation ๐Ÿ’…
  • -fsched-spec-load โ€” allow speculative motion of some load instructions. This only makes sense when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher.
  • -fsched-spec-load-dangerous โ€” allow speculative motion of more load instructions ๐Ÿ˜ณ. This only makes sense when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher.
  • -fsched-stalled-insns, -fsched-stalled-insns=n โ€” define how many insns (if any) can be moved prematurely from the queue of stalled insns into the ready list during the second scheduling pass. -fno-sched-stalled-insns means that no insns are moved prematurely, and -fsched-stalled-insns=0 means there is no limit on how many queued insns can be moved prematurely. -fsched-stalled-insns without a value is equivalent to -fsched-stalled-insns=1.
  • -fsched-stalled-insns-dep, -fsched-stalled-insns-dep=n โ€” define how many insn groups (cycles) are examined for a dependency on a stalled insn that is a candidate for premature removal from the queue of stalled insns. This has an effect only during the second scheduling pass, and only if -fsched-stalled-insns is used. -fno-sched-stalled-insns-dep is equivalent to -fsched-stalled-insns-dep=0. And -fsched-stalled-insns-dep without a value is equivalent to -fsched-stalled-insns-dep=1. ๐Ÿฆ‹
  • -fsched2-use-superblocks โ€” okay so when you're scheduling after register allocation, this one lets GCC use superblock scheduling ๐Ÿ’… which means instructions can move across basic block boundaries, and that gives you faster schedules. But bestie, listen: this option is experimental, because not every machine description GCC uses models the CPU closely enough to dodge unreliable results from this algorithm. So likeโ€ฆ it might slay, it might be messy ๐Ÿ˜ญ

This 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 โœจ this one favors the instruction that belongs to a schedule group. It's on by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -fsched-critical-path-heuristic โ€” enables the critical-path heuristic in the scheduler ๐ŸŽฏ favors instructions on the critical path. On 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 ๐Ÿฆ‹ favors speculative instructions with greater dependency weakness. On by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -fsched-rank-heuristic โ€” enables the rank heuristic in the scheduler ๐Ÿ‘‘ favors the instruction belonging to a basic block with greater size or frequency. On by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -fsched-last-insn-heuristic โ€” enables the last-instruction heuristic in the scheduler ๐Ÿ’ซ favors the instruction that's less dependent on the last instruction scheduled. On by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
  • -fsched-dep-count-heuristic โ€” enables the dependent-count heuristic in the scheduler ๐ŸŒธ favors the instruction that has more instructions depending on it. On by default when scheduling is enabled, 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, later scheduling passes might change its schedule ๐Ÿ™ˆ this option is how you control that behavior.
  • -fselective-scheduling โ€” schedule instructions using the selective scheduling algorithm โญ selective scheduling runs instead of the first scheduler pass.
  • -fselective-scheduling2 โ€” same selective scheduling algorithm energy, but this one runs instead of the second scheduler pass ๐Ÿ’…
  • -fsel-sched-pipelining โ€” enables software pipelining of innermost loops during selective scheduling ๐ŸŒ€ heads up though: this option has 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 ๐ŸŽ€ but again, no effect unless -fsel-sched-pipelining is turned on. iykyk.
  • -fsemantic-interposition โ€” some object formats, like ELF, allow interposing of symbols by the dynamic linker ๐Ÿงš which means: for symbols exported from the DSO, the compiler can't do interprocedural propagation, inlining and other optimizations, because it has to anticipate that the function or variable in question might change. Like, it's useful โ€” say, to rewrite memory allocation functions with a debugging implementation โ€” but it's expensive in terms of code quality ๐Ÿ’€

With -fno-semantic-interposition the compiler assumes that if interposition happens for functions, the overwriting function will have precisely the same semantics (and side effects). Same deal for variables: if interposition happens, the constructor of the variable will be the same. The flag has no effect for functions explicitly declared inline (where it's never allowed for interposition to change semantics) and for symbols explicitly declared weak.

  • -fshrink-wrap โ€” emit function prologues only before the parts of the function that actually need it, instead of dumping them at the top of the function like a normie ๐Ÿ“ฆ enabled by default at -O and higher.
  • -fshrink-wrap-separate โ€” shrink-wraps separate parts of the prologue and epilogue separately, so those parts only get executed when needed โœจ on by default, but has no effect unless -fshrink-wrap is also turned on and the target supports this.
  • -fcaller-saves โ€” enables allocation of values to registers that get clobbered by function calls, by emitting extra instructions to save and restore the registers around such calls ๐Ÿ’พ such allocation only happens when it seems to result in better code.

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. Only possible if the called functions are part of the same compilation unit as the current function and they're compiled before it.

Enabled at levels -O2, -O3, -Os, however the option is disabled if generated code will be instrumented for profiling (-p, or -pg) or if the callee's register usage can't be known exactly (this happens on targets that don't expose prologues and epilogues in RTL).

  • -fconserve-stack โ€” attempt to minimize stack usage ๐Ÿ“ the compiler tries to use less stack space, even if that makes the program slower. This option implies setting the large-stack-frame parameter to 100 and the large-stack-frame-growth parameter to 400.
  • -ftree-reassoc โ€” perform reassociation on trees ๐ŸŒˆ enabled by default at -O1 and higher.
  • -fcode-hoisting โ€” perform code hoisting ๐Ÿ‘‘ code hoisting tries to move the evaluation of expressions executed on all paths to the function exit as early as possible. Especially useful as a code size optimization, but it often helps for code speed as well. Enabled by default at -O2 and higher.
  • -ftree-pre โ€” perform partial redundancy elimination (PRE) on trees โœจ enabled by default at -O2 and -O3.
  • -ftree-partial-pre โ€” makes partial redundancy elimination (PRE) more aggressive ๐Ÿ’… enabled by default at -O3.
  • -ftree-forwprop โ€” perform forward propagation on trees ๐Ÿฆ‹ enabled by default at -O1 and higher.
  • -ftree-fre โ€” perform full redundancy elimination (FRE) on trees ๐ŸŒธ the difference between FRE and PRE is that FRE only considers expressions that are computed on all paths leading to the redundant computation. This analysis is faster than PRE, though it exposes fewer redundancies. Enabled by default at -O1 and higher.
  • -ftree-phiprop โ€” perform hoisting of loads from conditional pointers on trees ๐ŸŽ€ this pass is enabled by default at -O1 and higher.
  • -fhoist-adjacent-loads โ€” speculatively hoist loads from both branches of an if-then-else if the loads are from adjacent locations in the same structure and the target architecture has a conditional move instruction ๐ŸŒ€ enabled by default at -O2 and higher.
  • -ftree-copy-prop โ€” perform copy propagation on trees ๐Ÿ’ซ this pass eliminates unnecessary copy operations. Enabled by default at -O1 and higher.
  • -fipa-pure-const โ€” discover which functions are pure or constant ๐Ÿงš enabled by default at -O1 and higher.
  • -fipa-reference โ€” discover which static variables do not escape the compilation unit ๐Ÿ“ enabled by default at -O1 and higher.
  • -fipa-reference-addressable โ€” discover read-only, write-only and non-addressable static variables โญ enabled by default at -O1 and higher.
  • -fipa-stack-alignment โ€” reduce stack alignment on call sites if possible ๐Ÿ“ฆ enabled by default.
  • -fipa-pta โ€” perform interprocedural pointer analysis and interprocedural modification and reference analysis ๐Ÿ” heads up: 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 are 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. 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, then optimizes accordingly. Can substantially increase performance if the application has constants passed to functions ๐Ÿ”ฅ enabled by default at -O2, -Os and -O3. It is also enabled by -fprofile-use and -fauto-profile.
  • -fipa-cp-clone โ€” perform function cloning to make interprocedural constant propagation stronger ๐Ÿ‘‘ when enabled, interprocedural constant propagation performs function cloning when an externally visible function can be called with constant arguments. Because this optimization can create multiple copies of functions, it may significantly increase code size (see --param ipa-cp-unit-growth=value) ๐Ÿ’€ enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile.
  • -fipa-bit-cp โ€” when enabled, perform interprocedural bitwise constant propagation ๐ŸŽ€ enabled by default at -O2 and by -fprofile-use and -fauto-profile. It requires that -fipa-cp is enabled.
  • -fipa-vrp โ€” okay so this one does interprocedural propagation of value ranges when it's turned on. It's on by default at -O2, and heads up: it needs -fipa-cp to be enabled too, like it literally can't do its thing without it. ๐Ÿ’…
  • -fipa-icf โ€” this one does Identical Code Folding for functions and read-only variables. It shrinks your code size, but bestie, it may disturb unwind stacks because it replaces a function with an equivalent one that has a different name ๐Ÿ˜ญ. Works way more effectively when link-time optimization is enabled.

So the behavior is similar to the Gold Linker's ICF optimization, but GCC ICF works on different levels, so the optimizations are not the same โ€” there are equivalences found only by GCC and equivalences found only by Gold. Both iconic, not identical, iykyk.

Enabled by default at -O2 and -Os โœจ

  • -flive-patching=level โ€” this controls GCC's optimizations so the output is suitable for live-patching.

Real talk: if the compiler's optimization uses a function's body, or info extracted from its body, to optimize/change another function, that latter one is called an impacted function of the former. So if you patch a function, its impacted functions should be patched too. Periodt.

The impacted functions get determined by the compiler's interprocedural optimizations. For example, a caller is impacted when inlining a function into its caller, cloning a function and changing its caller to call this new clone, or extracting a function's pureness/constness information to optimize its direct or indirect callers, etc.

Usually, the more IPA optimizations enabled, the larger the number of impacted functions for each function. So to control how many impacted functions there are and to make computing that list easier, IPA optimizations can be partially enabled at two different levels.

The level argument should be one of these:

  • inline-clone โ€” only enables inlining and cloning optimizations, which includes inlining, cloning, interprocedural scalar replacement of aggregates and partial inlining. So when you patch a function, all its callers and its clones' callers are impacted, and therefore 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 enables inlining of static functions. So when you patch a static function, all its callers are impacted and need to be patched as well.

On top of all the flags that -flive-patching=inline-clone disables, -flive-patching=inline-only-static also disables: -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.

๐Ÿซถ Heads up bestie: -flive-patching is not supported with link-time optimization (-flto). No cap.
  • -fisolate-erroneous-paths-dereference โ€” detects paths that trigger erroneous or undefined behavior because of dereferencing a null pointer ๐Ÿ™ˆ. It isolates those paths from the main control flow and turns the statement with the erroneous or 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 being used in a way that's forbidden by a "returns_nonnull" or "nonnull" attribute. It isolates those paths from the main control flow and turns the statement with the erroneous or undefined behavior 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. Enabled 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 is 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. This pass only operates on local scalar variables and is enabled by default at -O1 and higher.
  • -fssa-backprop โ€” propagates information about 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 โ€” performs pattern matching on SSA PHI nodes to optimize conditional code. Enabled by default at -O1 and higher, except for -Og.
  • -ftree-switch-conversion โ€” performs conversion of simple initializations in a switch to initializations from a scalar array. Enabled by default at -O2 and higher โญ
  • -ftree-tail-merge โ€” looks for identical code sequences ๐Ÿ‘€. When it finds them, it replaces one with a jump to the other. This optimization is known as tail merging or cross jumping. Enabled by default at -O2 and higher. The compilation time in this pass can be limited using 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 isn't also specified.
  • -ffinite-loops โ€” assumes that a loop with an exit will eventually take that exit and not loop forever ๐Ÿ”ฅ. This lets the compiler remove loops that otherwise have no side-effects, since it doesn't consider eventual endless looping as one of those side-effects.

Enabled by default at -O2 for C++ with -std=c++11 or higher.

  • -ftree-dominator-opts โ€” performs a whole 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. So a dead store is a store into a memory location that gets overwritten later by another store without any 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 increases the effectiveness of code motion optimizations, 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. It's a generic loop nest optimizer based on the Pluto optimization algorithms. It calculates a loop structure optimized for data-locality and parallelism. This option is experimental โš ๏ธ
  • -floop-parallelize-all โ€” uses the Graphite data dependence analysis to identify loops that can be parallelized. It parallelizes all the loops that can be analyzed to not contain loop carried dependences, without checking that it's profitable to parallelize the loops ๐Ÿ‘‘
  • -ftree-coalesce-vars โ€” while transforming the program out of the SSA representation, it attempts to reduce copying by coalescing versions of different user-defined variables instead of just compiler temporaries. Warning bestie: this may severely limit the ability to debug an optimized program compiled with -fno-var-tracking-assignments ๐Ÿ˜ญ. In the negated form, this flag prevents SSA coalescing of user variables. Enabled by default if optimization is enabled, and it does very little otherwise.
  • -ftree-loop-if-convert โ€” attempts to transform conditional jumps in the innermost loops into branch-less equivalents. The intent is to remove control-flow from the innermost loops so the vectorization pass can handle these loops better ๐ŸŒˆ. Enabled by default if vectorization is enabled.
  • -ftree-loop-distribution โ€” performs loop distribution. This can improve cache performance on big loop bodies and lets further loop optimizations โ€” like parallelization or vectorization โ€” take place. For example, the loop
        DO I = 1, N
          A(I) = B(I) + C
          D(I) = E(I) * F
        ENDDO

gets transformed to

        DO I = 1, N
           A(I) = B(I) + C
        ENDDO
        DO I = 1, N
           D(I) = E(I) * F
        ENDDO

This flag is enabled by default at -O3. It's also enabled by -fprofile-use and -fauto-profile ๐Ÿ’œ

  • -ftree-loop-distribute-patterns โ€” performs loop distribution of patterns that can be code generated with calls to a library. Enabled by default at -O2 and higher, and by -fprofile-use and -fauto-profile.

This pass distributes the initialization loops and generates a call to memset zero. For example, the loop

        DO I = 1, N
          A(I) = 0
          B(I) = A(I) + I
        ENDDO

...it gets transformed into something like this:

DO I = 1, N
   A(I) = 0
ENDDO
DO I = 1, N
   B(I) = A(I) + I
ENDDO

and bestie, that whole initialization loop becomes a straight-up call to memset zero. Chef's kiss. โœจ This flag is on by default at -O3, and it's also switched on by -fprofile-use and -fauto-profile.

  • -floop-interchange โ€” does loop interchange outside of graphite. It can level up your cache performance on loop nests and lets other loop optimizations (hi, vectorization ๐Ÿ‘‹) actually happen. Like, this loop:
for (int i = 0; i < N; i++)
  for (int j = 0; j < N; j++)
    for (int k = 0; k < N; k++)
      c[i][j] = c[i][j] + a[i][k]*b[k][j];

becomes this:

for (int i = 0; i < N; i++)
  for (int k = 0; k < N; k++)
    for (int j = 0; j < N; j++)
      c[i][j] = c[i][j] + a[i][k]*b[k][j];

Enabled by default at -O3, and also enabled by -fprofile-use and -fauto-profile. ๐Ÿ’ซ

  • -floop-unroll-and-jam โ€” applies unroll-and-jam transformations to loops where that's actually feasible. In a loop nest it unrolls the outer loop by some factor and fuses the resulting multiple inner loops together. Enabled by default at -O3, and also enabled by -fprofile-use and -fauto-profile. ๐ŸŒ€
  • -ftree-loop-im โ€” performs loop invariant motion on trees. Real talk though, this pass only moves the invariants that are hard to handle at the RTL level (think function calls, and operations that expand into nontrivial sequences of insns). Paired with -funswitch-loops, it also lifts operands of conditions that are invariant out of the loop, so loop unswitching can get away with just trivial invariantness analysis. This pass also includes store motion. ๐Ÿง 
  • -ftree-loop-ivcanon โ€” creates a canonical counter for the number of iterations in loops where figuring out that count takes complicated analysis. Later optimizations can then figure out the number easily. Super useful, especially when paired with unrolling. ๐Ÿ”ข
  • -ftree-scev-cprop โ€” performs final value replacement. So if a variable gets modified inside a loop in a way where its value on exit can be worked out from just its initial value plus the number of loop iterations, then it replaces uses of that final value with the computation instead โ€” assuming that computation is cheap enough. This cuts down data dependencies and may unlock 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. The whole glow-up package. ๐Ÿ’…
  • -ftree-parallelize-loops=n โ€” parallelizes loops, i.e. splits their iteration space so they run across n threads. Heads up: this only works for loops whose iterations are independent and can be reordered arbitrarily. And the optimization is only profitable on multiprocessor machines, for loops that are CPU-intensive rather than constrained by, say, memory bandwidth. This option implies -pthread, which means it's only supported on targets that actually support -pthread. ๐Ÿงต
  • -ftree-pta โ€” performs function-local points-to analysis on trees. Enabled by default at -O1 and higher, except for -Og. ๐ŸŽฏ
  • -ftree-sra โ€” performs scalar replacement of aggregates. This pass swaps structure references out for scalars so it doesn't commit structures to memory too early. Enabled by default at -O1 and higher, except for -Og. ๐Ÿ—๏ธ
  • -fstore-merging โ€” merges narrow stores that land on consecutive memory addresses. It takes contiguous stores of immediate values narrower than a word and merges them into fewer, wider stores to cut down the instruction count. 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 get replaced at their use location with the expression that defines them. Yeah, this produces non-GIMPLE code, but it hands the expanders way more complex trees to work with, which results in better RTL generation. Enabled by default at -O1 and higher. ๐Ÿ”„
  • -ftree-slsr โ€” performs straight-line strength reduction on trees. It spots related expressions involving multiplications and swaps them for cheaper calculations when it can. Enabled by default at -O1 and higher. ๐Ÿ’ช
  • -ftree-vectorize โ€” performs vectorization on trees. This flag enables -ftree-loop-vectorize and -ftree-slp-vectorize if you haven't explicitly specified them. ๐ŸŒˆ
  • -ftree-loop-vectorize โ€” performs loop vectorization on trees. Enabled by default at -O2 and by -ftree-vectorize, -fprofile-use, and -fauto-profile. ๐Ÿ”
  • -ftree-slp-vectorize โ€” performs basic block vectorization on trees. 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, which boosts a program's security and predictability by preventing uninitialized memory disclosure and use. Okay but here's the catch, bestie โ€” GCC still treats an automatic variable that has no explicit initializer as uninitialized: -Wuninitialized and -Wanalyzer-use-of-uninitialized-value will still warn about those variables, and the compiler will optimize as if the variable were uninitialized. ๐Ÿ™ˆ With this option, GCC also zeroes out any padding of automatic variables that have structure or union types. But โ€” and this is the annoying part โ€” 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 those cases.

The three values of choice are:

  • uninitialized โ€” doesn't initialize any automatic variables. This is C and C++'s default.
  • pattern โ€” initializes automatic variables with values that will likely turn logic bugs into crashes down the line, are easily recognized in a crash dump, and aren't values programmers can lean on for useful program semantics. The current value is a byte-repeatable pattern with byte 0xFE. Ngl, the values used for pattern initialization might change in the future.
  • zero โ€” initializes automatic variables with zeroes.

The default is uninitialized.

You can control this behavior for one specific variable using the variable attribute uninitialized. ๐ŸŽ€

  • -fvect-cost-model=model โ€” changes the cost model used for vectorization. The model argument should be one of unlimited, dynamic, cheap or very-cheap. With the unlimited model, the vectorized code-path is assumed to be profitable. With the dynamic model, a runtime check guards the vectorized code-path so it only kicks in for iteration counts that will likely run faster than the original scalar loop. The cheap model disables vectorization of loops where doing so would be cost prohibitive โ€” like when you'd need runtime checks for data dependence or alignment โ€” but otherwise it's equal to the dynamic model. The very-cheap model only allows vectorization if the vector code would entirely replace the scalar code being vectorized. For example, if each iteration of a vectorized loop could only handle exactly four iterations of the scalar loop, very-cheap would only allow vectorization if the scalar iteration count is known to be a multiple of four. The default cost model depends on other optimization flags and is either dynamic or cheap. ๐Ÿ’ธ
  • -fsimd-cost-model=model โ€” changes 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 the values of model mean the same thing as described in -fvect-cost-model, and by default a cost model defined with -fvect-cost-model is used. ๐ŸŽ›๏ธ
  • -ftree-vrp โ€” performs Value Range Propagation on trees. It's kinda like the constant propagation pass, except instead of values it propagates ranges of values. That lets the optimizers nuke unnecessary range checks like array bound checks and null pointer checks. Enabled by default at -O2 and higher. Heads up: null pointer check elimination only happens if -fdelete-null-pointer-checks is enabled. ๐Ÿšง
  • -fsplit-paths โ€” splits paths that lead to loop backedges. This can improve dead code elimination and common subexpression elimination. Enabled by default at -O3 and above. ๐Ÿ”€
  • -fsplit-ivs-in-unroller โ€” lets values of induction variables in later iterations of the unrolled loop be expressed using the value from the first iteration. This breaks up long dependency chains, which makes the scheduling passes way more efficient. A combo of -fweb and CSE is often enough to get the same effect โ€” but that's not reliable when the loop body is more complicated than a single basic block, and on some architectures it doesn't work at all because of restrictions in the CSE pass. This optimization is enabled by default. โ›“๏ธ๐Ÿ’ฅ
  • -fvariable-expansion-in-unroller โ€” with this, the compiler makes multiple copies of some local variables when unrolling a loop, which can result in superior code. Enabled by default for PowerPC targets, disabled by default everywhere else. ๐Ÿฌ
  • -fpartial-inlining โ€” inlines parts of functions. Just so you know, this option only does anything when inlining itself is turned on via the -finline-functions or -finline-small-functions options. Enabled at levels -O2, -O3, -Os. โœ‚๏ธ
  • -fpredictive-commoning โ€” performs predictive commoning optimization, i.e. reusing computations (especially memory loads and stores) that were performed in previous iterations of loops. Enabled at level -O3, and also enabled by -fprofile-use and -fauto-profile. ๐Ÿ”ฎ
  • -fprefetch-loop-arrays โ€” if the target machine supports it, generates instructions to prefetch memory so loops that access large arrays run faster. Fair warning: this option may generate better or worse code โ€” the results are highly dependent on the structure of the loops within your source code. Disabled at level -Os. ๐ŸŒฌ๏ธ
  • -fno-printf-return-value โ€” bestie, this one is about not substituting constants for the known return value of formatted output functions like sprintf, snprintf, vsprintf, and vsnprintf (but heads up, not printf or fprintf ๐Ÿ’…). When the substitution is on, GCC can optimize โ€” or literally eliminate โ€” branches based on the known return value of those functions when they're called with arguments that are either constant, or whose values are known to be in a range that makes figuring out the exact return value possible. So 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 gives its best results with -O2 and above โœจ. It works in tandem with the -Wformat-overflow and -Wformat-truncation options. And yes, -fprintf-return-value is enabled by default ๐Ÿ’–.

  • -fno-peephole
  • -fno-peephole2 โ€” disables any machine-specific peephole optimizations ๐Ÿซถ. The difference between -fno-peephole and -fno-peephole2 is literally just how they're implemented in the compiler โ€” some targets use one, some use the other, and a few use both, iykyk.

-fpeephole is enabled by default. -fpeephole2 is enabled at levels -O2, -O3, -Os.

  • -fno-guess-branch-probability โ€” do not guess branch probabilities using heuristics, periodt.

GCC uses heuristics to guess branch probabilities if they aren't provided by profiling feedback (-fprofile-arcs). These heuristics are based on the control flow graph. If some branch probabilities are specified by __builtin_expect, then the heuristics are used to guess branch probabilities for the rest of the control flow graph, taking the __builtin_expect info into account. The interactions between the heuristics and __builtin_expect can be complex, and in some cases it may be useful to disable the heuristics so that 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 so we reduce the number of taken branches and improve code locality ๐ŸŒธ. Enabled at levels -O1, -O2, -O3, -Os.
  • -freorder-blocks-algorithm=algorithm โ€” use the specified algorithm for basic block reordering, bestie. 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 and minimize 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 โ€” in addition to reordering basic blocks in the compiled function to reduce the number of taken branches, this one partitions hot and cold basic blocks into separate sections of the assembly and .o files, to improve paging and cache locality performance ๐Ÿ”ฅ.

This optimization is automatically turned off in the presence of exception handling or unwind tables (on targets using setjump/longjump or target specific scheme), for linkonce sections, for functions with a user-defined section attribute, and on any architecture that does not support named sections. When -fsplit-stack is used this option isn't 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 โœจ. This gets implemented by using special subsections .text.hot for the most frequently executed functions and .text.unlikely for the unlikely-executed ones. 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.

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 applicable to the language being compiled ๐Ÿ’…. For C (and C++), this activates optimizations based on the type of expressions. In particular, an object of one type is assumed never to reside at the same address as an object of a different type, unless the types are almost the same. For example, an unsigned int can alias an int, but not a void* or a double. A character type may alias any other type.

Pay special attention to code like this ๐Ÿ‘€:

union a_union {
  int i;
  double d;
};

int f() {
  union a_union t;
  t.d = 3.0;
  return t.i;
}

The practice of reading from a different union member than the one most recently written to (called "type-punning") is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type. So the code above works as expected. However, this code might not:

int f() {
  union a_union t;
  int* ip;
  t.d = 3.0;
  ip = &t.i;
  return *ip;
}

Similarly, access by taking the address, casting the resulting pointer, and dereferencing the result has undefined behavior โ€” even if the cast uses a union type, like:

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 apply 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 โ€” align the start of functions to the next power-of-two greater than or equal to n, skipping up to m-1 bytes ๐Ÿ’–. This ensures that at least the first m bytes of the function can be fetched by the CPU without crossing an n-byte alignment boundary. It's an optimization of code performance, and alignment is ignored for functions considered cold. If alignment is required for all functions, use -fmin-function-alignment.

If m isn't specified, it defaults to n.

Examples, because we love a demo: -falign-functions=32 aligns functions to the next 32-byte boundary, -falign-functions=24 aligns to the next 32-byte boundary only if this can be done by skipping 23 bytes or less, and -falign-functions=32:7 aligns to the next 32-byte boundary only if this can be done by skipping 6 bytes or less โœจ.

The second pair of n2:m2 values lets you specify a secondary alignment: -falign-functions=64:7:32:3 aligns to the next 64-byte boundary if this can be done by skipping 6 bytes or less, otherwise it aligns to the next 32-byte boundary if this can be done by skipping 2 bytes or less. If m2 isn't specified, it defaults to n2.

Some assemblers only support this flag when n is a power of two; in that case, it's rounded up ๐Ÿซถ.

-fno-align-functions and -falign-functions=1 are equivalent and mean that functions are not aligned.

If n isn't specified or is zero, use a machine-dependent default. The maximum allowed n option value is 65536.

Enabled at levels -O2, -O3.

  • -flimit-function-alignment โ€” if this is enabled, the compiler tries to avoid unnecessarily overaligning functions ๐Ÿ˜Œ. It attempts to instruct the assembler to align by the amount specified by -falign-functions, but not to skip more bytes than the size of the function.
  • -falign-labels
  • -falign-labels=n
  • -falign-labels=n:m
  • -falign-labels=n:m:n2
  • -falign-labels=n:m:n2:m2 โ€” align all branch targets to a power-of-two boundary ๐ŸŒˆ.

The parameters of this option are analogous to the -falign-functions option. -fno-align-labels and -falign-labels=1 are equivalent and mean labels aren't aligned.

If -falign-loops or -falign-jumps are applicable and are greater than this value, then their values are used instead.

If n isn't 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 โ€” align 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's an optimization of code performance, and alignment is ignored for loops considered cold.

If -falign-labels is greater than this value, then its value is used instead.

Parameters of this option are analogous to the -falign-functions option. -fno-align-loops and -falign-loops=1 are equivalent and mean loops aren't aligned. The maximum allowed n option value is 65536.

If n isn't specified or is zero, use a machine-dependent default.

Enabled at levels -O2, -O3.

  • -falign-jumps
  • -falign-jumps=n
  • -falign-jumps=n:m
  • -falign-jumps=n:m:n2
  • -falign-jumps=n:m:n2:m2 โ€” align branch targets to a power-of-two boundary, for branch targets where the targets can only be reached by jumping ๐Ÿ‘‘. In this case, no dummy operations need be executed. It's an optimization of code performance, and alignment is ignored for jumps considered cold.

If -falign-labels is greater than this value, then its value is used instead.

Parameters of this option are analogous to the -falign-functions option. -fno-align-jumps and -falign-jumps=1 are equivalent and mean that loops are not aligned.

If n is not specified or is zero, use a machine-dependent default. The maximum allowed n option value is 65536.

๐Ÿ”ฅ Enabled at levels -O2, -O3.

  • -fmin-function-alignment โ€” Specify minimal alignment of functions to the next power-of-two greater than or equal to n. Unlike -falign-functions this alignment is applied also to all functions (even those considered cold). The alignment is also not affected by -flimit-function-alignment.
  • -fno-allocation-dce โ€” Do not remove unused C++ allocations in dead code elimination. no ghost allocations getting swept, bestie ๐Ÿ’…
  • -fallow-store-data-races โ€” Allow the compiler to perform optimizations that may introduce new data races on stores, without proving that the variable cannot be concurrently accessed by other threads. Does not affect optimization of local data. It is safe to use this option if it is known that global data will not be accessed by multiple threads.

Examples of optimizations enabled by -fallow-store-data-races include hoisting or if-conversions that may cause a value that was already in memory to be re-written with that same value. Such re-writing is safe in a single threaded context but may be unsafe in a multi-threaded context. Note that on some processors, if-conversions may be required in order to enable vectorization.

Enabled at level -Ofast. โœจ

  • -funit-at-a-time โ€” This option is left for compatibility reasons. -funit-at-a-time has no effect, while -fno-unit-at-a-time implies -fno-toplevel-reorder and -fno-section-anchors.

Enabled by default. ๐Ÿซถ

  • -fno-toplevel-reorder โ€” Do not reorder top-level functions, variables, and asm statements. Output them in the same order that they appear in the input file. When this option is used, unreferenced static variables are not removed. This option is intended to support existing code that relies on a particular ordering. For new code, it is better to use attributes when possible.

-ftoplevel-reorder is the default at -O1 and higher, and also at -O0 if -fsection-anchors is explicitly requested. Additionally -fno-toplevel-reorder implies -fno-section-anchors.

  • -funreachable-traps โ€” With this option, the compiler turns calls to __builtin_unreachable into traps, instead of using them for optimization. This also affects any such calls implicitly generated by the compiler.

This option has the same effect as -fsanitize=unreachable -fsanitize-trap=unreachable, but does not affect the values of those options. If -fsanitize=unreachable is enabled, that option takes priority over this one.

This option is enabled by default at -O0 and -Og. ๐Ÿ’œ

  • -fweb โ€” Constructs webs as commonly used for register allocation purposes and assign each web individual pseudo register. This allows the register allocation pass to operate on pseudos directly, but also strengthens several other optimization passes, such as CSE, loop optimizer and trivial dead code remover. It can, however, make debugging impossible, since variables no longer stay in a "home register".

Enabled by default with -funroll-loops. ๐ŸŒ€

  • -fwhole-program โ€” Assume that the current compilation unit represents the whole program being compiled. All public functions and variables with the exception of main and those merged by attribute externally_visible become static functions and in effect are optimized more aggressively by interprocedural optimizers.

With -flto this option has a limited use. In most cases the precise list of symbols used or exported from the binary is known the resolution info passed to the link-time optimizer by the linker plugin. It is still useful if no linker plugin is used or during incremental link step when final code is produced (with -flto -flinker-output=nolto-rel).

  • -flto[=n] โ€” This option runs the standard link-time optimizer. When invoked with source code, it generates GIMPLE (one of GCC's internal representations) and writes it to special ELF sections in the object file. When the object files are linked together, all the function bodies are read from these ELF sections and instantiated as if they had been part of the same translation unit.

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

gcc -c -O2 -flto foo.c
gcc -c -O2 -flto bar.c
gcc -o myprog -flto -O2 foo.o bar.o

The first two invocations to GCC save a bytecode representation of GIMPLE into special ELF sections inside foo.o and bar.o. The final invocation reads the GIMPLE bytecode from foo.o and bar.o, merges the two files into a single internal image, and compiles the result as usual. Since both foo.o and bar.o are merged into a single image, this causes all the interprocedural analyses and optimizations in GCC to work across the two files as if they were a single one. This means, for example, that the inliner is able to inline functions in bar.o into functions in foo.o and vice-versa.

Another (simpler) way to enable link-time optimization is:

gcc -o myprog -flto -O2 foo.c bar.c

The above generates bytecode for foo.c and bar.c, merges them together into a single GIMPLE representation and optimizes them as usual to produce myprog.

The important thing to keep in mind is that to enable link-time optimizations you need to use the GCC driver to perform the link step. GCC automatically performs link-time optimization if any of the objects involved were compiled with the -flto command-line option. You can always override the automatic decision to do link-time optimization by passing -fno-lto to the link command.

To make whole program optimization effective, it is necessary to make certain whole program assumptions. The compiler needs to know what functions and variables can be accessed by libraries and runtime outside of the link-time optimized unit. When supported by the linker, the linker plugin (see -fuse-linker-plugin) passes information to the compiler about used and externally visible symbols. When the linker plugin is not available, -fwhole-program should be used to allow the compiler to make these assumptions, which leads to more aggressive optimization decisions.

When a file is compiled with -flto without -fuse-linker-plugin, the generated object file is larger than a regular object file because it contains GIMPLE bytecodes and the usual final code (see -ffat-lto-objects). This means that object files with LTO information can be linked as normal object files; if -fno-lto is passed to the linker, no interprocedural optimizations are applied. Note that when -fno-fat-lto-objects is enabled the compile stage is faster but you cannot perform a regular, non-LTO link on them.

When producing the final binary, GCC only applies link-time optimizations to those files that contain bytecode. Therefore, you can mix and match object files and libraries with GIMPLE bytecodes and final object code. GCC automatically selects which files to optimize in LTO mode and which files to link without further processing.

Generally, options specified at link time override those specified at compile time, although in some cases GCC attempts to infer link-time options from the settings used to compile the input files.

If you do not specify an optimization level option -O at link time, then GCC uses the highest optimization level used when compiling the object files. Note that it is generally ineffective to specify an optimization level option only at link time and not at compile time, for two reasons. First, compiling without optimization suppresses compiler passes that gather information needed for effective optimization at link time. Second, some early optimization passes can be performed only at compile time and not at link time.

There are some code generation flags preserved by GCC when generating bytecodes, as they need to be used during the final link. Currently, the following options and their settings are taken from the first object file that explicitly specifies them: -fcommon, -fexceptions, -fnon-call-exceptions, -fgnu-tm and all the -m target flags.

The following options -fPIC, -fpic, -fpie and -fPIE are combined based on the following scheme:

-fPIC + -fpic = -fpic
-fPIC + -fno-pic = -fno-pic
-fpic/-fPIC + (no option) = (no option)
-fPIC + -fPIE = -fPIE
-fpic + -fPIE = -fpie
-fPIC/-fpic + -fpie = -fpie

Certain ABI-changing flags are required to match in all compilation units, and trying to override this at link time with a conflicting value is ignored. This includes options such as -freg-struct-return and -fpcc-struct-return.

Other options such as -ffp-contract, -fno-strict-overflow, -fwrapv, -fno-trapv or -fno-strict-aliasing are passed through to the link stage and merged conservatively for conflicting translation units. Specifically -fno-strict-overflow, -fwrapv and -fno-trapv take precedence; and for example -ffp-contract=off takes precedence over -ffp-contract=fast. You can override them at link time.

Diagnostic options such as -Wstringop-overflow are passed through to the link stage and their setting matches that of the compile-step at function granularity. Note that this matters only for diagnostics emitted during optimization. Note that code transforms such as inlining can lead to warnings being enabled or disabled for regions if code not consistent with the setting at compile time.

When you need to pass options to the assembler via -Wa or -Xassembler make sure to either compile such translation units with -fno-lto or consistently use the same assembler options on all translation units. You can alternatively also specify assembler options at LTO link time. slay the link step, bestie ๐ŸŒˆ๐Ÿ’–

okay bestie so to actually get debug info generated you gotta hand over -g at compile time, no way around it. 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 like โ€” any elaborate debug info settings, the fancy stuff 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 fr fr. just don't.

and if LTO bumps into objects with C linkage declared with incompatible types in separate translation units being linked together โ€” which is undefined behavior per ISO C99 6.2.7, not me being dramatic, that's the spec โ€” a non-fatal diagnostic may be issued. the behavior is still undefined at run time. similar diagnostics may get raised for other languages too. so like, the compiler is being nice by warning you, but it's not saving you ๐Ÿ’€

another very slay feature of LTO: you can apply interprocedural optimizations on files written in different languages. look at this:

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 the final link is done with g++ so you get the C++ runtime libraries, and -lgfortran is tacked on to get the Fortran runtime libraries. generally, when you're mixing languages in LTO mode, use the same link command options as you would when mixing languages in a regular (non-LTO) compilation. consistency is the vibe โœจ

if object files containing GIMPLE bytecode are chilling in a library archive โ€” say libfoo.a โ€” you can extract and use them in an LTO link if you're using a linker with plugin support. to make 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. 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 needed GIMPLE files from libfoo.a and passes them on to the running GCC so they become part of the aggregated GIMPLE image that's gonna get optimized. iconic behavior ๐Ÿซถ

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 as usual โ€” but they don't participate in the LTO optimization process. 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. both worlds, bestie ๐Ÿ’…

link-time optimizations don't need the whole program present to operate, which is lowkey so nice. if the program doesn't require any symbols to be exported, you can combine -flto and -fwhole-program to let the interprocedural optimizers use 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 (see -fuse-linker-plugin).

now the sad part ๐Ÿ˜ญ โ€” 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. periodt. keep your versions matched.

also: link-time optimization does not work well with generation of debugging information on systems other than those using a combination of ELF and DWARF. just so you know ๐Ÿ™ˆ

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 may be used to override the program used. cute, right?

you can also specify -flto=jobserver to use GNU make's job server mode to determine the number of parallel jobs. this is useful when the Makefile calling GCC is already executing in parallel. you must prepend a + to the command recipe in the parent Makefile for this to work (don't skip that, it will Not work). 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 โ€” it's giving observant ๐Ÿ‘‘

use -flto=auto to use GNU make's job server if it's available, or otherwise fall back to autodetection of the number of CPU threads present in your system. auto-pilot mode, love that for you โญ

-flto-partition=alg

specify the partitioning algorithm used by the link-time optimizer. the value is either:

  • 1to1 โ€” partitioning that mirrors the original source files
  • balanced โ€” partitioning into equally sized chunks (whenever possible)
  • max โ€” create a new partition for every symbol where possible

specifying none as an algorithm disables partitioning and streaming completely. the default value is balanced. while 1to1 can be used as a workaround for various code ordering issues, the max partitioning is intended for internal testing only โ€” do not come for me if you try it. the value one specifies that exactly one partition should be used, while the value none bypasses partitioning and executes the link-time optimization step directly from the WPA phase. so many options, all valid, pick your fighter ๐ŸŒˆ

-flto-compression-level=n

this one specifies the level of compression used for 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) to 19 (maximum compression)
  • zlib โ€” supports values from 0 to 9

values outside this range get clamped to either the minimum or maximum of the supported values (so no, -flto-compression-level=1000 isn't gonna do anything extra, it just clamps). if the option isn't given, a default balanced compression setting is used. balanced queen ๐Ÿ’–

-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. so like, check your linker bestie.

this option enables the extraction of object files with GIMPLE bytecode out of library archives. this improves the quality of optimization by exposing more code to the link-time optimizer. this information specifies what symbols can be accessed externally (by non-LTO object or during dynamic linking). resulting code quality improvements on binaries (and shared libraries that use hidden visibility) are similar to -fwhole-program. see -flto for a description of the effect of this flag and how to use it.

this option is enabled by default when LTO support in GCC is enabled and GCC was configured for use with a linker supporting plugins (GNU ld 2.21 or newer or gold). free upgrade, we love to see it โœจ

-ffat-lto-objects

fat LTO objects are object files that contain both the intermediate language and the object code. this makes them usable for both LTO linking and normal linking. this option is effective only when compiling with -flto and is ignored at link time. (fat = thicc with two c's, both payloads inside ๐Ÿ“)

-fno-fat-lto-objects improves compilation time over plain LTO, but it requires the complete toolchain to be aware of LTO. it requires a linker with linker plugin support for basic functionality. additionally, nm, ar and ranlib need to support linker plugins to allow a full-featured build environment (capable of building static libraries etc). GCC provides the gcc-ar, gcc-nm, gcc-ranlib wrappers to pass the right options to these tools. with non fat LTO, makefiles need to be modified to use them. yes, you gotta edit the makefiles. sorry ๐Ÿ˜ญ

also note that modern binutils provide a plugin auto-load mechanism. installing the linker plugin into $libdir/bfd-plugins has the same effect as usage of the command wrappers (gcc-ar, gcc-nm and gcc-ranlib). same energy, different route.

the default is -fno-fat-lto-objects on targets with linker plugin support.

-fcompare-elim

after register allocation and post-register allocation instruction splitting, identify arithmetic instructions that compute processor flags similar to a comparison operation based on that arithmetic. if possible, eliminate the explicit comparison operation. sneaky efficient, obsessed ๐Ÿ’…

this pass only applies to certain targets that cannot explicitly represent the comparison operation before register allocation is complete. so like, target-dependent.

enabled at levels -O1, -O2, -O3, -Os.

-fcprop-registers

after register allocation and post-register allocation instruction splitting, perform a copy-propagation pass to try to reduce scheduling dependencies and occasionally eliminate the copy. honestly? tidy.

enabled at levels -O1, -O2, -O3, -Os.

-fprofile-correction

profiles collected using an instrumented binary for multi-threaded programs may be inconsistent due to missed counter updates (the counters simply miss stuff, it happens). when this option is specified, GCC uses heuristics to correct or smooth out such inconsistencies. by default, GCC emits an error message when an inconsistent profile is detected. no correction, just judgment.

this option is enabled by -fauto-profile.

-fprofile-partial-training

with -fprofile-use, all portions of programs not executed during the train run are optimized aggressively for size rather than speed. in some cases it's just not practical to train all possible hot paths in the program โ€” for example, the program may contain functions specific to a given hardware, and training may not cover all hardware configurations the program is run on. with -fprofile-partial-training, profile feedback will be ignored for all functions not executed during the train run, which leads 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 it also leads to significantly bigger code. tradeoff city, bestie ๐ŸŒธ

-fprofile-use

-fprofile-use=path

enable profile feedback-directed optimizations, plus the following optimizations โ€” many of which are generally profitable only when profile feedback is actually 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. like, actually. it's not optional, the whole thing runs on that data.

so like, by default, GCC throws a whole error message if the feedback profiles don't match the source code ๐Ÿ˜ค. You can turn that error into a warning by using -Wno-error=coverage-mismatch โ€” but bestie, note this 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).

If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.

  • -fauto-profile, -fauto-profile=path** โ€” turns on sampling-based feedback-directed optimizations plus this whole squad of optimizations, many of which are generally profitable only when you actually have profile feedback available:
-fbranch-probabilities  -fprofile-values -funroll-loops
-fpeel-loops  -ftracer  -fvpt -finline-functions  -fipa-cp
-fipa-cp-clone  -fipa-bit-cp -fpredictive-commoning  -fsplit-loops
-funswitch-loops -fgcse-after-reload  -ftree-loop-vectorize
-ftree-slp-vectorize -fvect-cost-model=dynamic
-ftree-loop-distribute-patterns -fprofile-correction

path is the name of a file containing AutoFDO profile information. If you omit it, it defaults to fbdata.afdo in the current directory.

Producing an AutoFDO profile data file requires running your program with the perf utility on a supported GNU/Linux target system. For more 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 to a format that GCC can use. You also have to supply the unstripped binary for your program to this tool. See https://github.com/google/autofdo.

E.g.

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

okay now we're entering the floating-point zone ๐ŸŒŠ๐Ÿ’… โ€” the following options control compiler behavior regarding floating-point arithmetic. They trade off between speed and correctness, and every single one must be specifically enabled (no auto-magic, bestie).

  • -ffloat-store โ€” do not store floating-point variables in registers, and inhibit other options that might change whether a floating-point value is taken from a register or memory.

This option prevents undesirable excess precision on machines such as the 68000 where the floating registers (of the 68881) keep more precision than a "double" is supposed to have. Similarly for the x86 architecture. For most programs, the excess precision does only good, but a few programs rely on the precise definition of IEEE floating point. Use -ffloat-store for such programs, after modifying them to store all pertinent intermediate computations into variables.

  • -fexcess-precision=style** โ€” this option allows further control over excess precision on machines where floating-point operations occur in a format with more precision or range than the IEEE standard and interchange floating-point types. By default, -fexcess-precision=fast is in effect; this means that operations may be carried out in a wider precision than the types specified in the source if that would result in faster code, and it is unpredictable when rounding to the types specified in the source code takes place. When compiling C 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.

This option causes the preprocessor macro __FAST_MATH__ to be defined.

This option is not turned on by any -O option besides -Ofast since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.

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

This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.

The default is -fmath-errno.

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

  • -funsafe-math-optimizations โ€” allow optimizations for floating-point arithmetic that (a) assume that arguments and results are valid and (b) may violate IEEE or ANSI standards. When used at link time, it may include libraries or startup files that change the default FPU control word or other similar optimizations.

This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications. Enables -fno-signed-zeros, -fno-trapping-math, -fassociative-math and -freciprocal-math.

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

  • -fassociative-math โ€” allow re-association of operands in series of floating-point operations. This violates the ISO C and C++ language standard by possibly changing computation result. NOTE: re-ordering may change the sign of zero as well as ignore NaNs and inhibit or create underflow or overflow (and thus cannot be used on code that relies on rounding behavior like "(x + 2**52) - 2**52". May also reorder floating-point comparisons and thus may not be used when ordered comparisons are required. This option requires that both -fno-signed-zeros and -fno-trapping-math be in effect. Moreover, it doesn't make much sense with -frounding-math. For Fortran the option is automatically enabled when both -fno-signed-zeros and -fno-trapping-math are in effect.

The default is -fno-associative-math.

  • -freciprocal-math โ€” allow the reciprocal of a value to be used instead of dividing by the value if this enables optimizations. For example "x / y" can be replaced with "x * (1/y)", which is useful if "(1/y)" is subject to common subexpression elimination. Note that this loses precision and increases the number of flops operating on the value.

The default is -fno-reciprocal-math.

  • -ffinite-math-only โ€” allow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or +-Infs.

This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.

The default is -fno-finite-math-only.

  • -fno-signed-zeros โ€” allow optimizations for floating-point arithmetic that ignore the signedness of zero. IEEE arithmetic specifies the behavior of distinct +0.0 and -0.0 values, which then prohibits simplification of expressions such as x+0.0 or 0.0*x (even with -ffinite-math-only). This option implies that the sign of a zero result isn't significant.

The default is -fsigned-zeros.

  • -fno-trapping-math โ€” compile code assuming that floating-point operations cannot generate user-visible traps. These traps include division by zero, overflow, underflow, inexact result and invalid operation. This option requires that -fno-signaling-nans be in effect. Setting this option may allow faster code if one relies on "non-stop" IEEE arithmetic, for example.

This option should never be turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions.

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 โ€” okay so this one says: compile assuming IEEE signaling NaNs might throw user-visible traps during floating-point ops ๐Ÿ‘€. Turning it on disables the optimizations that could change how many exceptions are visible when signaling NaNs are around. It implies -ftrapping-math. Bonus: it makes the preprocessor macro __SUPPORT_SNAN__ get defined โœจ. The default is -fno-signaling-nans. And bestie, heads up: this option is experimental and does not currently guarantee to disable all GCC optimizations that affect signaling NaN behavior ๐Ÿ˜ญ so likeโ€ฆ vibe with caution.
  • -fno-fp-int-builtin-inexact โ€” this one tells the built-in functions ceil, floor, round and trunc (plus their float and long double variants) not to generate code that raises the inexact floating-point exception for noninteger arguments. Why does that matter? Because ISO C99 and C11 allow these functions to raise inexact, but ISO/IEC TS 18661-1:2014 (the C bindings to IEEE 754-2008, as integrated into ISO C2X) does not allow them to ๐ŸŒธ. The default is -ffp-int-builtin-inexact โ€” i.e. the exception is allowed โ€” unless C2X or a later C standard is selected. Ngl this option does literally nothing unless -ftrapping-math is in effect. And even with -fno-fp-int-builtin-inexact, if the functions generate a call to a library function, the inexact exception may still be raised if the library implementation doesn't follow TS 18661 ๐Ÿ’€.
  • -fsingle-precision-constant โ€” treats floating-point constants as single precision instead of sneakily implicitly converting them to double-precision constants. No cap, that's the whole thing ๐ŸŽ€.
  • -fcx-limited-range โ€” when enabled, this option states that a range reduction step is not needed when performing complex division. Also: no checking whether the result of a complex multiplication or division is NaN + I*NaN, with an attempt to rescue the situation in that case ๐Ÿ™ˆ. Default is -fno-cx-limited-range, but it gets enabled by -ffast-math. It controls the default setting of the ISO C99 CX_LIMITED_RANGE pragma โ€” but the option itself applies to all languages, periodt ๐Ÿ’….
  • -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, like actually broken, you've been warned bestie ๐Ÿซถ.

  • -fbranch-probabilities โ€” after running a program compiled with -fprofile-arcs, you can compile it a second time using -fbranch-probabilities to improve optimizations based on the number of times each branch was taken ๐Ÿ“Š. When a program compiled with -fprofile-arcs exits, it saves arc execution counts to a file called sourcename.gcda for each source file. The 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. (Details about the file naming live in -fprofile-arcs.)

With -fbranch-probabilities, GCC puts a REG_BR_PROB note on each JUMP_INSN and CALL_INSN. These can be used to improve optimization. Currently they're only used in one place: in reorg.cc, instead of guessing which path a branch is most likely to take, the REG_BR_PROB values are used to exactly determine which path is taken more often ๐Ÿ‘‘

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

  • -fprofile-values โ€” if combined with -fprofile-arcs, it adds code so that some data about values of expressions in the program is gathered. With -fbranch-probabilities, it reads back the data gathered from profiling values of expressions for usage in optimizations ๐Ÿ”ฅ. Enabled by -fprofile-generate, -fprofile-use, and -fauto-profile.
  • -fprofile-reorder-functions โ€” function reordering based on profile instrumentation collects first time of execution of a function and orders these functions in ascending order โฑ๏ธ. Enabled with -fprofile-use.
  • -fvpt โ€” if combined with -fprofile-arcs, this option instructs the compiler to add code to gather information about values of expressions. With -fbranch-probabilities, it reads back the data gathered and actually performs the optimizations based on them. Currently the optimizations include specialization of division operations using the knowledge about the value of the denominator ๐Ÿงš. Enabled with -fprofile-use and -fauto-profile.
  • -frename-registers โ€” attempt to avoid false dependencies in scheduled code by making use of registers left over after register allocation. This optimization most benefits processors with lots of registers ๐Ÿ’–. Depending on the debug information format adopted by the target, however, it can make debugging impossible, since variables no longer stay in a "home register" ๐Ÿ˜ญ. 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 is enough information that they do not 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. For example:
for (int i = 0; i < n; ++i)
  x[i * stride] = ...;

becomes:

if (stride == 1)
  for (int i = 0; i < n; ++i)
    x[i] = ...;
else
  for (int i = 0; i < n; ++i)
    x[i * stride] = ...;

This is particularly useful for assumed-shape arrays in Fortran, where (for example) it allows better vectorization assuming contiguous accesses ๐ŸŒˆ. This flag is enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile.

  • -ffunction-sections and -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; }

...the compiler usually just calculates the addresses of all three variables, but if you compile with -fsection-anchors, it grabs them from one shared anchor point instead ๐Ÿ’… the effect is basically this pseudocode (which, heads up, isn't valid C):

int foo (void)
{
  register int *xr = &x;
  return xr[&a - &x] + xr[&b - &x] + xr[&c - &x];
}

and ngl, not every target supports this option ๐Ÿ™ˆ

  • -fzero-call-used-regs=choice โ€” zeroes out the call-used registers at function return so your program is more secure ๐Ÿ’ช it does this either by mitigating Return-Oriented Programming (ROP) attacks or by stopping information from leaking through registers. The possible values of choice are the same as for the zero_call_used_regs attribute, and the default is skip. You can control this behaviour for one specific function by using the function attribute zero_call_used_regs ๐ŸŽ€
  • --param name=value โ€” so GCC has a bunch of constants hiding inside it that control how much optimization gets done. Like, GCC won't inline functions that contain more than a certain number of instructions, right? Well, you can control some of these constants right from the command line with --param โœจ

The names of the specific parameters, and what their values actually mean, are tied to the compiler's internals, and are subject to change without notice in future releases ๐Ÿ‘€ (iykyk โ€” don't build your whole personality on these staying the same).

Wanna see the minimal, maximal and default values of a parameter? Use the --help=param -Q options. Super handy ๐Ÿซถ

In every 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's considered well predictable ๐ŸŒธ
  • max-rtl-if-conversion-insns โ€” RTL if-conversion tries to remove the conditional branches around a block and replace them with conditionally executed instructions. This parameter gives the max number of instructions in a block that should 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 just vibes ๐Ÿ’…
  • max-rtl-if-conversion-predictable-cost โ€” RTL if-conversion will try to remove the conditional branches around a block and swap them for 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 max 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. Bumping this value up means more aggressive optimization, which makes compilation time go up with probably only a small improvement in executable size ๐Ÿ˜ญ
  • min-crossjump-insns โ€” the minimum number of instructions that have to match at the end of two blocks before cross-jumping is 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 max number of instructions to duplicate to a block that jumps to a computed goto. To avoid O(N^2) behaviour in a bunch of passes, GCC factors computed gotos early in the compilation process and unfactors them as late as possible. Only computed jumps at the end of a basic block with no more than max-goto-duplication-insns are unfactored ๐ŸŒ€
  • max-delay-slot-insn-search โ€” the max 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, which makes compilation time go up with probably a small improvement in execution time ๐ŸŒˆ
  • max-delay-slot-live-search โ€” when trying to fill delay slots, the max number of instructions to consider when searching for a block with valid live register information. Increasing this arbitrarily chosen value means more aggressive optimization, increasing compilation time. This parameter should be removed when the delay slot code gets rewritten to maintain the control-flow graph ๐ŸŽ€
  • max-gcse-memory โ€” the approximate maximum amount of memory in kB that can be allocated to perform the global common subexpression elimination optimization. If more memory than specified is required, the optimization just doesn't happen ๐Ÿคทโ€โ™€๏ธ
  • max-gcse-insertion-ratio โ€” if the ratio of expression insertions to deletions is larger than this value for any expression, then RTL PRE inserts or removes the expression and thus leaves partially redundant computations in the instruction stream ๐Ÿ‘€
  • max-pending-list-length โ€” the max number of pending dependencies scheduling allows before flushing the current state and starting over. Large functions with few branches or calls can create excessively large lists which needlessly consume memory and resources ๐Ÿ˜ญ
  • max-modulo-backtrack-attempts โ€” the max number of backtrack attempts the scheduler should make when modulo scheduling a loop. Larger values can exponentially increase compilation time ๐Ÿ’€
  • 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 โ€” several parameters control the tree inliner used in GCC. This number sets the max number of instructions (counted in GCC's internal representation) in a single function that the tree inliner considers for inlining. This only affects functions declared inline and methods implemented in a class declaration (C++) ๐Ÿ‘‘
  • max-inline-insns-auto โ€” when you use -finline-functions (which is included in -O3), a 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 function prologue and epilogue โณ
  • inline-heuristics-hint-percent โ€” the scale (in percents) applied to inline-insns-single, inline-insns-single-O2 and inline-insns-auto when inline heuristics hint that inlining is very profitable (which will enable later optimizations) ๐Ÿ”ฅ
  • uninlined-thunk-insns, uninlined-thunk-time โ€” same as --param uninlined-function-insns and --param uninlined-function-time but applied to function thunks ๐Ÿ’œ
  • inline-min-speedup โ€” when the estimated performance improvement of caller + callee runtime exceeds this threshold (in percent), the function can be inlined regardless of the limit on --param max-inline-insns-single and --param max-inline-insns-auto ๐Ÿš€
  • 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's 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. So for smaller units, the size is increased to --param large-unit-insns before applying --param inline-unit-growth ๐ŸŒˆ
  • lazy-modules โ€” max number of concurrently open C++ module files when lazy loading ๐Ÿ—‚๏ธ
  • inline-unit-growth โ€” specifies maximal overall growth of the compilation unit caused by inlining. For example, parameter value 20 limits unit growth to 1.2 times the original size. Cold functions (either marked cold via an attribute or by profile feedback) are not accounted into the unit size ๐ŸงŠ
  • ipa-cp-unit-growth โ€” specifies maximal overall growth of the compilation unit caused by interprocedural constant propagation. For example, parameter value 10 limits unit growth to 1.1 times the original size ๐Ÿ‘‘
  • ipa-cp-large-unit-insns โ€” how big a translation unit has to be before the IPA-CP pass is like "okay that's large" ๐Ÿ‘€
  • large-stack-frame โ€” the threshold that defines a "large" stack frame. While it's inlining, the algorithm genuinely tries not to blow past this limit too much ๐Ÿซถ
  • large-stack-frame-growth โ€” the max growth of large stack frames caused by inlining, in percents. Like, a value of 1000 caps large stack frame growth at 11 times the original size. math is mathing ๐Ÿ’…
  • max-inline-insns-recursive, max-inline-insns-recursive-auto โ€” the max number of instructions an out-of-line copy of a self-recursive inline function can grow into via recursive inlining.

--param max-inline-insns-recursive is the one for functions declared inline. For functions that aren't 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. two flavors, pick your fighter โœจ

  • max-inline-recursive-depth, max-inline-recursive-depth-auto โ€” the max recursion depth used for recursive inlining.

Same deal as above: --param max-inline-recursive-depth applies to functions declared inline, and for functions not declared inline, recursive inlining only kicks in when -finline-functions (included in -O3) is enabled, in which case --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 little recursion depth โ€” like, it bloats the prologue size or makes the function body more complex for 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 percents). threshold queen ๐Ÿ‘‘

  • early-inlining-insns โ€” how much growth the early inliner is allowed to make. Basically it boosts the amount of inlining for code with a large abstraction penalty ๐ŸŽ€
  • max-early-inliner-iterations โ€” the iteration limit of the early inliner. It basically bounds how many nested indirect calls the early inliner can resolve. Deeper chains still get handled by late inlining, no worries ๐Ÿฆ‹
  • 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 max number of base pointers, references, and accesses stored for a single function by mod/ref analysis ๐Ÿ—‚๏ธ
  • modref-max-tests โ€” the max number of tests the alias oracle can perform to disambiguate memory locations using the mod/ref info. This one ought to be bigger than --param modref-max-bases and --param modref-max-refs, so keep that in mind bestie ๐Ÿ’…
  • modref-max-depth โ€” the max depth of the DFS walk used by modref escape analysis. Setting it to 0 disables the analysis completely. poof, gone ๐Ÿ’€
  • modref-max-escape-points โ€” the max number of escape points tracked by modref per SSA-name ๐Ÿƒโ€โ™€๏ธ๐Ÿ’จ
  • modref-max-adjustments โ€” the max number of times the access range gets enlarged during modref dataflow analysis ๐Ÿ“ˆ
  • profile-func-internal-id โ€” controls whether to use the function internal id in profile database lookup. If the value is 0, the compiler uses an id based on the function assembler name and filename, which makes old profile data more tolerant to source changes such as function reordering etc. nostalgic profile data hours ๐Ÿ˜Œ
  • min-vect-loop-bound โ€” the minimum number of iterations under which loops are not vectorized when -ftree-vectorize is used. After vectorization, the number of iterations needs to be greater than the value specified by this option for vectorization to be allowed ๐ŸŒ€
  • gcse-cost-distance-ratio โ€” a scaling factor in the calculation of the max distance an expression can be moved by GCSE optimizations. Currently this is only supported in the code hoisting pass. The bigger the ratio, the more aggressive code hoisting is with simple expressions โ€” aka 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 how far an expression can travel. Currently only supported in the code hoisting pass. The lesser the cost, the more aggressive code hoisting is. Specifying 0 lets all expressions travel unrestricted distances โ€” no cap, main character energy ๐Ÿ‘‘
  • max-hoist-depth โ€” the depth of the search in the dominator tree for expressions to hoist. It exists to avoid quadratic behavior in the hoisting algorithm. A value of 0 puts no limit on the search, but it may slow down compilation of huge functions ๐ŸŒ
  • max-tail-merge-comparisons โ€” the max amount of similar bbs to compare a bb with. This is used to avoid quadratic behavior in tree tail merging ๐ŸŒณ
  • max-tail-merge-iterations โ€” the max amount of iterations of the pass over the function. This is used to limit compilation time in tree tail merging โณ
  • store-merging-allow-unaligned โ€” lets the store merging pass introduce unaligned stores if it's legal to do so ๐Ÿ™ˆ
  • max-stores-to-merge โ€” the max number of stores to attempt to merge into wider stores in the store merging pass ๐Ÿงฉ
  • max-store-chains-to-track โ€” the max 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 max number of stores to track at the same time in the attempt to merge them into wider stores in the store merging pass ๐Ÿ‘€
  • max-unrolled-insns โ€” the max number of instructions a loop may have to be unrolled. If a loop is unrolled, this parameter also determines how many times the loop code is unrolled ๐ŸŽž๏ธ
  • max-average-unrolled-insns โ€” the max number of instructions, biased by the probabilities of their execution, that a loop may have to be unrolled. If a loop is unrolled, this parameter also determines how many times the loop code is unrolled ๐Ÿ“Š
  • max-unroll-times โ€” the max number of unrollings of a single loop ๐Ÿ”‚
  • max-peeled-insns โ€” the max number of instructions a loop may have to be peeled. If a loop is peeled, this parameter also determines how many times the loop code is peeled ๐ŸŒ
  • max-peel-times โ€” the max number of peelings of a single loop ๐ŸŒ๐ŸŒ
  • max-peel-branches โ€” the max number of branches on the hot path through the peeled sequence ๐ŸŒถ๏ธ
  • max-completely-peeled-insns โ€” the max number of insns of a completely peeled loop โœจ
  • max-completely-peel-times โ€” the max number of iterations of a loop for it to be suitable for complete peeling ๐Ÿ”„
  • max-completely-peel-loop-nest-depth โ€” the max depth of a loop nest suitable for complete peeling ๐Ÿช†
  • max-unswitch-insns โ€” the max number of insns of an unswitched loop ๐Ÿ”€
  • max-unswitch-depth โ€” the max 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, this specifies the minimum threshold for the probability of a semi-invariant condition statement to trigger a loop split โœ‚๏ธ
  • iv-consider-all-candidates-bound โ€” a bound on the number of candidates for induction variables; below it, all candidates get considered for each use in induction variable optimizations. If there are more candidates than this, only the most relevant ones are considered, to avoid quadratic time complexity โฑ๏ธ
  • iv-max-considered-uses โ€” the induction variable optimizations give up on loops containing more induction variable uses ๐Ÿณ๏ธ
  • 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 max size (in bytes) of objects tracked bytewise by dead store elimination. Larger values may result in larger compilation times โš ๏ธ
  • dse-max-alias-queries-per-store โ€” the max number of queries into the alias oracle per store. Larger values result in larger compilation times and may result in more removed dead stores ๐Ÿ—‘๏ธ
  • scev-max-expr-size โ€” a bound on the size of expressions used in the scalar evolutions analyzer. Large expressions slow the analyzer down ๐Ÿข
  • scev-max-expr-complexity โ€” a bound on the complexity of expressions in the scalar evolutions analyzer. Complex expressions slow the analyzer down too ๐Ÿ˜ฎโ€๐Ÿ’จ
  • max-tree-if-conversion-phi-args โ€” the max number of arguments in a PHI supported by TREE if conversion, unless the loop is marked with simd pragma ๐ŸŽฏ
  • vect-max-layout-candidates โ€” the max number of possible vector layouts (such as permutations) to consider when optimizing to-be-vectorized code ๐Ÿงฎ
  • vect-max-version-for-alignment-checks โ€” the max number of run-time checks that can be performed when doing loop versioning for alignment in the vectorizer ๐Ÿ“
  • vect-max-version-for-alias-checks โ€” the max number of run-time checks that can be performed when doing loop versioning for alias in the vectorizer ๐Ÿ•ต๏ธโ€โ™€๏ธ
  • vect-max-peeling-for-alignment โ€” the max number of loop peels to enhance access alignment for the vectorizer. A value of -1 means no limit ๐ŸŒˆ
  • max-iterations-to-track โ€” the max number of iterations of a loop that the brute-force algorithm (the one analysing how many times a loop runs) will actually bother evaluating. Like, that's the cap on its patience ๐Ÿ’…
  • hot-bb-count-fraction โ€” so this one's the denominator n of the fraction 1/n, taken from the maximal execution count of a basic block across the whole program. A basic block needs at least that much to be considered ๐Ÿ”ฅhot๐Ÿ”ฅ. Default is 10000, meaning a basic block is hot if its execution count is greater than 1/10000 of the maximal execution count. 0 means it's never considered hot. Used in non-LTO mode, iykyk.
  • hot-bb-count-ws-permille โ€” the number of most-executed permilles, ranging from 0 to 1000, of the profiled execution of the entire program that a basic block's execution count has to be part of for it to count as hot. Default is 990, which means a basic block is hot if its execution count contributes to the upper 990 permilles, aka 99.0%, of the profiled execution of the whole program. 0 means never hot, periodt. Used in LTO mode.
  • hot-bb-frequency-fraction โ€” the denominator n of the fraction 1/n of the execution frequency of a function's entry block; a basic block in that function needs at least that much to be considered hot. Default is 1000, so a basic block is hot within a function if it's executed more frequently than 1/1000 of the frequency of the function's entry block. 0 means it's never considered hot, no cap.
  • unlikely-bb-count-fraction โ€” the denominator n of the fraction 1/n of the number of profiled runs of the entire program, below which a basic block's execution count has to fall for the block to be considered unlikely executed ๐Ÿ™ˆ. Default is 20, meaning a basic block is unlikely executed if it runs in fewer than 1/20, or 5%, of the program's runs. 0 means it's always considered unlikely executed โ€” chaotic but okay.
  • max-predicted-iterations โ€” the max number of loop iterations we predict statically. Super useful when a function has one loop with a known bound and another with an unknown bound: the known iteration count gets predicted correctly, while the unknown one averages out to roughly 10. Which means the loop with no bounds looks artificially cold next to the other one ๐Ÿฅถ โ€” not its fault, honestly.
  • builtin-expect-probability โ€” controls the probability of the expression having the specified value. Takes a percentage (i.e. 0 ... 100) as input. Slay.
  • builtin-string-cmp-inline-length โ€” the maximum length of a constant string for a builtin string cmp call that's eligible for inlining.
  • align-threshold โ€” picks the fraction of the maximal frequency of executions of a basic block in a function, used 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. It keeps unnecessary code size expansion in check, bestie ๐ŸŽ€

The tracer-dynamic-coverage-feedback parameter is used only when profile feedback is available. Real profiles (as opposed to statically estimated ones) are much less balanced, which lets the threshold be a larger value.

  • tracer-max-code-growth โ€” stops tail duplication once code growth hits the given percentage. It's a pretty artificial limit, because most of the duplicates get eliminated later in cross jumping โ€” so you can set it to way higher values than the code growth you actually want ๐Ÿ’€
  • tracer-min-branch-ratio โ€” stops reverse growth when the reverse probability of the best edge is less than this threshold (in percent).
  • tracer-min-branch-probability, tracer-min-branch-probability-feedback โ€” stops forward growth if the best edge's probability is lower than this threshold.

Same energy as tracer-dynamic-coverage: two parameters, one for each situation. tracer-min-branch-probability-feedback is used when compiling with profile feedback, and tracer-min-branch-probability when compiling without. The value for compilation with profile feedback needs to be more conservative (higher) to make tracer effective fr fr.

  • 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 heads up: a value larger than the operating system provided guard will leave code vulnerable to stack clash style attacks ๐Ÿ˜ญ
Not me warning you twice โ€” protect your stack, bestie.
  • stack-clash-protection-probe-interval โ€” stack clash protection involves probing stack space as it's 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 a value larger than the operating system provided guard will leave code vulnerable to stack clash style attacks ๐Ÿ”ฅ
  • 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 flushing.
  • ggc-min-expand โ€” GCC uses a garbage collector to manage its own memory allocation. This parameter specifies the minimum percentage by which the garbage collector's heap should be allowed to expand between collections. Tuning this may improve compilation speed; it has no effect on code generation. ๐Ÿฆ‹

The default is 30% + 70% * (RAM/1GB) with an upper bound of 100% when RAM >= 1GB. If "getrlimit" is available, the notion of "RAM" is the smallest of actual RAM and "RLIMIT_DATA" or "RLIMIT_AS". If GCC isn't able to calculate RAM on a particular platform, the lower bound of 30% is used. Setting this parameter and ggc-min-heapsize to zero causes a full collection to occur at every opportunity. That is extremely slow, but can be useful for debugging ๐Ÿ‘‘

  • ggc-min-heapsize โ€” minimum size of the garbage collector's heap before it begins bothering to collect garbage. The first collection 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. Setting this parameter and ggc-min-expand to zero causes a full collection to occur at every opportunity.

  • max-reload-search-insns โ€” the maximum number of instructions reload should look backward for an equivalent register. Increasing values mean more aggressive optimization, which makes compilation time go up with probably slightly better performance. The eternal tradeoff, honestly ๐Ÿซถ
  • max-cselib-memory-locations โ€” the maximum number of memory locations cselib should take into account. Increasing values mean more aggressive optimization, making the compilation time increase with probably slightly better performance.
  • max-sched-ready-insns โ€” the maximum number of instructions ready to be issued that the scheduler should consider at any given time during the first scheduling pass. Increasing values mean more thorough searches, making the compilation time increase with probably little benefit ๐Ÿ’€
  • max-sched-region-blocks โ€” the maximum number of blocks in a region to be considered for interblock scheduling.
  • max-pipeline-region-blocks โ€” the maximum number of blocks in a region to be considered for pipelining in the selective scheduler.
  • max-sched-region-insns โ€” the maximum number of insns in a region to be considered for interblock scheduling.
  • max-pipeline-region-insns โ€” the maximum number of insns in a region to be considered for pipelining in the selective scheduler.
  • min-spec-prob โ€” the minimum probability (in percents) of reaching a source block for interblock speculative scheduling.
  • max-sched-extend-regions-iters โ€” the maximum number of iterations through CFG to extend regions. A value of 0 disables region extensions.
  • max-sched-insn-conflict-delay โ€” the maximum conflict delay for an insn to be considered for speculative motion.
  • sched-spec-prob-cutoff โ€” the minimal probability of speculation success (in percents), so that speculative insns 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 basically a depth of search for available instructions ๐Ÿ”
  • selsched-max-sched-times โ€” the maximum number of times an instruction is scheduled during selective scheduling. This is the limit on the number of iterations through which the instruction may be pipelined.
  • selsched-insns-to-rename โ€” the maximum number of best instructions in the ready list that 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 number of RTLs, that the combiner is allowed to record for a pseudo register as that register's last known value. โœจ
  • max-combine-insns โ€” the max number of instructions the RTL combiner will try to combine. That's it, that's the whole vibe.
  • integer-share-limit โ€” little integer constants can share one data structure, which cuts the compiler's memory use and speeds it up. This param sets the ceiling on the value of a shared integer constant. ๐Ÿ’–
  • ssp-buffer-size โ€” the minimum size of buffers (like, arrays, bestie) that get stack smashing protection when -fstack-protector is in play.
  • min-size-for-stack-sharing โ€” the minimum size of variables that get to take part in stack slot sharing when you're not optimizing. ๐Ÿซถ
  • max-jump-thread-duplication-stmts โ€” the maximum number of statements allowed in a block that has to be duplicated when threading jumps.
  • max-jump-thread-paths โ€” the maximum number of paths considered when hunting for jump threading opportunities. When you land on a block, incoming edges only get considered if the number of paths searched so far times the number of incoming edges doesn't blow past this specified maximum. Math check, lowkey ๐Ÿ’…
  • max-fields-for-field-sensitive โ€” the maximum number of fields in a structure that get treated in a field sensitive manner during pointer analysis.
  • prefetch-latency โ€” an estimate of the average number of instructions executed before a prefetch finishes. How far ahead it prefetches is proportional to this constant. Heads up though: bumping this number may also mean fewer streams get prefetched โ€” see simultaneous-prefetches. ๐Ÿฆ‹
  • simultaneous-prefetches โ€” maximum number of prefetches that can be running at the same time.
  • l1-cache-line-size โ€” the size of a cache line in the L1 data cache, in bytes.
  • l1-cache-size โ€” the size of the L1 data cache, in kilobytes.
  • l2-cache-size โ€” the size of the L2 data cache, in kilobytes.
  • prefetch-dynamic-strides โ€” whether the loop array prefetch pass should fire off software prefetch hints for strides that are non-constant. Sometimes that's genuinely a win, but ngl, the fact that the stride is non-constant can make it hard to predict whether there's a clear benefit to issuing those hints at all.

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

  • prefetch-minimum-stride โ€” the minimum constant stride, in bytes, before we start using prefetch hints at all. If the stride is under this threshold, no prefetch hints for you ๐Ÿ™ˆ

This one's a lifesaver for processors with hardware prefetchers โ€” in that case the hardware prefetchers and software prefetchers can beef with each other. If the hardware prefetchers have a maximum stride they can handle, put it here and the software prefetchers get used way better. ๐Ÿ‘‘

A value of -1 means we have no threshold, so prefetch hints can be issued for any constant stride.

This setting is only useful for strides that are known and constant. Periodt.
  • destructive-interference-size / constructive-interference-size โ€” the values for the C++17 variables std::hardware_destructive_interference_size and std::hardware_constructive_interference_size. The destructive interference size is the minimum recommended offset between two independent concurrently-accessed objects; the constructive interference size is the maximum recommended size of contiguous memory accessed together. Typically both are the size of an L1 cache line for the target, in bytes. For a generic target covering a range of L1 cache line sizes, the constructive interference size is usually the small end of the range and the destructive size is the large end. ๐ŸŒˆ

The destructive interference size is meant for layout, and that means 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 anywhere ABI stability matters โ€” like the public interface of a library โ€” is strongly discouraged. If you do use it there, users can stabilize the value with this option. ๐Ÿ˜ญ

The constructive interference size is less sensitive, since it's typically only used in a static_assert to make sure a type fits within a cache line. Cute, low-stakes.

See also -Winterference-size.

  • loop-interchange-max-num-stmts โ€” the maximum number of stmts in a loop that'll be interchanged.
  • loop-interchange-stride-ratio โ€” the minimum ratio between the strides of two loops for interchange to actually be profitable.
  • min-insn-to-prefetch-ratio โ€” the minimum ratio between the number of instructions and the number of prefetches 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.
  • use-canonical-types โ€” whether the compiler uses the "canonical" type system. It should always be 1, which uses a more efficient internal mechanism for comparing types in C++ and Objective-C++. But if bugs in the canonical type system are making compilation fail, set this to 0 to disable canonical types. Emergency lever, iykyk ๐Ÿšจ
  • switch-conversion-max-branch-ratio โ€” switch initialization conversion refuses to create arrays bigger than switch-conversion-max-branch-ratio times the number of branches in the switch. Respect the cap โœจ
  • max-partial-antic-length โ€” maximum length of the partial antic set computed during the tree partial redundancy elimination optimization (-ftree-pre) when optimizing at -O3 and above. For some sorts of source code the enhanced partial redundancy elimination optimization can absolutely run away and eat all the memory on the host machine ๐Ÿ’€ This parameter puts a limit on the length of the sets computed, which stops the runaway behavior. Setting a value of 0 for this parameter allows an unlimited set length โ€” main character energy, zero guardrails.
  • 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.
  • sccvn-max-alias-queries-per-access โ€” maximum number of alias-oracle queries performed when looking for redundancies for loads and stores. If this limit gets hit, the search is aborted and the load or store isn't considered redundant. The number of queries is algorithmically limited to the number of stores on all paths from the load to the function entry. ๐ŸŽ€
  • ira-max-loops-num โ€” IRA uses regional register allocation by default. If a function contains more loops than this parameter's number, only at most that many of the most frequently-executed loops form regions for regional register allocation.
  • ira-max-conflict-table-size โ€” IRA uses a sophisticated algorithm to compress the conflict table, but that table can still need an excessive amount of memory for huge functions. If a function's conflict table could be bigger than the size in MB given by this parameter, the register allocator instead falls back to a faster, simpler, lower-quality algorithm that doesn't need a pseudo-register conflict table. Trade-off slay ๐Ÿ’…
  • ira-loop-reserved-regs โ€” IRA can be used to evaluate more accurate register pressure in loops when deciding whether to move loop invariants (see -O3). This parameter gives the number of available registers reserved for some other purposes. Default of the parameter is the best one found from numerous experiments. Science! ๐Ÿ”ฅ
  • ira-consider-dup-in-all-alts โ€” makes IRA consider matching constraint (duplicated operand number) heavily across all available alternatives for preferred register class. If it's set to zero, IRA only respects the matching constraint when it's in the only available alternative with an appropriate register class. Otherwise, IRA will check all available alternatives for preferred register class even after it's found some choice with an appropriate register class โ€” and then respect the found qualified matching constraint.
  • ira-simple-lra-insn-threshold โ€” approximate function insn number in 1K units that triggers simple local RA.
  • lra-inheritance-ebb-probability-cutoff โ€” LRA tries to reuse values reloaded in registers in subsequent insns. That optimization is called inheritance. EBB is used as the region to do it in. This parameter defines the minimal fall-through edge probability, in percentage, used to add a BB to inheritance EBB in LRA. The default value was chosen from numerous runs of SPEC2000 on x86-64. Very "we tested this so you don't have to" of them ๐Ÿซถ
  • loop-invariant-max-bbs-in-loop โ€” loop invariant motion can get super expensive, both in compilation time and in the amount of compile-time memory needed, with very large loops. Loops with more basic blocks than this parameter won't have loop invariant motion optimization performed on them.
  • loop-max-datarefs-for-datadeps โ€” building data dependencies is expensive for very large loops. This parameter limits the number of data references in loops that get considered for data dependence analysis. These large loops aren't handled by the optimizations that use loop data dependencies. ๐ŸŒธ

  • max-vartrack-size โ€” this one's the cap on how many hash table slots the variable tracking dataflow analysis is allowed to use for any function ๐ŸŽ€. If the limit gets blown while variable tracking at assignments is on, the analysis for that function gets retried without it โ€” after all the debug insns are yeeted from the function ๐Ÿ™ˆ. And if it still gets exceeded even with no debug insns around? Then var tracking analysis is just completely disabled for that function, periodt. Setting this parameter to zero makes it unlimited ๐Ÿ’ซ.
  • max-vartrack-expr-depth โ€” sets the max number of recursion levels when the compiler tries to map variable names or debug temporaries onto value expressions ๐Ÿงš. It's a straight-up trade: compilation time vs. more complete debug info. Set it too low and value expressions that are available and could be represented in debug info may end up not being used ๐Ÿ˜ญ. Set it higher and the compiler might find way more complex debug expressions โ€” but compile time and memory use may grow ๐Ÿ“ˆ.
  • max-debug-marker-count โ€” a threshold on the number of debug markers (think begin stmt markers) so we don't get a complexity explosion at inlining or when expanding to RTL ๐Ÿ’€. If a function has more such gimple stmts than the set limit, those stmts get dropped from the inlined copy of the function, and from its RTL expansion too.
  • min-nondebug-insn-uid โ€” nondebug insns get uids starting at this parameter โœจ. Everything below it is reserved exclusively for debug insns created by -fvar-tracking-assignments โ€” though debug insns may get (non-overlapping) uids above it if the reserved range runs out ๐Ÿ‘‘.
  • ipa-sra-deref-prob-threshold โ€” IPA-SRA only swaps a pointer that's known to not be NULL for one or more new parameters 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 only replaces a pointer to an aggregate with one or more new parameters when their cumulative size is less than or equal to ipa-sra-ptr-growth-factor times the size of the original pointer parameter ๐ŸŒธ.
  • ipa-sra-ptrwrap-growth-factor โ€” extra maximum allowed growth of the total size of those new parameters that IPA-SRA replaces a pointer-to-an-aggregate with, in the case where it points to a local variable that the caller only writes to and passes as an argument to other functions ๐Ÿ’….
  • ipa-sra-max-replacements โ€” the max pieces of an aggregate that IPA-SRA tracks ๐Ÿ”ฅ. Which consequently also makes it the maximum number of replacements of a formal parameter.
  • sra-max-scalarization-size-Ospeed, sra-max-scalarization-size-Osize โ€” okay so the two Scalar Reduction of Aggregates passes (SRA and IPA-SRA) are out here trying to replace scalar parts of aggregates with uses of independent scalar variables ๐Ÿซถ. These parameters control the maximum size, in storage units, of an aggregate that gets considered for replacement when you're compiling for speed (sra-max-scalarization-size-Ospeed) or for size (sra-max-scalarization-size-Osize) respectively.
  • sra-max-propagations โ€” the max number of artificial accesses that Scalar Replacement of Aggregates (SRA) will track, per one local variable, to help copy propagation along ๐Ÿ’œ.
  • tm-max-aggregate-size โ€” when making copies of thread-local variables inside a transaction, this parameter sets the size in bytes after which variables get saved with the logging functions instead of save/restore code sequence pairs ๐ŸŒˆ. Only applies when you're using -fgnu-tm, iykyk.
  • graphite-max-nb-scop-params โ€” to dodge exponential effects in the Graphite loop transforms, the number of parameters in a Static Control Part (SCoP) is bounded โญ. A value of zero lifts the bound entirely. And btw, a variable whose value is unknown at compilation time and defined outside a SCoP counts as 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 ๐Ÿฆ‹. You change the strip length with the loop-block-tile-size parameter.
  • ipa-jump-function-lookups โ€” specifies the number of statements visited during jump function offset discovery ๐Ÿ”.
  • ipa-cp-value-list-size โ€” IPA-CP tries to track all possible values and types passed to a function's parameter so it can propagate them and do devirtualization ๐Ÿ’ซ. ipa-cp-value-list-size is the max 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 only performs those cloning opportunities whose scores exceed ipa-cp-eval-threshold ๐Ÿ‘‘.
  • ipa-cp-max-recursive-depth โ€” max depth of recursive cloning for a self-recursive function ๐ŸŒ€.
  • ipa-cp-min-recursive-probability โ€” recursive cloning happens only when the probability of the call being executed exceeds the parameter โœจ.
  • ipa-cp-profile-count-base โ€” when you're using -fprofile-use, 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 โ€” the percentage penalty recursive functions receive when they're evaluated for cloning ๐Ÿ’€.
  • ipa-cp-single-call-penalty โ€” the percentage penalty that functions containing a single call to another function receive when they're evaluated for cloning ๐Ÿ™ˆ.
  • ipa-max-agg-items โ€” IPA-CP is also capable of propagating 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 figures out that a cloning candidate would make the number of iterations of a loop known, it adds a bonus of ipa-cp-loop-hint-bonus to the profitability score of that candidate ๐ŸŽ.
  • ipa-max-loop-predicates โ€” the max 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 to track values pointed to by function parameters ๐Ÿ‘€. But so it doesn't spend forever analyzing huge functions, it gives up and considers all memory clobbered after examining ipa-max-aa-steps statements that modify memory ๐Ÿ’….
  • ipa-max-switch-predicate-bounds โ€” maximal number of boundary endpoints of case ranges of a switch statement ๐ŸŽ€. For a switch that exceeds this limit, IPA-CP will not construct the cloning cost predicate โ€” the thing used to estimate cloning benefit โ€” for the default case of the switch statement.
  • ipa-max-param-expr-ops โ€” IPA-CP will analyze a conditional statement that references some function parameter to estimate the benefit of cloning upon a certain constant value ๐Ÿ”ฅ. But if the number of operations in a parameter expression exceeds ipa-max-param-expr-ops, the expression gets treated as a complicated one, and IPA analysis doesn't handle it.
  • lto-partitions โ€” specify the desired number of partitions produced during WHOPR compilation ๐Ÿงฉ. The number of partitions should exceed the number of CPUs used for compilation.
  • lto-min-partition โ€” size of the minimal partition for WHOPR (in estimated instructions) ๐Ÿ“. This prevents the expense of splitting very small programs into way too many partitions.
  • lto-max-partition โ€” size of the max partition for WHOPR (in estimated instructions), to provide an upper bound for the individual size of a partition ๐Ÿซถ. Meant to be used only with balanced partitioning.
  • lto-max-streaming-parallelism โ€” maximal number of parallel processes used for LTO streaming ๐Ÿš€.
  • cxx-max-namespaces-for-diagnostic-help โ€” the max 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 that still allows statement sinking of a statement ๐ŸŒŠ. Larger numbers result in more aggressive statement sinking. A small positive adjustment is applied for statements with memory operands, since those are even more profitable to sink.
  • max-stores-to-sink โ€” the max number of conditional store pairs that can be sunk ๐Ÿ“ฆ. Set it to 0 if either vectorization (-ftree-vectorize) or if-conversion (-ftree-loop-if-convert) is disabled.
  • case-values-threshold โ€” the smallest number of different values for which it's best to use a jump-table instead of a tree of conditional branches ๐ŸŽฏ. If the value is 0, use the default for the machine.
  • jump-table-max-growth-ratio-for-size โ€” the maximum code size growth ratio when expanding into a jump table (in percent) ๐Ÿ“. This 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) โšก. This parameter is used when optimizing for speed.
  • tree-reassoc-width โ€” set the maximum number of instructions executed in parallel in a reassociated tree ๐ŸŒ€. This parameter overrides target dependent heuristics used by default if it has a non zero value.
  • sched-pressure-algorithm โ€” picks which of the two implementations of -fsched-pressure you get. Algorithm 1 is the OG, and it's the one more likely to stop instructions from getting reordered. Algorithm 2 was designed as a compromise between algorithm 1's kinda-conservative vibe and the default scheduler's full-send aggressive energy. It leans way harder on having a regular register file and accurate register pressure classes. More deets live in haifa-sched.cc in the GCC sources if you're that girl. Default choice? Depends on the target, bestie. ๐Ÿ’…
  • max-slsr-cand-scan โ€” sets the max number of existing candidates that get considered when hunting for a basis for a new straight-line strength reduction candidate.
  • asan-globals โ€” turns on buffer overflow detection for global objects. It's on by default if you're using -fsanitize=address. Wanna yeet global objects protection? --param asan-globals=0. โœจ
  • asan-stack โ€” buffer overflow detection for stack objects, on by default with -fsanitize=address. Kill stack protection with --param asan-stack=0.
  • asan-instrument-reads โ€” buffer overflow detection for memory reads. On by default with -fsanitize=address; disable with --param asan-instrument-reads=0.
  • asan-instrument-writes โ€” buffer overflow detection for memory writes. On by default with -fsanitize=address; disable with --param asan-instrument-writes=0.
  • asan-memintrin โ€” detection for built-in functions, on by default with -fsanitize=address. Turn it off with --param asan-memintrin=0.
  • asan-use-after-return โ€” detection of use-after-return, on by default when you use -fsanitize=address. Disable with --param asan-use-after-return=0.
โš ๏ธ Note, bestie: by default the check is disabled at run time. To actually enable it, add "detect_stack_use_after_return=1" to the environment variable ASAN_OPTIONS. Don't forget this part, iykyk ๐Ÿ’€
  • asan-instrumentation-with-call-threshold โ€” if the number of memory accesses in the function being instrumented is greater or equal to this number, it uses callbacks instead of inline checks. E.g. to disable inline code use --param asan-instrumentation-with-call-threshold=0.
  • asan-kernel-mem-intrinsic-prefix โ€” if nonzero, prefixes calls to memcpy, memset and memmove with __asan_ or __hwasan_ for -fsanitize=kernel-address or -fsanitize=kernel-hwaddress, respectively.
  • hwasan-instrument-stack โ€” enables hwasan instrumentation of statically sized stack-allocated variables. On by default with -fsanitize=hwaddress, off by default with -fsanitize=kernel-hwaddress. Disable stack instrumentation with --param hwasan-instrument-stack=0, enable it with --param hwasan-instrument-stack=1. ๐ŸŽ€
  • hwasan-random-frame-tag โ€” when using stack instrumentation, decides tags for stack variables using a deterministic sequence beginning at a random tag for each frame. With this parameter unset, tags are chosen using the same sequence but beginning from 1. Enabled by default for -fsanitize=hwaddress and unavailable for -fsanitize=kernel-hwaddress. Disable with --param hwasan-random-frame-tag=0.
  • hwasan-instrument-allocas โ€” enables hwasan instrumentation of dynamically sized stack-allocated variables. On by default with -fsanitize=hwaddress, off by default with -fsanitize=kernel-hwaddress. Disable instrumentation of such variables with --param hwasan-instrument-allocas=0, enable it with --param hwasan-instrument-allocas=1.
  • hwasan-instrument-reads โ€” enables hwasan checks on memory reads. Instrumentation of reads is on by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. Disable with --param hwasan-instrument-reads=0.
  • hwasan-instrument-writes โ€” enables hwasan checks on memory writes. On by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. Disable with --param hwasan-instrument-writes=0.
  • hwasan-instrument-mem-intrinsics โ€” enables hwasan instrumentation of builtin functions. On by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. Disable with --param hwasan-instrument-mem-intrinsics=0.
  • use-after-scope-direct-emission-threshold โ€” if the size of a local variable in bytes is smaller or equal to this number, it directly poisons (or unpoisons) 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 โ€” chunk size of omp schedule for loops parallelized by parloops.
  • parloops-schedule โ€” 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. Note that for a parallelized loop nest, the minimum number of iterations of the outermost loop per thread is two.
  • max-ssa-name-query-depth โ€” maximum depth of recursion when querying properties of SSA names in things like fold routines. One level of recursion corresponds to following a use-def chain.
  • max-speculative-devirt-maydefs โ€” the maximum number of may-defs we analyze when looking for a must-def specifying the dynamic type of an object that invokes a virtual call we may be able to devirtualize speculatively.
  • evrp-sparse-threshold โ€” maximum 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 maximum 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 maximum number of times the outer loop should be unrolled by the unroll-and-jam transformation.
  • max-rtl-if-conversion-unpredictable-cost โ€” maximum permissible cost for the sequence that would be generated by the RTL if-conversion pass for a branch that is considered unpredictable.
  • max-variable-expansions-in-unroller โ€” if -fvariable-expansion-in-unroller is used, the maximum number of times that an individual variable will be expanded during loop unrolling.
  • partial-inlining-entry-probability โ€” maximum probability of the entry BB of split region (in percent relative to entry BB of the function) to make partial inlining happen.
  • max-tracked-strlens โ€” maximum number of strings for which 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 permit performing redundancy elimination after reload.
  • max-loop-header-insns โ€” the maximum number of insns in loop header duplicated by the copy loop headers pass.
  • vect-epilogues-nomask โ€” enable loop epilogue vectorization using smaller vector size. ๐Ÿฆ‹
  • vect-partial-vector-usage โ€” controls when the loop vectorizer considers using partial vector loads and stores as an alternative to falling back to scalar code. 0 stops the vectorizer from ever using partial vector loads and stores. 1 allows partial vector loads and stores if vectorization removes the need for the code to iterate. 2 allows partial vector loads and stores in all loops. The parameter only has an effect on targets that support partial vector loads and stores.
  • vect-inner-loop-cost-factor โ€” the maximum factor which the loop vectorizer applies to the cost of statements in an inner loop relative to the loop being vectorized. The factor applied is the maximum of the estimated number of iterations of the inner loop and this parameter. The default value of this parameter is 50.
  • vect-induction-float โ€” enable loop vectorization of floating point inductions.
  • avoid-fma-max-bits โ€” maximum number of bits for which we avoid creating FMAs.
  • sms-loop-average-count-threshold โ€” a threshold on the average loop count considered by the swing modulo scheduler.
  • 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 swing modulo scheduler uses for scheduling a loop. ๐Ÿ”ฅ
  • lra-max-considered-reload-pseudos โ€” the max number of reload pseudos that get considered while we're spilling a non-reload pseudo ๐Ÿ’…
  • max-pow-sqrt-depth โ€” maximum depth of sqrt chains to use when synthesizing exponentiation by a real constant ๐Ÿ”ฅ
  • max-dse-active-local-stores โ€” maximum number of active local stores in RTL dead store elimination, no cap fr
  • asan-instrument-allocas โ€” turns on asan allocas/VLAs protection โœจ
  • max-iterations-computation-cost โ€” the bound on the cost of an expression to compute the number of iterations
  • max-isl-operations โ€” maximum number of isl operations, and 0 means unlimited ๐Ÿฆ‹
  • graphite-max-arrays-per-scop โ€” maximum number of arrays per scop
  • max-vartrack-reverse-op-size โ€” max size of loc list for which reverse ops should be added
  • fsm-scale-path-stmts โ€” scale factor to apply to the number of statements in a threading path crossing a loop backedge, when comparing against --param=max-jump-thread-duplication-stmts
  • uninit-control-dep-attempts โ€” maximum number of nested calls to search for control dependencies during uninitialized variable analysis
  • uninit-max-chain-len โ€” maximum number of predicates anded for each predicate ored in the normalized predicate chain
  • uninit-max-num-chains โ€” maximum number of predicates ored in the normalized predicate chain
  • sched-autopref-queue-depth โ€” hardware autoprefetcher scheduler model control flag ๐Ÿ‘‘ number of lookahead cycles the model looks into; at ' ' only enable instruction sorting heuristic
  • loop-versioning-max-inner-insns โ€” the maximum number of instructions an inner loop can have before the loop versioning pass decides it's too big to copy
  • loop-versioning-max-outer-insns โ€” the maximum number of instructions an outer loop can have before the loop versioning pass decides it's too big to copy, discounting any instructions in inner loops that directly benefit from versioning
  • ssa-name-def-chain-limit โ€” the maximum number of SSA_NAME assignments to follow when determining a property of a variable, like its value. This caps the number of iterations or recursive calls GCC does when optimizing certain statements, or when determining their validity before issuing 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 inside the analyzer, before it terminates analysis of that point ๐Ÿ’€
  • analyzer-max-constraints โ€” the maximum number of constraints per state
  • analyzer-min-snodes-for-call-summary โ€” the minimum number of supernodes within a function for the analyzer to 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 terminates analysis of 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 that 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 terminating analysis
  • 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 are decomposed into parts โ€” a sequence of compute constructs, each then handled individually. This one's work in progress, heads up ๐Ÿšง With --param=openacc-kernels=parloops, OpenACC kernels constructs are handled by the parloops pass, en bloc. And that's 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 (and that's the current default). With --param=openacc-privatization=noisy, do diagnose ๐Ÿ—ฃ๏ธ

The following choices of name are available on AArch64 targets, bestie ๐ŸŽ€

  • aarch64-sve-compare-costs โ€” when vectorizing for SVE, consider using "unpacked" vectors for smaller elements and let the cost model 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. 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. Default value is 2.
  • 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 figure out whether unrolling the main vectorized loop would be beneficial, and by how much. This parameter set's the upper bound of how much the vectorizer will unroll the main loop. Default value is four.

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 gets aborted ๐Ÿ’€

๐ŸŽ€ Program Instrumentation Options ๐ŸŽ€

GCC supports a bunch of command-line options that control adding run-time instrumentation to the code it normally generates. Like, one purpose of instrumentation is collecting profiling statistics so you can find program hot spots, do code coverage analysis, or run profile-guided optimizations โœจ Another class of program instrumentation is adding run-time checking to detect programming errors like invalid pointer dereferences or out-of-bounds array accesses โ€” plus deliberately hostile attacks such as stack smashing or C++ vtable hijacking ๐Ÿ˜ค There's also a general hook you can use to implement other forms of tracing or function-level instrumentation, for debug or program analysis purposes. iykyk.

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

You can use the function attribute no_instrument_function to suppress profiling of individual functions when compiling with these options ๐Ÿ™ˆ

  • -fprofile-arcs โ€” add code so that program flow arcs are instrumented. During execution the program records how many times each branch and call is executed and how many times it is taken or returns ๐Ÿ“Š On targets that support constructors with priority support, profiling properly handles constructors, destructors and C++ constructors (and destructors) of classes which are used as a type of a global variable.

When the compiled program exits it saves this data to a file called auxname.gcda for each source file ๐Ÿ’พ The data may be used for profile-directed optimizations (-fbranch-probabilities), or for test coverage analysis (-ftest-coverage). Each object file's auxname is generated from the name of the output file, if explicitly specified and it's not the final executable โ€” otherwise it's the basename of the source file. In both cases any suffix is removed (e.g. foo.gcda for input file dir/foo.c, or dir/foo.gcda for output file specified as -o dir/foo.o) ๐Ÿซถ

๐Ÿ’ก ok bestie, tiny note first: if a command line directly links source files, the corresponding .gcda files get prefixed with the unsuffixed name of the output file. E.g. gcc a.c b.c -o binary would generate binary-a.gcda and binary-b.gcda files. no cap.

  • --coverage โ€” this one is for compiling and linking code thatโ€™s instrumented for coverage analysis. Itโ€™s literally a synonym for -fprofile-arcs -ftest-coverage when compiling, and -lgcov when linking. See those optionsโ€™ docs for the full tea. ๐Ÿซถ
    • Compile the source files with -fprofile-arcs plus optimization and code generation options. For test coverage analysis, use the additional -ftest-coverage option. You do not need to profile every source file in a program.
    • Compile the source files additionally with -fprofile-abs-path to create absolute path names in the .gcno files. This lets gcov find the correct sources in projects where compilations happen with different working directories.
    • Link your object files with -lgcov or -fprofile-arcs (the latter implies the former).
    • Run the program on a representative workload to generate the arc profile information. This may be repeated any number of times. You can run concurrent instances of your program, and provided that the file system supports locking, the data files will be correctly updated. Unless a strict ISO C dialect option is in effect, fork calls are detected and correctly handled without double counting.

Moreover, an object file can be recompiled multiple times and the corresponding .gcda file merges as long as the source file and the compiler options are unchanged.

  • For profile-directed optimizations, compile the source files again with the same optimization and code generation options plus -fbranch-probabilities.
  • For test coverage analysis, use gcov to produce human readable information from the .gcno and .gcda files. Refer to the gcov documentation for further information.

With -fprofile-arcs, for each function of your program GCC creates a program flow graph, then finds a spanning tree for the graph. Only arcs that are not on the spanning tree have to be instrumented: the compiler adds code to count the number of times that these arcs are executed. When an arc is the only exit or only entrance to a block, the instrumentation code can be added to the block; otherwise, a new basic block must be created to hold the instrumentation code. slay, honestly. ๐Ÿ’…

  • -ftest-coverage โ€” produce a notes file that the gcov code-coverage utility can use to show program coverage. Each source fileโ€™s note file is called auxname.gcno. Refer to the -fprofile-arcs option above for a description of auxname and instructions on how to generate test coverage data. Coverage data matches the source files more closely if you do not optimize. โœจ
  • -fprofile-abs-path โ€” automatically convert relative source file names to absolute path names in the .gcno files. This allows gcov to find the correct sources in projects where compilations occur with different working directories. ๐ŸŽ€
  • -fprofile-dir=path โ€” set the directory to search for the profile data files in to path. This option affects only the profile data generated by -fprofile-generate, -ftest-coverage, -fprofile-arcs and used by -fprofile-use and -fbranch-probabilities and its related options. Both absolute and relative paths can be used. By default, GCC uses the current directory as path, thus the profile data file appears in the same directory as the object file. In order to prevent the file name clashing, if the object file name is not an absolute path, we mangle the absolute path of the sourcename.gcda file and use it as the file name of a .gcda file. See 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 โ€” enable options usually used for instrumenting application to produce profile useful for later recompilation with profile feedback based optimization. You must use -fprofile-generate both when compiling and when linking your program. ๐Ÿ”ฅ

The following options are enabled: -fprofile-arcs, -fprofile-values, -finline-functions, and -fipa-bit-cp.

If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.

To optimize the program based on the collected profile information, use -fprofile-use. ๐Ÿ‘‘

  • -fprofile-info-section, -fprofile-info-section=name โ€” register the profile information in the specified section instead of using a constructor/destructor. The section name is name if it is specified, otherwise the section name defaults to .gcov_info. A pointer to the profile information generated by -fprofile-arcs 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. bestie, donโ€™t say I didnโ€™t warn you. ๐Ÿ’€
  • -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 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 โ€” alter 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. ๐Ÿ™ˆ

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

  • -fprofile-exclude-files=regex โ€” instrument only functions from files whose name does not match any of the regular expressions (separated by semi-colons). ๐ŸŒˆ

For example, -fprofile-exclude-files=/usr/.* will prevent instrumentation of all files that are located in the /usr/ folder. periodt. ๐Ÿ’…

  • -fprofile-reproducible=[multithreaded|parallel-runs|serial] โ€” bestie, this one controls how reproducible the profile is that -fprofile-generate gathers ๐ŸŽ€. Why do we care? Because it lets you rebuild the program with the same outcome, which is lowkey a whole thing for stuff like distribution packages.

With -fprofile-reproducible=serial, the profile gathered by -fprofile-generate is reproducible provided the trained program behaves the same at each invocation of the train run, it is not multi-threaded, and profile data streaming is always done in the same order. Small note: profile streaming happens at the end of the program run but also before the fork function is invoked ๐Ÿ‘€.

Also be aware it's quite common that execution counts of some part of programs depend on stuff like the length of temporary file names or memory space randomization (which may affect hash-table collision rate). Such non-reproducible parts of programs may be annotated by the no_instrument_function function attribute โœจ. And gcov-dump with -l can be used to dump gathered data and verify that they are indeed reproducible, slay.

With -fprofile-reproducible=parallel-runs, the collected profile stays reproducible regardless of the order of streaming of the data into gcda files. This setting makes it possible to run multiple instances of the instrumented program in parallel (like with make -j). Trade-off though: it reduces the quality of gathered data, in particular of indirect call profiling ๐Ÿ’….

  • -fsanitize=address โ€” enables AddressSanitizer, a fast memory error detector ๐Ÿ”ฅ. Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. This option enables -fsanitize-address-use-after-scope. More deets at <https://github.com/google/sanitizers/wiki/AddressSanitizer>. The run-time behavior can be influenced using the ASAN_OPTIONS environment variable โ€” when it's set to help=1, the available options are shown at startup of the instrumented program. Full list of supported options lives at <https://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flags>. The option cannot be combined with -fsanitize=thread or -fsanitize=hwaddress. And note: the only targets -fsanitize=hwaddress is currently supported on are x86-64 (only with -mlam=u48 or -mlam=u57 options) and AArch64 โ€” and in both cases only in ABIs with 64-bit pointers.

To get more accurate stack traces, you can use options such as -O0, -O1, or -Og (which, for instance, prevent most function inlining), -fno-optimize-sibling-calls (which prevents optimizing sibling and tail recursive calls; this option is implicit for -O0, -O1, or -Og), or -fno-ipa-icf (which disables Identical Code Folding for functions). And since multiple runs of the program may yield backtraces with different addresses due to ASLR (Address Space Layout Randomization), it may be desirable to turn ASLR off โ€” on Linux, this can be achieved with:

setarch `uname -m` -R ./prog
  • -fsanitize=kernel-address โ€” enables AddressSanitizer for the Linux kernel ๐Ÿง. More at <https://github.com/google/kernel-sanitizers>.
  • -fsanitize=hwaddress โ€” enables Hardware-assisted AddressSanitizer, which uses a hardware ability to ignore the top byte of a pointer so it can detect memory errors with a low memory overhead โœจ. Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. The option enables -fsanitize-address-use-after-scope. More at <https://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html>. The run-time behavior can be influenced using the HWASAN_OPTIONS environment variable โ€” set to help=1, and the available options are shown at startup of the instrumented program. This option cannot be combined with -fsanitize=thread or -fsanitize=address, and is currently only available on AArch64 ๐Ÿ’….
  • -fsanitize=kernel-hwaddress โ€” enables Hardware-assisted AddressSanitizer for compilation of the Linux kernel ๐Ÿง. Similar to -fsanitize=kernel-address but using an alternate instrumentation method, and similar to -fsanitize=hwaddress but with instrumentation differences necessary for compiling the Linux kernel. Those differences exist to avoid hwasan library initialization calls and to account for the stack pointer having a different value in its top byte.
Heads up: this option has different defaults to -fsanitize=hwaddress. Instrumenting the stack and alloca calls are not on by default, but are still possible by specifying the command-line options --param hwasan-instrument-stack=1 and --param hwasan-instrument-allocas=1 respectively. Using a random frame tag is not implemented for kernel instrumentation.
  • -fsanitize=pointer-compare โ€” instruments comparison operation (<, <=, >, >=) with pointer operands ๐Ÿฆ‹. The option must be combined with either -fsanitize=kernel-address or -fsanitize=address. The option cannot be combined with -fsanitize=thread. Note: by default the check is disabled at run time โ€” to enable it, add detect_invalid_pointer_pairs=2 to the environment variable ASAN_OPTIONS. Using detect_invalid_pointer_pairs=1 detects an invalid operation only when both pointers are non-null ๐Ÿ‘€.
  • -fsanitize=pointer-subtract โ€” instruments subtraction with pointer operands ๐ŸŒธ. The option must be combined with either -fsanitize=kernel-address or -fsanitize=address. The option cannot be combined with -fsanitize=thread. Note: by default the check is disabled at run time โ€” to enable it, add detect_invalid_pointer_pairs=2 to the environment variable ASAN_OPTIONS. Using detect_invalid_pointer_pairs=1 detects an invalid operation only when both pointers are non-null ๐Ÿซถ.
  • -fsanitize=shadow-call-stack โ€” enables ShadowCallStack, a security enhancement mechanism used to protect programs against return address overwrites (e.g. stack buffer overflows) ๐Ÿ‘‘. It works by saving a function's return address to a separately allocated shadow call stack in the function prologue, then restoring the return address from the shadow call stack in the function epilogue. Instrumentation only occurs in functions that need to save the return address to the stack.

Currently it only supports the aarch64 platform. It's specifically designed for Linux kernels that enable the CONFIG_SHADOW_CALL_STACK option. For user space programs, runtime support is not currently provided in libc and libgcc ๐Ÿ˜ญ โ€” so if you wanna use this feature in user space, you need to provide your own runtime support. And it should be noted that this may cause the ABI rules to be broken.

On aarch64, the instrumentation makes use of the platform register x18. This generally means that any code that may run on the same thread as code compiled with ShadowCallStack must be compiled with the flag -ffixed-x18 โ€” otherwise functions compiled without -ffixed-x18 might clobber x18 and so corrupt the shadow stack pointer ๐Ÿ’€.

Also, because there's no userspace runtime support, code compiled with ShadowCallStack cannot use exception handling. Use -fno-exceptions to turn off exceptions.

See <https://clang.llvm.org/docs/ShadowCallStack.html> for more details.

Note: sanitized atomic builtins cannot throw exceptions when operating on invalid memory addresses with non-call exceptions (-fnon-call-exceptions).
  • -fsanitize=leak โ€” enables LeakSanitizer, a memory leak detector ๐Ÿš. This option only matters for linking of executables โ€” the executable gets linked against a library that overrides malloc and other allocator functions. More at <https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer>. The run-time behavior can be influenced using the LSAN_OPTIONS environment variable. The option cannot be combined with -fsanitize=thread.
  • -fsanitize=undefined โ€” enables UndefinedBehaviorSanitizer, a fast undefined behavior detector โœจ. Various computations are instrumented to detect undefined behavior at runtime. More at <https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html>. The run-time behavior can be influenced using the UBSAN_OPTIONS environment variable. Current suboptions are:
    • -fsanitize=shift โ€” this option enables checking that the result of a shift operation is not undefined ๐ŸŒ€. Note that what exactly is considered undefined differs slightly between C and C++, as well as between ISO C90 and C99, etc. This option has two suboptions: -fsanitize=shift-base and -fsanitize=shift-exponent.
    • -fsanitize=shift-exponent โ€” this option enables checking that the second argument of a shift operation is not negative and is smaller than the precision of the promoted first argument ๐Ÿ’….
    • -fsanitize=shift-base โ€” if the second argument of a shift operation is within range, check that the result of a shift operation is not undefined ๐Ÿฆ‹. Note that what exactly is considered undefined differs slightly between C and C++, as well as between ISO C90 and C99, etc.
    • -fsanitize=integer-divide-by-zero โ€” detects integer division by zero ๐Ÿ˜ค.
    • -fsanitize=unreachable โ€” with this option, the compiler turns the __builtin_unreachable call into a diagnostics message call instead. When reaching the __builtin_unreachable call, the behavior is undefined ๐Ÿ’€.
    • -fsanitize=vla-bound โ€” this option instructs the compiler to check that the size of a variable length array is positive ๐ŸŒธ.
    • -fsanitize=null โ€” this option enables pointer checking ๐Ÿ‘‘. Particularly, the 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 by a NULL pointer.
  • -fsanitize=return โ€” this one's the return-statement bouncer ๐Ÿ’…. Programs built with it will throw an error message the moment the end of a non-void function gets reached without actually returning a value. C++ only, bestie โ€” don't come looking for it in C.
  • -fsanitize=signed-integer-overflow โ€” signed integer overflow checking, bestie! We check that the result of +, *, and both unary and binary - doesn't overflow in signed arithmetics. It also catches INT_MIN / -1 signed division ๐Ÿ”ฅ. Note tho: integer promotion rules must be taken into account. Which means this is not an overflow:
signed char a = SCHAR_MAX;
a++;
  • -fsanitize=bounds โ€” instruments array bounds, so various out-of-bounds accesses get detected ๐Ÿ‘€. Not instrumented: flexible array members, flexible array member-like arrays, and initializers of variables with static storage โ€” the one exception being flexible array member-like arrays for which the -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. Ik, that's a mouthful, but it's exactly what it says ๐Ÿ’€.
  • -fsanitize=bounds-strict โ€” strict instrumentation of array bounds. Most out-of-bounds accesses get detected, including flexible array member-like arrays. Initializers of variables with static storage are not instrumented.
  • -fsanitize=alignment โ€” checks the alignment of pointers when they get dereferenced, or when a reference is bound to an insufficiently aligned target, or when a method or constructor is invoked on an insufficiently aligned object ๐ŸŽฏ.
  • -fsanitize=object-size โ€” instruments memory references using the __builtin_dynamic_object_size function, so various out-of-bounds pointer accesses get detected.
  • -fsanitize=float-divide-by-zero โ€” detects floating-point division by zero. And unlike the other similar options, this one is not enabled by -fsanitize=undefined, because floating-point division by zero can legitimately be how you obtain infinities and NaNs ๐ŸŒˆ. Divas have range, okay?
  • -fsanitize=float-cast-overflow โ€” floating-point type to integer conversion checking. We check the result of the conversion doesn't overflow. Unlike other similar options, -fsanitize=float-cast-overflow is not enabled by -fsanitize=undefined. Also this option does not work well with FE_INVALID exceptions enabled ๐Ÿ™ˆ.
  • -fsanitize=nonnull-attribute โ€” instruments calls, checking whether null values are not passed to arguments marked as requiring a non-null value by the nonnull function attribute ๐Ÿšซ.
  • -fsanitize=returns-nonnull-attribute โ€” instruments return statements in functions marked with the returns_nonnull function attribute, to detect returning null values from those functions. no cap, don't return null from a nonnull function.
  • -fsanitize=bool โ€” instruments loads from bool. If a value other than 0/1 gets loaded, a run-time error is issued. That's it. That's the whole vibe check โœจ.
  • -fsanitize=enum โ€” instruments loads from an enum type. If a value outside the range of values for the enum type gets 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 only, fr fr ๐Ÿ’œ.
  • -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 gets passed to those 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 ๐Ÿ‘€.
Heads up bestie ๐Ÿซถ: 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. Like, don't do it, it's giving chaos.

Also while -ftrapv causes traps for signed overflows to be emitted, -fsanitize=undefined gives a diagnostic message instead. This currently works only for the C family of languages.


  • -fno-sanitize=all โ€” disables all previously enabled sanitizers. And no, -fsanitize=all is not allowed, because some sanitizers cannot be used together ๐Ÿ’€. It's giving exclusive friend group.
  • -fasan-shadow-offset=number โ€” forces GCC to use a custom shadow offset in AddressSanitizer checks. Useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer ๐Ÿงš.
  • -fsanitize-sections=s1,s2,... โ€” sanitize global variables in selected user-defined sections. si may contain wildcards. cute and targeted โœจ.
  • -fsanitize-recover[=opts] โ€” -fsanitize-recover= controls error recovery mode for the sanitizers mentioned in the comma-separated list of opts. Enabling this option for a sanitizer component causes it to attempt to continue running the program as if no error happened. Which means multiple runtime errors can be reported in a single program run, and the exit code of the program may indicate success even when errors have been reported ๐Ÿ˜ญ. The -fno-sanitize-recover= option can be used to alter this behavior: only the first detected error is reported and 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 are also accepted โ€” the former enables recovery for all sanitizers that support it, the latter disables recovery for all sanitizers that support it.

Even if 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 โ€” enables sanitization of local variables to detect use-after-scope bugs. The option sets -fstack-reuse to none. obsessed with the thoroughness ๐ŸŽ€.
  • -fsanitize-trap[=opts] โ€” 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? The libubsan library is not needed and is not linked in, so this is usable even in freestanding environments. slay ๐Ÿ’….

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 also be 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 โ€” and -fsanitize-trap=vptr is not allowed ๐Ÿ™….

  • -fsanitize-undefined-trap-on-error โ€” deprecated equivalent of -fsanitize-trap=all. old news, bestie, but it's still here ๐ŸŒธ.
  • -fsanitize-coverage=trace-pc โ€” enables coverage-guided fuzzing code instrumentation. Inserts a call to __sanitizer_cov_trace_pc into every basic block ๐Ÿ‘‘.
  • -fsanitize-coverage=trace-cmp โ€” enables dataflow guided fuzzing code instrumentation. Inserts a call to __sanitizer_cov_trace_cmp1, __sanitizer_cov_trace_cmp2, __sanitizer_cov_trace_cmp4 or __sanitizer_cov_trace_cmp8 for integral comparison with both operands variable, or __sanitizer_cov_trace_const_cmp1, __sanitizer_cov_trace_const_cmp2, __sanitizer_cov_trace_const_cmp4 or __sanitizer_cov_trace_const_cmp8 for integral comparison with one operand constant, __sanitizer_cov_trace_cmpf or __sanitizer_cov_trace_cmpd for float or double comparisons, and __sanitizer_cov_trace_switch for switch statements. the way it has a function for every comparisonโ€ฆ meticulous queen ๐Ÿงš.
  • -fcf-protection=[full|branch|return|none|check] โ€” enables code instrumentation of control-flow transfers to increase program security by checking that target addresses of control-flow transfer instructions (such as indirect function call, function return, indirect jump) are valid ๐Ÿ›ก๏ธ. This prevents diverting the flow of control to an unexpected target. It's intended to protect against threats like Return-oriented Programming (ROP), and similarly call/jmp-oriented programming (COP/JOP). literally the bodyguard of your control flow, ngl.

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

The value "check" is for that final link step with link-time optimization (LTO) ๐Ÿ’… โ€” if your LTO object files got compiled with different -fcf-protection values, it throws an error at you. And at compile time? The "check" value is just ignored, like it's not even there ๐Ÿ™ˆ.

The macro __CET__ gets defined whenever you use -fcf-protection. First bit of __CET__ = 1 for the value "branch", second bit = 1 for the "return" โœจ.

You can also slap the "nocf_check" attribute on stuff to mark which functions and calls should get skipped from instrumentation, super handy ๐Ÿซถ.

Currently the x86 GNU/Linux target is the one serving us an implementation based on Intel Control-flow Enforcement Technology (CET), and it works for i686 processor or newer ๐Ÿ‘‘.


  • -fharden-compares โ€” for every logical test that survives gimple optimizations and isn't the condition in a conditional branch (think: conditions tested for conditional moves, or ones stored in boolean variables), it emits extra code to compute and verify the reversed condition, and calls "__builtin_trap" if the results don't match ๐Ÿ˜ญ. Pair it with -fharden-conditional-branches to cover absolutely all the conditionals, no gaps.
  • -fharden-conditional-branches โ€” for every non-vectorized conditional branch that survives gimple optimizations, it emits extra code to compute and verify the reversed condition, and calls "__builtin_trap" if the result is unexpected ๐Ÿ’€. Bestie, use it with -fharden-compares so all your conditionals are covered.
  • -fstack-protector โ€” emits extra code to check for buffer overflows, like those stack smashing attacks ๐Ÿ˜ค. How? By adding a guard variable to functions with vulnerable objects โ€” and that includes 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. If a guard check fails, an error message is printed and the program exits, periodt ๐Ÿ”ฅ. Only variables actually allocated on the stack count, so optimized-away variables or variables allocated in registers don't count, sorry not sorry.
  • -fstack-protector-all โ€” literally -fstack-protector but all functions get protected, no exceptions ๐Ÿ’….
  • -fstack-protector-strong โ€” like -fstack-protector but it also includes extra functions to be protected: the ones that have local array definitions, or have references to local frame addresses ๐ŸŽ€. Same deal as before โ€” only variables actually allocated on the stack are considered; optimized-away variables and register-allocated variables don't count.
  • -fstack-protector-explicit โ€” like -fstack-protector but it only protects those functions which have the "stack_protect" attribute ๐ŸŒธ.
  • -fstack-check โ€” generates code to verify you're not going beyond the boundary of the stack ๐Ÿฆ‹. You should specify this flag if you're running in an environment with multiple threads, but you only rarely need it in a single-threaded environment, because stack overflow is automatically detected on nearly all systems when there's only one stack.

Note that this switch does not actually cause checking to be done โ€” the operating system or the language runtime has to do that. The switch causes generation of code to ensure that they see the stack being extended ๐Ÿ‘€.

You can additionally specify a string parameter: no means no checking, generic 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 needs no specific target support in the compiler, but bestie, it comes with these drawbacks ๐Ÿ˜ญ:

  1. Modified allocation strategy for large objects: they're always allocated dynamically if their size exceeds a fixed threshold. Note this may change the semantics of some code โš ๏ธ.
  2. Fixed limit on the size of the static frame of functions: when it's topped by a particular function, stack checking is not reliable and a warning is issued by the compiler.
  3. Inefficiency: because of both the modified allocation strategy and the generic implementation, code performance is hampered ๐Ÿ’€.

Note that old-style stack checking is also the fallback method for specific if no target support has been added in the compiler.

-fstack-check= is designed for Ada's needs to detect infinite recursion and stack overflows. specific is an excellent choice when compiling Ada code โœจ. It is not generally sufficient to protect against stack-clash attacks โ€” for those you want -fstack-clash-protection.

  • -fstack-clash-protection โ€” generates code to prevent stack clash style attacks ๐Ÿ›ก๏ธ. When this option is enabled, the compiler will only allocate one page of stack space at a time, and each page is accessed immediately after allocation. So it prevents allocations from jumping over any stack guard page that the operating system provides.

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

  • -fstack-limit-register=reg, -fstack-limit-symbol=sym, -fno-stack-limit โ€” generates code to ensure the stack doesn't grow beyond a certain value, either the value of a register or the address of a symbol ๐ŸŽฏ. If a larger stack is required, a signal is raised at run time. For most targets, the signal gets raised before the stack overruns the boundary, so you can catch that signal without taking special precautions โ€” iconic behavior honestly.

For instance, if the stack starts at absolute address 0x80000000 and grows downwards, you can use the flags -fstack-limit-symbol=__stack_limit and -Wl,--defsym,__stack_limit=0x7ffe0000 to enforce a stack limit of 128KB. Note that this may only work with the GNU linker ๐Ÿ‘€.

You can locally override stack limit checking by using the "no_stack_limit" function attribute ๐Ÿ’œ.

  • -fsplit-stack โ€” generates code to automatically split the stack before it overflows ๐Ÿ”ฅ. The resulting program has a discontiguous stack which can only overflow if the program is unable to allocate any more memory โ€” so basically, good luck overflowing it. This is most useful when running threaded programs, because it's no longer necessary to calculate a good stack size to use for each thread. Currently 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 that latter code to run ๐Ÿ˜ฌ. If compiling all code โ€” including library code โ€” with -fsplit-stack isn't an option, then the linker can fix up these calls so that the code compiled without -fsplit-stack always has a large stack. Support for this is implemented in the gold linker in GNU binutils release 2.21 and later โœจ.

  • -fvtable-verify=[std|preinit|none] โ€” this one's C++ only, bestie ๐Ÿ’…. It turns on (or off, if you're using -fvtable-verify=none) the security feature that verifies at run time, for every virtual call, that the vtable pointer through which the call is made is valid for the type of the object, and hasn't been corrupted or overwritten ๐Ÿ˜ค. If an invalid vtable pointer is detected at run time, an error is reported and execution of the program is immediately halted ๐Ÿ’€.

This option causes run-time data structures to be built at program startup, which are then used for verifying the vtable pointers. The options std and preinit control the timing of when those data structures get built. In both cases they're 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, and preinit takes priority over std ๐Ÿ‘‘.

  • -fvtv-debug โ€” when used in conjunction with -fvtable-verify=std or -fvtable-verify=preinit, it causes debug versions of the runtime functions for the vtable verification feature to be called ๐Ÿ›. This flag also causes the compiler to log info 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 ๐Ÿ™ˆ.
  • -fvtv-counts โ€” this is a debugging flag ๐Ÿ›. When used with -fvtable-verify=std or -fvtable-verify=preinit, it causes the compiler to keep track of the total number of virtual calls it encounters and the number of verifications it inserts. It also counts the number of calls to certain run-time library functions that it inserts, and logs this info 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 to vtv_class_set_sizes.log in the same directory ๐Ÿ“.
Note: this feature appends data to the log files. To get fresh log files, be sure to delete any existing ones ๐ŸŒธ.
  • -finstrument-functions โ€” generates instrumentation calls for entry and exit to functions ๐ŸŽ€. Just after function entry and just before function exit, the following profiling functions get called with the address of the current function and its call site. (On some platforms, "__builtin_return_address" doesn't work beyond the current function, so the call site info may not be available to the profiling functions otherwise ๐Ÿ‘€.)
void __cyg_profile_func_enter (void *this_fn,
                               void *call_site);
void __cyg_profile_func_exit  (void *this_fn,
                               void *call_site);

The first argument is the address of the start of the current function, which you can look up exactly in the symbol table โœจ.

okay so bestie, this instrumentation is also done for functions expanded inline in other functions ๐Ÿ’…. The profiling calls indicate where, conceptually, the inline function is entered and exited. This means that addressable versions of such functions must be available. If all your uses of a function are expanded inline, this may mean an additional expansion of code size. If you use "extern inline" in your C code, an addressable version of such functions must be provided. (This is normally the case anyway, but if you get lucky and the optimizer always expands the functions inline, you might have gotten away without providing static copies.) ๐Ÿ˜ญ

A function may be given the attribute "no_instrument_function", in which case this instrumentation is not done. This can be used, for example, for the profiling functions listed above, high-priority interrupt routines, and any functions from which the profiling functions cannot safely be called (perhaps signal handlers, if the profiling routines generate output or allocate memory). ๐Ÿซถ

  • -finstrument-functions-once โ€” this is similar to -finstrument-functions, but the profiling functions are called only once per instrumented function, i.e. the first profiling function is called after the first entry into the instrumented function and the second profiling function is called before the exit corresponding to this first entry. ๐ŸŽ€
    • The definition of โ€œonceโ€ for the purpose of this option is a little vague because the implementation is not protected against data races. As a result, 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, that 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,... โ€” set the list of functions that are excluded from instrumentation (see the description of -finstrument-functions). 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 is considered to be 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 this option sets the list of function names to be excluded from instrumentation. ๐ŸŒธ
    • The function name to be matched is its user-visible name, such as vector<int> blah(const vector<int> &), not the internal mangled name (e.g., _Z4blahRSt6vectorIiSaIiEE). ๐Ÿ‘‘
    • The match is done on substrings: if the sym parameter is a substring of the function name, it is considered to be a match. For C99 and C++ extended identifiers, the function name must be given in UTF-8, not using universal character names. ๐ŸŒˆ
  • -fpatchable-function-entry=N[,M] โ€” generate N NOPs right at the beginning of each function, with the function entry point before the Mth NOP. If M is omitted, it defaults to 0 so the function entry points to the address just at the first NOP. ๐Ÿ”ฅ
    • The NOP instructions reserve extra space which can be used to patch in any desired instrumentation at run time, provided that the code segment is writable. The amount of space is controllable indirectly via the number of NOPs; the NOP instruction used corresponds to the instruction emitted by the internal GCC back-end interface gen_nop. This behavior is target-specific and may also depend on the architecture variant and/or other compilation options. ๐Ÿงš
    • For run-time identification, the starting addresses of these areas, which correspond to their respective function entries minus M, are additionally collected in the __patchable_function_entries section of the resulting binary. ๐Ÿ’œ
    • Note that the value of __attribute__ ((patchable_function_entry (N,M))) takes precedence over command-line option -fpatchable-function-entry=N,M. This can be used to increase the area size or to remove it completely on a single function. If N=0, no pad location is recorded. โญ
    • The NOP instructions are inserted atโ€”and maybe before, depending on Mโ€”the function entry address, even before the prologue. On PowerPC with the ELFv2 ABI, for a function with dual entry points, the local entry point is this function entry address by default. See the -msplit-patch-nops option to change this. ๐Ÿ“
    • 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 when not using -msplit-patch-nops. ๐Ÿ’–

๐ŸŒŸ Options Controlling the Preprocessor ๐ŸŒŸ

These options control the C preprocessor, which 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. 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 are invoking the preprocessor from a shell or shell-like program you may need to use the shellโ€™s quoting syntax to protect characters such as spaces that have a meaning in the shell syntax. ๐Ÿš
    • If you wish to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so you should quote the option. With sh and csh, -D'name(args...)=definition' works. โœจ
    • -D and -U options are processed in the order they are given on the command line. All -imacros file and -include file options are processed after all -D and -U options. ๐Ÿ”ฅ
  • -U name โ€” cancel any previous definition of name, either built in or provided with a -D option. ๐Ÿ’€
  • -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 not found there, it is searched for in the remainder of the #include "..." search chain as normal. ๐ŸŒธ
    • If multiple -include options are given, the files are included in the order they appear on the command line. ๐Ÿฆ‹
  • -imacros file โ€” exactly like -include, except that any output produced by scanning file is thrown away. Macros it defines remain defined. This allows you to acquire all the macros from a header without also processing its declarations. ๐Ÿงš
    • 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. โœจ
    • When used with the driver options -MD or -MMD, -MF overrides the default dependency output file. ๐Ÿ’…
    • If file is -, then the dependencies are written to stdout. ๐ŸŽ€
  • -MG โ€” in conjunction with an option such as -M requesting dependency generation, -MG assumes missing header files are generated files and adds them to the dependency list without raising an error. The dependency filename is taken directly from the #include directive without prepending any path. -MG also suppresses preprocessed output, as a missing header file renders this useless. ๐Ÿ”ฅ
    • This feature is used in automatic updating of makefiles. ๐Ÿฆ‹
  • -Mno-modules โ€” disable dependency generation for compiled module interfaces. ๐Ÿ’œ
  • -MP โ€” tells CPP to add a phony target for every dependency except the main file, so each one depends on nothing. These dummy rules are the fix for the errors make throws when you delete header files without updating the Makefile to match. This is typical output:
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 such as .c, and appends the platformโ€™s usual object suffix. That result is the target. An -MT option sets the target to be exactly the string you specify. If you want multiple targets, you can specify them as a single argument to -MT, or use multiple -MT options. For example, -MT '$(objpfx)foo.o' might give:
$(objpfx)foo.o: foo.c
  • -MQ target โ€” same as -MT, but it quotes any characters which are special to Make. -MQ '$(objpfx)foo.o' gives:
$$(objpfx)foo.o: foo.c

The default target is automatically quoted, as if it were given with -MQ.

  • -MD โ€” -MD is equivalent to -M -MF file, except that -E is not implied. The driver determines file based on whether an -o option is given. If it is, the driver uses its argument but with a suffix of .d; otherwise it takes the name of the input file, removes any directory components and suffix, and applies a .d suffix.

If -MD is used in conjunction with -E, any -o switch is understood to specify the dependency output file, but if used without -E, each -o is understood to specify a target object file.

Since -E is not implied, -MD can be used to generate a dependency output file as a side effect of the compilation process.

  • -MMD โ€” like -MD except mention only user header files, not system header files.
  • -fpreprocessed โ€” tells the preprocessor the input file has already been preprocessed. This suppresses things like macro expansion, trigraph conversion, escaped newline splicing, and processing of most directives. The preprocessor still recognizes and removes comments, 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.

-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 optionโ€™s behavior depends on the -E and -fpreprocessed options.

With -E, preprocessing is limited to the handling of directives such as "#define", "#ifdef", and "#error". Other preprocessor operations, such as macro expansion and trigraph conversion, are not performed. In addition, the -dD option is implicitly enabled.

With -fpreprocessed, predefinition of command line and most builtin macros is disabled. Macros such as "__LINE__", which are contextually dependent, are handled normally. This enables compilation of files previously preprocessed with "-E -fdirectives-only".

With both -E and -fpreprocessed, the rules for -fpreprocessed take precedence. This enables full preprocessing of files previously preprocessed with "-E -fdirectives-only".

  • -fdollars-in-identifiers โ€” accept $ in identifiers. ๐Ÿ’ธ
  • -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++.
  • -fno-canonical-system-headers โ€” when preprocessing, do not shorten system header paths with canonicalization.
  • -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 allows the compiler to emit diagnostics about the current macro expansion stack when a compilation error occurs in a macro expansion. Using this option makes the preprocessor and the compiler consume more memory. The level parameter can be used to choose the level of precision of token location tracking, thus decreasing memory consumption if necessary. Value 0 of level de-activates this option. Value 1 tracks token locations in a degraded mode for the sake of minimal memory overhead; in this mode all tokens resulting from the expansion of an argument of a function-like macro have the same location. Value 2 tracks token locations completely; 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.
  • -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".
  • -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 not specified, only the precompiled header is listed and not the files that were used to create it, because those files are not consulted when a precompiled header is used.
  • -fpch-preprocess โ€” this option allows use of a precompiled header together with -E. It inserts a special "#pragma", specifically "#pragma GCC pch_preprocess "filename"", in the output to mark the place where the precompiled header was found, and its filename. When -fpreprocessed is in use, GCC recognizes this "#pragma" and loads the PCH.

This option is off by default, because the resulting preprocessed output is only really suitable as input to GCC. It is switched on by -save-temps.

You should not write this "#pragma" in your own code, but it is safe to edit the filename if the PCH file is available in a different location. The filename may be absolute or it may be relative to GCCโ€™s current directory.

  • -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.
  • -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.
  • -A -predicate=answer โ€” cancel an assertion with the predicate predicate and answer answer.
  • -C โ€” do not discard comments. All comments are passed through to the output file, except for comments in processed directives, which are deleted along with the directive.

You should be prepared for side effects when using -C; it causes the preprocessor to treat comments as tokens in their own right. For example, comments appearing at the start of what would be a directive line have the effect of turning that line into an ordinary source line, since the first token on the line is no longer a #.

  • -CC โ€” do not discard comments, including during macro expansion. This is like -C, except that comments contained within macros are also passed through to the output file where the macro is expanded.

In addition to the side effects of the -C option, the -CC option causes all C++-style comments inside a macro to be converted to C-style comments. This is to prevent later use of that macro from inadvertently commenting out the remainder of the source line.

The -CC option is generally used to support lint comments.

  • -P โ€” inhibit generation of linemarkers in the output from the preprocessor. This might be useful when running the preprocessor on something that is not C code, and will be sent to a program which might be confused by the linemarkers.
  • -traditional, -traditional-cpp โ€” try to imitate the behavior of pre-standard C preprocessors, as opposed to ISO C preprocessors. See the GNU CPP manual for details.

quick note first, bestie: GCC does not otherwise try to emulate a pre-standard C compiler, and these options are only supported with the -E switch, or when you invoke CPP explicitly.

  • -trigraphs โ€” Support ISO C trigraphs. These are three-character sequences, all starting with ??, that are defined by ISO C to stand for single characters. For example, ??/ stands for \, so '??/n' is a character constant for a newline.

The nine trigraphs and their replacements are:

Trigraph:       ??(  ??)  ??<  ??>  ??=  ??/  ??'  ??!  ??-
Replacement:      [    ]    {    }    #    \    ^    |    ~

By default, GCC ignores trigraphs, but in standard-conforming modes it converts them. See the -std and -ansi options.

  • -remap โ€” Enable special code to work around file systems which only permit very short file names, such as MS-DOS.
  • -H โ€” Print the name of each header file used, in addition to other normal activities. Each name is indented to show how deep in the #include stack it is. Precompiled header files are also printed, even if they are found to be invalid; an invalid precompiled header file is printed with ...x and a valid one with ...!.
  • -dletters โ€” Says to make debugging dumps during compilation as specified by letters. The flags documented here are those relevant to the preprocessor. Other letters are interpreted by the compiler proper, or reserved for future versions of GCC, and so are silently ignored.
If you specify letters whose behavior conflicts, the result is undefined.
  • -dM โ€” Instead of the normal output, generate a list of #define directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor. Assuming you have no file foo.h, the command
touch foo.h; cpp -dM foo.h

shows all the predefined macros.

If you use -dM without the -E option, -dM is interpreted as a synonym for -fdump-rtl-mach.

  • -dD โ€” Like -dM except in two respects: it does not include the predefined macros, and it outputs both the #define directives and the result of preprocessing. Both kinds of output go to the standard output file.
  • -dN โ€” Like -dD, but emit only the macro names, not their expansions.
  • -dI โ€” Output #include directives in addition to the result of preprocessing.
  • -dU โ€” Like -dD except that only macros that are expanded, or whose definedness is tested in preprocessor directives, are output; the output is delayed until the use or test of the macro; and #undef directives are also output for macros tested but undefined at the time.
  • -fdebug-cpp โ€” This option is only useful for debugging GCC. When used from CPP or with -E, it dumps debugging information about location maps. Every token in the output is preceded by the dump of the map its location belongs to.

When used from GCC without -E, this option has no effect.

  • -Wp,option โ€” You can use -Wp,option to bypass the compiler driver and pass option directly through to the preprocessor. If option contains commas, it is split into multiple options at the commas. However, many options are modified, translated or interpreted by the compiler driver before being passed to the preprocessor, and -Wp forcibly bypasses this phase. The preprocessor's direct interface is undocumented and subject to change, so whenever possible you should avoid using -Wp and let the driver handle the options instead.
  • -Xpreprocessor option โ€” Pass option as an option to the preprocessor. You can use this to supply system-specific preprocessor options that GCC does not recognize.

If you want to pass an option that takes an argument, you must use -Xpreprocessor twice, once for the option and once for the argument.

  • -no-integrated-cpp โ€” Perform preprocessing as a separate pass before compilation. By default, GCC performs preprocessing as an integrated part of input tokenization and parsing. If this option is provided, the appropriate language front end (cc1, cc1plus, or cc1obj for C, C++, and Objective-C, respectively) is instead invoked twice, once for preprocessing only and once for actual compilation of the preprocessed input. This option may be useful in conjunction with the -B or -wrapper options to specify an alternate preprocessor or perform additional processing of the program source between normal preprocessing and compilation.
  • -flarge-source-files โ€” Adjust GCC to expect large source files, at the expense of slower compilation and higher memory usage.

Specifically, GCC normally tracks both column numbers and line numbers within source files and it normally prints both of these numbers in diagnostics. However, once it has processed a certain number of source lines, it stops tracking column numbers and only tracks line numbers. This means that diagnostics for later lines do not include column numbers. It also means that options like -Wmisleading-indentation cease to work at that point, although the compiler prints a note if this happens. Passing -flarge-source-files significantly increases the number of source lines that GCC can process before it stops tracking columns.


โœจ Passing Options to the Assembler โœจ

You can pass options to the assembler, bestie. ๐Ÿ’–

  • -Wa,option โ€” Pass option as an option to the assembler. If option contains commas, it is split into multiple options at the commas.
  • -Xassembler option โ€” Pass option as an option to the assembler. You can use this to supply system-specific assembler options that GCC does not recognize.

If you want to pass an option that takes an argument, you must use -Xassembler twice, once for the option and once for the argument.


๐Ÿ”— Options for Linking ๐Ÿ”—

These options come into play when the compiler links object files into an executable output file. They are meaningless if the compiler is not doing a link step.

  • object-file-name โ€” A file name that does not end in a special recognized suffix is considered to name an object file or library. (Object files are distinguished from libraries by the linker according to the file contents.) If linking is done, these object files are used as input to the linker.
  • -c, -S, -E โ€” If any of these options is used, then the linker is not run, and object file names should not be used as arguments.
  • -flinker-output=type โ€” This option controls code generation of the link-time optimizer. By default the linker output is automatically determined by the linker plugin. For debugging the compiler and if incremental linking with a non-LTO object file is desired, it may be useful to control the type manually.

If type is exec, code generation produces a static binary. In this case -fpic and -fpie are both disabled.

If type is dyn, code generation produces a shared library. In this case -fpic or -fPIC is preserved, but not enabled automatically. This allows to build shared libraries without position-independent code on architectures where this is possible, i.e. on x86.

If type is pie, code generation produces an -fpie executable. This results in similar optimizations as exec except that -fpie is not disabled if specified at compilation time.

If type is rel, the compiler assumes that incremental linking is done. The sections containing intermediate code for link-time optimization are merged, pre-optimized, and output to the resulting object file. In addition, if -ffat-lto-objects is specified, binary code is produced for future non-LTO linking. The object file produced by incremental linking is smaller than a static library produced from the same object files. At link time the result of incremental linking also loads faster than a static library assuming that the majority of objects in the library are used.

Finally nolto-rel configures the compiler for incremental linking where code generation is forced, a final binary is produced, and the intermediate code for later link-time optimization is stripped. When multiple object files are linked together the resulting code is better optimized than with link-time optimizations disabled (for example, cross-module inlining happens), but most of benefits of whole program optimizations are lost.

During the incremental link (by -r) the linker plugin defaults to rel. With current interfaces to GNU Binutils it is however not possible to incrementally link LTO objects and non-LTO objects into a single mixed object file. If any of object files in incremental link cannot be used for link-time optimization, the linker plugin issues a warning and uses nolto-rel. To maintain whole program optimization, it is recommended to link such objects into static library instead. Alternatively it is possible to use H.J. Lu's binutils with support for mixed objects.

  • -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.
  • -llibrary, -l library โ€” Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.)

The -l option is passed directly to the linker by GCC. Refer to your linker documentation for exact details. The general description below applies to the GNU linker.

The linker searches a standard list of directories for the library. The directories searched include several standard system directories plus any that you specify with -L.

Static libraries are archives of object files, and have file names like liblibrary.a. Some targets also support shared libraries, which typically have names like liblibrary.so. If both static and shared libraries are found, the linker gives preference to linking with the shared library unless the -static option is used.

Okay so the order thing โ€” it fr fr matters where in the command you write this option, like placement is everything bestie ๐Ÿ’…. 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 file foo.o but before bar.o. And if bar.o refers to functions in zโ€ฆ those functions may not be loaded ๐Ÿ˜ญ. It's giving "read the room, in order."

  • -lobjc โ€” bestie you need this special case of the -l option specifically to link an Objective-C or Objective-C++ program ๐Ÿ“.
  • -nostartfiles โ€” nope, don't use the standard system startup files when linking ๐Ÿ™ˆ. The standard system libraries are still used normally, unless -nostdlib, -nolibc, or -nodefaultlibs is used too.
  • -nodefaultlibs โ€” do not use the standard system libraries when linking ๐Ÿšซ. Only the libraries you specify get passed to the linker, and options specifying linkage of the system libraries, such as -static-libgcc or -shared-libgcc, are ignored (sorry queen, they're just not invited). The standard startup files are used normally, unless -nostartfiles is used.

The compiler may generate calls to memcmp, memset, memcpy and memmove โ€” and those entries are usually resolved by entries in libc. But when this option is specified, those entry points should be supplied through some other mechanism ๐Ÿ”ฅ.

  • -nolibc โ€” don't use the C library or system libraries tightly coupled with it when linking ๐Ÿ’€. It still links with the startup files, libgcc, or toolchain-provided language support libraries such as libgnat, libgfortran or libstdc++ โ€” unless options preventing their inclusion are used as well. This typically removes -lc from the link command line, plus system libraries that normally go with it and become meaningless when absence of a C library is assumed (for example -lpthread or -lm in some configurations). It's intended for bare-board targets when there is indeed no C library available โ€” main character bare-metal energy ๐Ÿงš.
  • -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.

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.

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.) No cap, don't skip this one ๐Ÿซถ.

  • -nostdlib++ โ€” do not implicitly link with standard C++ libraries ๐ŸŒธ.
  • -e entry, --entry=`entry โ€” specify that the program entry point is entry ๐Ÿ’–. The argument is interpreted by the linker; the GNU linker accepts either a symbol name or an address.
  • -pie โ€” produce a dynamically linked position independent executable on targets that support it ๐ŸŒˆ. For predictable results, you must also specify the same set of options used for compilation (-fpie, -fPIE, or model suboptions) when you specify this linker option โ€” consistency is the vibe check.
  • -no-pie โ€” don't produce a dynamically linked position independent executable ๐Ÿ™….
  • -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 (yes, both, don't half-ass it).
  • -r โ€” produce a relocatable object as output ๐Ÿ”ฅ. This is also known as partial linking.
  • -rdynamic โ€” pass the flag -export-dynamic to the ELF linker, on targets that support it โญ. This instructs the linker to add all symbols, not only used ones, to the dynamic symbol table. This option is needed for some uses of dlopen or to allow obtaining backtraces from within a program โ€” very "I want receipts from inside the program" of it.
  • -s โ€” remove all symbol table and relocation information from the executable โœ‚๏ธ๐Ÿ’€. Gone, deleted, not invited to the group chat.
  • -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.
  • -shared โ€” produce a shared object which can then be linked with other objects to form an executable ๐ŸŽ€. Not all systems support this option. For predictable results, you must also specify the same set of options used for compilation (-fpic, -fPIC, or model suboptions) when you specify this linker option.[1]
  • -shared-libgcc, -static-libgcc โ€” on systems that provide libgcc as a shared library, these options force the use of either the shared or static version, respectively ๐ŸŒธ. If no shared version of libgcc was built when the compiler was configured, these options have no effect (sad, but true).

There are several situations in which an application should use the shared libgcc instead of the static version. The most common of these is when the application wishes to throw and catch exceptions across different shared libraries. In that case, each of the libraries as well as the application itself should use the shared libgcc.

Therefore, the G++ driver automatically adds -shared-libgcc whenever you build a shared library or a main executable, because C++ programs typically use exceptions, so this is the right thing to do ๐Ÿ‘‘.

If, instead, you use the GCC driver to create shared libraries, you may find that they are not always linked with the shared libgcc. If GCC finds, at its configuration time, that you have a non-GNU linker or a GNU linker that does not support option --eh-frame-hdr, it links the shared version of libgcc into shared libraries by default. Otherwise, it takes advantage of the linker and optimizes away the linking with the shared version of libgcc, linking with the static version of libgcc by default. This allows exceptions to propagate through such shared libraries, without incurring relocation costs at library load time.

However, if a library or main executable is supposed to throw or catch exceptions, you must link it using the G++ driver, or using the option -shared-libgcc, such that it is linked with the shared libgcc ๐Ÿ’….

  • -static-libasan โ€” when the -fsanitize=address option is used to link a program, the GCC driver automatically links against libasan ๐Ÿ”. If libasan is available as a shared library, and the -static option is not used, then this links against the shared version of libasan. The -static-libasan option directs the GCC driver to link libasan statically, without necessarily linking other libraries statically.
  • -static-libtsan โ€” when the -fsanitize=thread option is used to link a program, the GCC driver automatically links against libtsan ๐Ÿงต. If libtsan is available as a shared library, and the -static option is not used, then this links against the shared version of libtsan. The -static-libtsan option directs the GCC driver to link libtsan statically, without necessarily linking other libraries statically.
  • -static-liblsan โ€” when the -fsanitize=leak option is used to link a program, the GCC driver automatically links against liblsan ๐Ÿ’ง. If liblsan is available as a shared library, and the -static option is not used, then this links against the shared version of liblsan. The -static-liblsan option directs the GCC driver to link liblsan statically, without necessarily linking other libraries statically.
  • -static-libubsan โ€” when the -fsanitize=undefined option is used to link a program, the GCC driver automatically links against libubsan ๐Ÿฆ‹. If libubsan is available as a shared library, and the -static option is not used, then this links against the shared version of libubsan. The -static-libubsan option directs the GCC driver to link libubsan statically, without necessarily linking other libraries statically.
  • -static-libstdc++ โ€” when the g++ program is used to link a C++ program, it normally automatically links against libstdc++ ๐Ÿ’œ. If libstdc++ is available as a shared library, and the -static option is not used, then this links against the shared version of libstdc++. That is normally fine. However, it is sometimes useful to freeze the version of libstdc++ used by the program without going all the way to a fully static link ๐ŸงŠ. The -static-libstdc++ option directs the g++ driver to link libstdc++ statically, without necessarily linking other libraries statically.
  • -symbolic โ€” bind references to global symbols when building a shared object ๐Ÿ”—. Warn about any unresolved references (unless overridden by the link editor option -Xlinker -z -Xlinker defs). Only a few systems support this option.
  • -T script โ€” use script as the linker script ๐Ÿ“œ. This option is supported by most systems using the GNU linker. On some targets, such as bare-board targets without an operating system, the -T option may be required when linking to avoid references to undefined symbols.
  • -Xlinker option โ€” pass option as an option to the linker ๐Ÿซถ. You can use this to supply system-specific linker options that GCC does not recognize.

If you want to pass an option that takes a separate argument, you must use -Xlinker twice โ€” once for the option and once for the argument. For example, to pass -assert definitions, you must write -Xlinker -assert -Xlinker definitions. It does not work to write -Xlinker "-assert definitions", because this passes the entire string as a single argument, which is not what the linker expects ๐Ÿ˜ญ โ€” like texting the whole sentence as one word, the linker is not gonna parse that bestie.


When you're working with the GNU linker, it's usually wayyy more convenient to hand linker options their arguments with the option=value syntax instead of passing them as separate args. Like, you can write -Xlinker -Map=output.map instead of the whole -Xlinker -Map -Xlinker output.map situation. Ngl though, other linkers might not support this syntax for command-line options, so don't @ me. ๐Ÿ’…

  • -Wl,option โ€” passes option straight through as an option to the linker. And if option has commas in it? It gets split into multiple options at the commas, bestie. You can use this syntax to pass an argument to the option too โ€” for example -Wl,-Map,output.map passes -Map output.map to the linker. And when you're using the GNU linker, you can get the exact same effect with -Wl,-Map=output.map. โœจ
  • -u symbol โ€” pretends that the symbol symbol is undefined, which forces the linking of library modules to define it. You can use -u multiple times with different symbols to force loading of even more library modules. Iconic, honestly. ๐Ÿ‘‘
  • -z keyword โ€” -z gets passed directly on to the linker along with the keyword keyword. Peep the section in your linker's documentation for what values are permitted and what they mean (iykyk). ๐Ÿ”

These options tell the compiler where to go looking for header files, libraries, and parts of the compiler itself. Think of it as setting up the group chat invite list, but for directories: ๐Ÿ’–

  • -I dir, -iquote dir, -isystem dir, -idirafter dir โ€” adds the directory dir to the list of directories searched for header files during preprocessing. If dir begins with = or $SYSROOT, then the = or $SYSROOT gets replaced by the sysroot prefix โ€” check out --sysroot and -isysroot for the lore.

Directories specified with -iquote apply only to the quote form of the directive, #include "file". Directories specified with -I, -isystem, or -idirafter apply to lookup for both the #include "file" and #include <file> directives.

You can specify any number or combination of these options on the command line to search for header files in several directories. The lookup order goes like this, and yes, you should absolutely memorize it:

  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 are searched before the standard system header file directories. BUT โ€” and this is a big but โ€” you should not use this option to add directories that contain vendor-supplied system header files; use -isystem for that. Respect the system headers, bestie. ๐Ÿ™ˆ

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. Fancy. โœจ

If a standard system include directory, or a directory specified with -isystem, is also specified with -I, the -I option is ignored. The directory is still searched, but as a system directory at its normal position in the system include chain. Why? To make sure GCC's procedure to fix buggy system headers and the ordering for the #include_next directive don't get inadvertently changed. If you really, truly need to change the search order for system directories, use the -nostdinc and/or -isystem options. Periodt. ๐Ÿ’…

  • -I- โ€” splits the include path. โš ๏ธ Heads up: this option has been deprecated. Please use -iquote instead for -I directories before the -I-, and remove the -I- option entirely.

Any directories specified with -I options before -I- are searched only for headers requested with #include "file"; they are not searched for #include <file>. If additional directories are specified with -I options after the -I-, those directories are searched for all #include directives.

Also, -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-. Like, none. ๐Ÿ˜ญ

  • -iprefix prefix โ€” specifies prefix as the prefix for subsequent -iwithprefix options. If the prefix represents a directory, you should include the final /. Don't forget it, or it's giving broken path energy. ๐Ÿซถ
  • -iwithprefix dir, -iwithprefixbefore dir โ€” appends dir to the prefix specified previously with -iprefix, and adds the resulting directory to the include search path. -iwithprefixbefore puts it in the same place -I would; -iwithprefix puts it where -idirafter would. Two little twins, different vibes. ๐Ÿงš
  • -isysroot dir โ€” this option is like the --sysroot option, but applies only to header files (except for Darwin targets, where it applies to both header files and libraries). See the --sysroot option for more info. ๐Ÿ“
  • -imultilib dir โ€” uses dir as a subdirectory of the directory containing target-specific C++ headers.
  • -nostdinc โ€” do not search the standard system directories for header files. Only the directories explicitly specified with -I, -iquote, -isystem, and/or -idirafter options (and the directory of the current file, if appropriate) are searched. No defaults, no filler. ๐Ÿ’€
  • -nostdinc++ โ€” do not search for header files in the C++-specific standard directories, but do still search the other standard directories. (This option is used when building the C++ library โ€” so if you're not doing that, mind your business.) ๐ŸŒธ
  • -iplugindir=dir โ€” sets the directory to search for plugins that are passed by -fplugin=name instead of -fplugin=path/name.so. This option is not meant to be used by the user, but only passed by the driver. So like... hands off, bestie. ๐Ÿ™…โ€โ™€๏ธ
  • -Ldir โ€” adds directory dir to the list of directories to be searched for -l. Simple, clean, iconic. โœจ
  • -Bprefix โ€” this option specifies where to find the executables, libraries, include files, and data files of the compiler itself. Big main character energy. ๐Ÿ‘‘

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 wasn'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. It's giving "try everything until something hits." ๐Ÿ’…

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. No cap. ๐Ÿ˜ญ

Another way to specify a prefix much like the -B prefix is to use the environment variable GCC_EXEC_PREFIX.

And 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. Weird? Yes. Canon? Also yes. ๐Ÿฆ‹

  • -no-canonical-prefixes โ€” do not expand any symbolic links, resolve references to /../ or /./, or make the path absolute when generating a relative prefix. Just... leave the path exactly as it is. ๐Ÿ’œ
  • --sysroot=dir โ€” uses 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. It's the "imagine this is the root" option. ๐ŸŒˆ

If you use both this option and the -isysroot option, then --sysroot applies to libraries, but -isysroot applies to header files.

The GNU linker (beginning with version 2.16) has the necessary support for this option. If your linker doesn't support this option, the header file aspect of --sysroot still works, but the library aspect does not. Half the slay, unfortunately. ๐Ÿ’€

  • --no-sysroot-suffix โ€” for some targets, a suffix is added to the root directory specified with --sysroot, depending on the other options used, so that headers may for example be found in dir/suffix/usr/include instead of dir/usr/include. This option disables the addition of such a suffix. Bye bye extra suffix. ๐ŸŽ€

๐Ÿ”ฅ Options for Code Generation Conventions ๐Ÿ”ฅ

These machine-independent options control the interface conventions used in code generation. Very "the rules of the universe" of it all. ๐ŸŒŒ

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. Iyk what I mean. ๐Ÿ˜Œ

  • -fstack-reuse=reuse-level โ€” this option controls stack space reuse for user declared local/auto variables and compiler generated temporaries. reuse_level can be all, named_vars, or none.

all enables stack reuse for all local variables and temporaries, named_vars enables the reuse only for user defined local variables with names, and none disables stack reuse completely. The default value is all. ๐Ÿซถ

The option is needed when the program extends the lifetime of a scoped local variable or a compiler generated temporary beyond the end point defined by the language. When a lifetime of a variable ends, and if the variable lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped local variables whose live range does not overlap with it. Legacy code extending local lifetime is likely to break with the stack reuse optimization. โš ๏ธ So like... be careful. This is the danger zone.

For example:

int *p;
{
  int local1;

  p = &local1;
  local1 = 10;
  ....
}
{
   int local2;
   local2 = 20;
   ...
}
                      if (*p == 10)  // out of scope use of local1
                        {

                        }

โ€ฆand here's the other one, bestie:

           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?
                      }

So like, the lifetime of a compiler generated temporary is well defined by the C++ standard, no cap ๐Ÿ’…. When a temporary's lifetime ends โ€” and if that temporary lives in memory โ€” the optimizing compiler is lowkey free to reuse its stack space with other temporaries or with scoped local variables whose live range doesn't overlap with it. Iconic, efficient, all that. BUT some legacy code relies on how older compilers behaved, where temporaries' stack space was not reused, and aggressive stack reuse can lead to runtime errors ๐Ÿ˜ญ. This option is literally the dial you use to control the temporary stack reuse optimization. ๐ŸŽ€

  • -ftrapv โ€” this one generates traps for signed overflow on addition, subtraction and multiplication operations ๐Ÿšจ. Heads up: -ftrapv and -fwrapv override each other, so putting -ftrapv -fwrapv on the command line means -fwrapv is the one that ends up effective. And ngl, only active options override โ€” so -ftrapv -fwrapv -fno-wrapv on the command line? That one results in -ftrapv being effective. ๐Ÿซถ
  • -fwrapv โ€” this 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. And same rule as above: -ftrapv and -fwrapv override each other, so -ftrapv -fwrapv on the command line gives you -fwrapv effective. Also only active options override, so -ftrapv -fwrapv -fno-wrapv on the command line results in -ftrapv being effective. iykyk ๐Ÿ’…
  • -fwrapv-pointer โ€” this instructs the compiler to assume that pointer arithmetic overflow on addition and subtraction wraps around using twos-complement representation. This flag disables some optimizations which assume pointer overflow is invalid. ๐Ÿฆ‹
  • -fstrict-overflow โ€” implies -fno-wrapv -fno-wrapv-pointer, and when negated it implies -fwrapv -fwrapv-pointer. Cute little bundle, periodt. โœจ
  • -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, so breathe ๐Ÿ˜ฎโ€๐Ÿ’จ. 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. That said, you may need to enable it when compiling C code that needs to interoperate properly with exception handlers written in C++. You may also wish to disable this option if you're compiling older C++ programs that don't use exception handling. ๐Ÿ’œ
  • -fnon-call-exceptions โ€” generate code that allows trapping instructions to throw exceptions. Lowkey important caveat: this requires platform-specific runtime support that does not exist everywhere ๐Ÿ™ˆ. And more than that, it only allows trapping instructions to throw exceptions โ€” like memory references or floating-point instructions. It does not allow exceptions to be thrown from arbitrary signal handlers such as SIGALRM. This enables -fexceptions.
  • -fdelete-dead-exceptions โ€” consider that instructions that may throw exceptions but don't otherwise contribute to the execution of the program can be optimized away ๐Ÿ—‘๏ธ. This does not affect calls to functions except those with the pure or const attributes. This option is enabled by default for the Ada and C++ compilers, as permitted by the language specifications. Optimization passes that cause dead exceptions to be removed are enabled independently at different optimization levels. โญ
  • -funwind-tables โ€” similar to -fexceptions, except it just generates any needed static data, 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 ๐Ÿซถ.
  • -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 a debugger or a garbage collector). iconic.
  • -fno-gnu-unique โ€” okay so 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. That'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 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. slay, problem solved ๐Ÿ’…
  • -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 decision-making 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 queen energy ๐ŸŽ€
Warning: the -fshort-enums switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface.
  • -fshort-wchar โ€” override the underlying type for wchar_t to be short unsigned int instead of the default for the target. This option is useful for building programs to run under WINE ๐Ÿท.
Warning: the -fshort-wchar switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface.
  • -fcommon โ€” in C code, this option controls the placement of global variables defined without an initializer, known as tentative definitions in the C standard. Tentative definitions are distinct from declarations of a variable with the extern keyword, which do not allocate storage ๐Ÿง.

The default is -fno-common, which specifies that the compiler places uninitialized global variables in the BSS section of the object file. This inhibits the merging of tentative definitions by the linker, so you get a multiple-definition error if the same variable is accidentally defined in more than one compilation unit ๐Ÿ’€.

The -fcommon places uninitialized global variables in a common block. This allows the linker to resolve all tentative definitions of the same variable in different compilation units to the same object, or to a non-tentative definition. This behavior is inconsistent with C++, and on many targets implies a speed and code size penalty on global variable references ๐ŸŒ. It is mainly useful to enable legacy code to link without errors. we love a legacy-code rescue mission ๐Ÿซถ

  • -fno-ident โ€” ignore the #ident directive. bye felicia ๐Ÿ‘‹
  • -finhibit-size-directive โ€” don't output a .size assembler directive, or anything else that would cause trouble if the function is split in the middle, and the two halves are placed at locations far apart in memory. This option is used when compiling crtstuff.c; you should not need to use it for anything else. like, seriously, that's its whole job ๐Ÿ’…
  • -fverbose-asm โ€” put extra commentary information in the generated assembly code to make it more readable โœจ. This option is generally only of use to those who actually need to read the generated assembly code (perhaps while debugging the compiler itself). nerd hours, and honestly, respect ๐Ÿงš

-fno-verbose-asm, the default, causes the extra information to be omitted and is useful when comparing two assembler files.

The added comments include:

  • information on the compiler version and command-line options,
  • the source code lines associated with the assembly instructions, in the form FILENAME:LINENUMBER:CONTENT OF LINE,
  • hints on which high-level expressions correspond to the various assembly instruction operands.

For example, given this C source file:

        int test (int n)
        {
          int i;
          int total = 0;

          for (i = 0; i < n; i++)
            total += i * i;
  return total;
}

so like, compiling to (x86_64) assembly via -S and yeeting the result straight to stdout via -o -, like this:

gcc -S test.c -fverbose-asm -Os -o -

gives you output that's giving pretty much 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

bestie, those comments are for humans not machines, so the exact format of them is literally subject to change โ€” don't go parsing them, ok? ๐Ÿ™ˆ

  • -frecord-gcc-switches โ€” this one makes the command line you used to invoke the compiler get recorded right there into the object file being created ๐Ÿ“. ngl it's only implemented on some targets, and the exact format of the recording depends on the target and the binary file format, but it usually takes the form of a section containing ASCII text. It's related to -fverbose-asm, except that switch only records info in the assembler output file as comments, so it never reaches the object file. Also peep -grecord-gcc-switches for another way of storing compiler options into the object file. โœจ
  • -fpic โ€” generate position-independent code (PIC) suitable for use in a shared library, if it's supported for the target machine. Such code accesses all constant addresses through a global offset table (GOT) ๐Ÿ’…. The dynamic loader resolves the GOT entries when the program starts (the dynamic loader is not part of GCC; it is part of the operating system โ€” not our department fr). If the GOT size for the linked executable exceeds a machine-specific maximum size, you get an error message from the linker indicating that -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. ๐Ÿ˜Œ)

Position-independent code requires special support, and therefore works only on certain machines. For the x86, GCC supports PIC for System V but not for the Sun 386i. Code generated for the IBM RS/6000 is always position-independent.

When this flag is set, the macros "__pic__" and "__PIC__" are defined to 1.

  • -fPIC โ€” if supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table ๐ŸŒˆ. This option makes a difference on AArch64, m68k, PowerPC and SPARC.

Position-independent code requires special support, and therefore works only on certain machines.

When this flag is set, the macros "__pic__" and "__PIC__" are defined to 2.

  • -fpie, -fPIE โ€” these are basically the little siblings of -fpic and -fPIC ๐Ÿซถ, except the generated position-independent code can only be linked into executables. Usually these are used to compile code that's gonna 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. iykyk ๐Ÿ’…
  • -fno-bit-tests โ€” do not use bit tests for switch statements even where it would be more efficient than other code generation strategies. periodt.
  • -ffixed-reg โ€” treat the register named reg as a fixed register; generated code should never refer to it (except 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. no -fno- version for you, sorry bestie ๐Ÿ˜ญ
  • -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. ๐Ÿซฃ like, catastrophic. don't.

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. ๐Ÿ’€ literally two flavors of chaos.

This flag does not have a negative form, because it specifies a three-way choice.

  • -fpack-struct[=n] โ€” with no value specified, pack all structure members together without holes ๐ŸŽ€. When a value is specified (which must be a small power of two), pack structure members according to this value, representing the maximum alignment (that is, objects with default alignment requirements larger than this are output potentially unaligned at the next fitting location).
Warning: the -fpack-struct switch causes GCC to generate code that is not binary compatible with code generated without that switch. Additionally, it makes the code suboptimal. Use it to conform to a non-default application binary interface. โš ๏ธ
  • -fleading-underscore โ€” this option and its counterpart, -fno-leading-underscore, forcibly change the way C symbols are represented in the object file ๐Ÿฆ‹. One use is to help link with legacy assembly code.
Warning: the -fleading-underscore switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface. Not all targets provide complete support for this switch. ๐Ÿ™ˆ
  • -ftls-model=model โ€” alter the thread-local storage model to be used ๐Ÿ”„. The model argument should be one of global-dynamic, local-dynamic, initial-exec or local-exec. Note that the choice is subject to optimization: the compiler may use a more efficient model for symbols not visible outside of the translation unit, or if -fpic is not given on the command line.

The default without -fpic is initial-exec; with -fpic the default is global-dynamic.

  • -ftrampolines โ€” for targets that normally need trampolines for nested functions, always generate them instead of using descriptors ๐ŸŽช. Otherwise, for targets that do not need them, like for example HP-PA or IA-64, do nothing.

A trampoline is a small piece of code that is created at run time on the stack when the address of a nested function is taken, and is used to call the nested function indirectly. Therefore, it requires the stack to be made executable in order for the program to work properly. ๐Ÿ˜ฌ yes, that kind of executable.

-fno-trampolines is enabled by default on a language by language basis to let the compiler avoid generating them, if it computes that this is safe, and replace them with descriptors. Descriptors are made up of data only, but the generated code must be prepared to deal with them. As of this writing, -fno-trampolines is enabled by default only for Ada.

Moreover, code compiled with -ftrampolines and code compiled with -fno-trampolines are not binary compatible if nested functions are present. This option must therefore be used on a program-wide basis and be manipulated with extreme care. ๐Ÿซถ like, whole-program or nothing, bestie.

For languages other than Ada, the "-ftrampolines" and "-fno-trampolines" options currently have no effect, and trampolines are always generated on platforms that need them for nested functions. ๐Ÿ’œ

-fvisibility=[default|internal|hidden|protected] โ€” okay so this one sets the default ELF image symbol visibility to whatever you pick, and likeโ€ฆ every symbol gets stamped with it unless something inside the code overrides it. Bestie, this is such a glow-up for shared object libraries: it can very substantially improve linking and load times, produce more optimized code, give you near-perfect API export, and prevent symbol clashes. It is strongly recommended that you use this in any shared objects you distribute. Periodt.

Despite the nomenclature (fancy word, love that for us), default always means public โ€” like, 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. And if you don't specify -fvisibility at all, the default is default, i.e. make every symbol public ๐Ÿ™ˆ.

A good explanation of the benefits of correct ELF symbol visibility is in "How To Write Shared Libraries" by Ulrich Drepper, which you can find at <https://www.akkadia.org/drepper/> โ€” however, there's a superior solution this option makes possible: instead of marking things hidden when the default is public, you flip it and make the default hidden and mark things public. This is the norm with DLLs on Windows, and with -fvisibility=hidden plus "__attribute__ ((visibility("default")))" instead of "__declspec(dllexport)" you get almost identical semantics with identical syntax. Genuinely 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 โ€” you enclose the declarations you want to set visibility for with, for example, "#pragma GCC visibility push(hidden)" and "#pragma GCC visibility pop". Bear in mind: 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. Sorry, no hiding those ๐Ÿซถ.

Heads up: headers from outside your project โ€” in particular system headers and headers from any other library you use โ€” may not be expecting to be compiled with visibility other than the default. You may need to explicitly say "#pragma GCC visibility push(default)" before including any such headers.

"extern" declarations are not affected by -fvisibility, so a lot of code can be recompiled with -fvisibility=hidden with zero modifications. However โ€” and this is the catch โ€” it means 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. Which means, for instance, an exception class that is thrown between DSOs must be explicitly marked with default visibility so that the type_info nodes are unified between the DSOs. Iconic behaviour, honestly.

An overview of these techniques, their benefits and how to use them lives at <https://gcc.gnu.org/wiki/Visibility> โญ


-fstrict-volatile-bitfields โ€” use this if accesses to volatile bit-fields (or other structure fields, although the compiler usually honors those types anyway) should use a single access of the width of the field's type, aligned to a natural alignment if possible. For example, targets with memory-mapped peripheral registers might require all such accesses to be 16 bits wide; with this flag you can declare all peripheral bit-fields as "unsigned short" (assuming short is 16 bits on these targets) to force GCC to use 16-bit accesses instead of, perhaps, a more efficient 32-bit access.

If this option is disabled, the compiler uses the most efficient instruction. In the previous example, that might be a 32-bit load instruction โ€” even though that accesses bytes that 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 this case GCC falls back to generating multiple accesses rather than code that will fault or truncate the result at run time. No cap.

Note: Due to restrictions of the C/C++11 memory model, write accesses are not allowed to touch non bit-field members. It's therefore recommended to define all bits of the field's type as bit-field members ๐ŸŒธ.

The default value of this option is determined by the application binary interface for the target processor.


-fsync-libcalls โ€” this one controls whether any out-of-line instance of the "__sync" family of functions may be used to implement the C++11 "__atomic" family of functions.

The default value of this option is enabled, so the only useful form of the option is -fno-sync-libcalls. This option is used in the implementation of the libatomic runtime library โœจ.


๐Ÿ‘‘ GCC Developer Options ๐Ÿ‘‘

This section is for the GCC devs themselves โ€” options that are primarily of interest to GCC developers, including options to support compiler testing and investigation of compiler bugs and compile-time performance problems. That includes options that produce debug dumps at various points in the compilation, options that print statistics such as memory use and execution time, and options that print information about GCC's configuration, such as where it searches for libraries. Bestie, you should rarely need any of these for ordinary compilation and linking tasks. This is backstage-pass territory ๐ŸŽ€.

Many developer options that cause GCC to dump output to a file take an optional =filename suffix. You can specify stdout or - to dump to standard output, and stderr for standard error.

If =filename is omitted, a default dump file name is constructed by concatenating the base dump file name, a pass number, phase letter, and pass name. The base dump file name is the name of the output file produced by the compiler if explicitly specified and not an executable; otherwise it'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 a list of comma-separated markers is additionally specified. When the "su" marker is specified, the callgraph is decorated with stack usage information โ€” it's equivalent to -fstack-usage. When the "da" marker is specified, the callgraph is decorated with information about dynamically allocated objects.

When compiling with -flto, no callgraph information is output along with the object file. At LTO link time, -fcallgraph-info may generate multiple callgraph information files next to intermediate LTO output files ๐Ÿ’–.


-dletters -fdump-rtl-pass -fdump-rtl-pass=filename

Says to make debugging dumps during compilation at times specified by letters. This is used for debugging the RTL-based passes of the compiler.

Some -dletters switches have different meaning when -E is used for preprocessing.

Debug dumps can be enabled with a -fdump-rtl switch or some -d option letters. Here are the possible letters for use in pass and letters, and their meanings ๐Ÿ‘‡

  • -fdump-rtl-alignments โ€” Dump after branch alignments have been computed.
  • -fdump-rtl-asmcons โ€” Dump after fixing rtl statements that have unsatisfied in/out constraints.
  • -fdump-rtl-auto_inc_dec โ€” Dump after auto-inc-dec discovery. This pass is only run on architectures that have auto inc or auto dec instructions.
  • -fdump-rtl-barriers โ€” Dump after cleaning up the barrier instructions.
  • -fdump-rtl-bbpart โ€” Dump after partitioning hot and cold basic blocks.
  • -fdump-rtl-bbro โ€” Dump after block reordering.
  • -fdump-rtl-btl1, -fdump-rtl-btl2 โ€” these 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 enable dumping after the three if conversion passes.
  • -fdump-rtl-cprop_hardreg โ€” Dump after hard register copy propagation.
  • -fdump-rtl-csa โ€” Dump after combining stack adjustments.
  • -fdump-rtl-cse1, -fdump-rtl-cse2 โ€” these enable dumping after the two common subexpression elimination passes.
  • -fdump-rtl-dce โ€” Dump after the standalone dead code elimination passes.
  • -fdump-rtl-dbr โ€” Dump after delayed branch scheduling.
  • -fdump-rtl-dce1, -fdump-rtl-dce2 โ€” these enable dumping after the two dead store elimination passes.
  • -fdump-rtl-eh โ€” Dump after finalization of EH handling code.
  • -fdump-rtl-eh_ranges โ€” Dump after conversion of EH handling range regions.
  • -fdump-rtl-expand โ€” Dump after RTL generation.
  • -fdump-rtl-fwprop1, -fdump-rtl-fwprop2 โ€” bestie these two turn on dumping right after the two forward propagation passes ๐Ÿ’–
  • -fdump-rtl-gcse1, -fdump-rtl-gcse2 โ€” these enable dumping after global common subexpression elimination โœจ
  • -fdump-rtl-init-regs โ€” dump after the registers get initialized ๐ŸŽ€
  • -fdump-rtl-initvals โ€” dump after the initial value sets are computed ๐Ÿฆ‹
  • -fdump-rtl-into_cfglayout โ€” dump after converting to cfglayout mode, slay ๐Ÿ’…
  • -fdump-rtl-ira โ€” dump after iterated register allocation ๐ŸŒธ
  • -fdump-rtl-jump โ€” dump after the second jump optimization ๐Ÿซถ
  • -fdump-rtl-loop2 โ€” this one enables dumping after the rtl loop optimization passes ๐Ÿ”ฅ
  • -fdump-rtl-mach โ€” dump after the machine dependent reorganization pass runs โ€” but only if that pass even exists on your target, iykyk ๐Ÿ‘‘
  • -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 enable dumping after the basic block scheduling passes โœจ
  • -fdump-rtl-ree โ€” dump after sign/zero extension elimination ๐Ÿฆ‹
  • -fdump-rtl-seqabstr โ€” dump after common sequence discovery ๐Ÿ’…
  • -fdump-rtl-shorten โ€” dump after shortening branches ๐ŸŒธ
  • -fdump-rtl-sibling โ€” dump after sibling call optimizations ๐Ÿซถ
  • -fdump-rtl-split1, -fdump-rtl-split2, -fdump-rtl-split3, -fdump-rtl-split4, -fdump-rtl-split5 โ€” these bad boys enable dumping after five whole rounds of instruction splitting, periodt ๐Ÿ”ฅ
  • -fdump-rtl-sms โ€” dump after modulo scheduling. heads up tho: this pass is only run on some architectures ๐Ÿ™ˆ
  • -fdump-rtl-stack โ€” dump after converting from GCC's "flat register file" registers to the x87's stack-like registers. and ngl, this pass is only run on x86 variants ๐Ÿ‘‘
  • -fdump-rtl-subreg1, -fdump-rtl-subreg2 โ€” these two enable dumping after the two subreg expansion passes ๐ŸŒˆ
  • -fdump-rtl-unshare โ€” dump after all rtl has been unshared โญ
  • -fdump-rtl-vartrack โ€” dump after variable tracking ๐Ÿ’œ
  • -fdump-rtl-vregs โ€” dump after converting virtual registers to hard registers ๐Ÿงš
  • -fdump-rtl-web โ€” dump after live range splitting ๐Ÿ’–
  • -fdump-rtl-regclass, -fdump-rtl-subregs_of_mode_init, -fdump-rtl-subregs_of_mode_finish, -fdump-rtl-dfinit, -fdump-rtl-dfinish โ€” okay so these dumps are defined but they always produce empty files ๐Ÿ˜ญ like literally nothing in them, that's the whole vibe
  • -da, -fdump-rtl-all โ€” produce all the dumps listed above. all of them. the whole collection ๐ŸŽ€
  • -dA โ€” annotate the assembler output with miscellaneous debugging information โœจ
  • -dD โ€” dump all macro definitions at the end of preprocessing, on top of the normal output ๐Ÿฆ‹
  • -dH โ€” produce a core dump whenever an error occurs ๐Ÿ’€ dramatic but okay
  • -dp โ€” annotate the assembler output with a comment indicating which pattern and alternative is used. the length and cost of each instruction also get printed ๐Ÿ’…
  • -dP โ€” dump the RTL in the assembler output as a comment before each instruction. this one also turns on -dp annotation ๐ŸŒธ
  • -dx โ€” just generate RTL for a function instead of compiling it. usually you'd pair it with -fdump-rtl-expand ๐Ÿซถ

  • -fdump-debug โ€” dump the debugging information generated during the debug generation phase ๐Ÿ”ฅ
  • -fdump-earlydebug โ€” dump the debugging information generated during the early debug generation phase โญ
  • -fdump-noaddr โ€” when you're doing debugging dumps, this suppresses address output. the whole point? it makes it way more feasible to run diff on debugging dumps from compiler invocations that use different compiler binaries and/or different text / bss / data / heap / stack / dso start locations ๐Ÿ’œ
  • -freport-bug โ€” collects and dumps debug information into a temporary file if an internal compiler error (ICE) occurs. honestly a lifesaver when things go sideways ๐Ÿ˜ญ
  • -fdump-unnumbered โ€” when doing debugging dumps, this suppresses instruction numbers and address output. again, this makes using diff on debugging dumps way more feasible for compiler invocations with different options โ€” especially with and without -g ๐Ÿงš
  • -fdump-unnumbered-links โ€” when doing debugging dumps (see the -d option up there โ†‘), this suppresses instruction numbers for the links to the previous and next instructions in a sequence ๐ŸŽ€
  • -fdump-ipa-switch, -fdump-ipa-switch-options โ€” these control the dumping at various stages of the 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 gets 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 โ€” creates a dump file with info about the 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 which create live-patches can figure out 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 the 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 โ€” these control the dumping of language-specific information. the options and filename portions behave exactly as described in the -fdump-tree option. the following switch values are accepted:
    • all โ€” enable all language-specific dumps โญ
    • class โ€” dump class hierarchy information. virtual table information is emitted unless 'slim' is specified. this option is applicable to C++ only ๐Ÿ’…
    • module โ€” dump module information. options lineno (locations), graph (reachability), blocks (clusters), uid (serialization), alias (mergeable), asmname (Elrond), eh (mapper) & vops (macros) may provide additional information. this option is applicable to C++ only ๐ŸŒธ
    • raw โ€” dump the raw internal tree data. this option is applicable to C++ only ๐Ÿซถ
  • -fdump-passes โ€” prints on stderr the list of optimization passes that are turned on and off by the current command-line options. lowkey a cheat code for knowing what's actually happening ๐Ÿ”ฅ
  • -fdump-statistics-option โ€” enable and control dumping of pass statistics in a separate file. the file name is generated by appending a suffix ending in .statistics to the source file name, and the file is created in the same directory as the output file. if the -option form is used, -stats causes counters to be summed over the whole compilation unit while -details dumps every event as the passes generate them. the default with no option is to sum counters for each function compiled ๐Ÿ‘‘
  • -fdump-tree-all, -fdump-tree-switch, -fdump-tree-switch-options, -fdump-tree-switch-options=filename โ€” okay so these bad boys let you control the dumping at basically every stage of processing the intermediate language tree, straight into a file. ๐Ÿ’– If you use the -options form, then options is a list of - separated options that control the details of the dump. Lowkey not every option works for every dump tho โ€” the ones that aren't meaningful just get silently ignored, no drama. Here's the full menu of what you can pick:
    • address โ€” prints the address of every node. Ngl this is usually not meaningful bc it shifts around depending on your environment and source file. Its main character energy is in tying a dump file to a debug environment.
    • asmname โ€” if DECL_ASSEMBLER_NAME has been set for a given decl, use that in the dump instead of DECL_NAME. Its whole point is making it easy to work backward from mangled names in the assembly file. iykyk.
    • slim โ€” when you're dumping front-end intermediate representations, this stops the dumping of members of a scope or body of a function just because that scope has been reached. It only dumps those items when they're directly reachable by some other path. When dumping pretty-printed trees, this option stops the bodies of control structures from being dumped. When dumping RTL, it prints the RTL in slim (condensed) form instead of the default LISP-like representation. slay.
    • raw โ€” prints a raw representation of the tree. By default, trees get pretty-printed into a C-like representation.
    • details โ€” enables more detailed dumps (not honored by every dump option, sad). Also pulls in information from the optimization passes.
    • stats โ€” enables dumping of various statistics about the pass (again, not honored by every dump option).
    • blocks โ€” enables showing basic block boundaries (disabled in raw dumps).
    • graph โ€” for each of the other indicated dump files (-fdump-rtl-pass), it dumps a representation of the control flow graph that's suitable for viewing with GraphViz to file.passid.pass.dot. Each function in the file is pretty-printed as a subgraph, so GraphViz can render them all in a single plot. ๐Ÿ’… Heads up: this option currently only works for RTL dumps, and the RTL is always dumped in slim form.
    • vops โ€” enables showing virtual operands for every statement.
    • lineno โ€” enables showing line numbers for statements.
    • uid โ€” enables showing the unique ID (DECL_UID) for each variable.
    • verbose โ€” enables showing the tree dump for each statement.
    • eh โ€” enables showing the EH region number holding each statement.
    • scev โ€” enables showing scalar evolution analysis details.
    • optimized โ€” enables showing optimization information (only available in certain passes).
    • missed โ€” enables showing missed optimization information (only available in certain passes).
    • note โ€” enables 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.

โœจ So to figure out what tree dumps are even available, or to find the dump for a pass you're obsessed with, 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. For example, to enable the dump from the Early Value Range Propagation pass, invoke GCC with the -fdump-tree-evrp option. Optionally, you may specify the name of the dump file. If you don't specify one, GCC creates 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. ๐Ÿซถ Note that the numeric codes are not stable and may change from one version of GCC to another โ€” so don't hardcode them, bestie.

  • -fopt-info, -fopt-info-options, -fopt-info-options=filename โ€” controls optimization dumps from the various optimization passes. ๐Ÿ’œ If you use the -options form, options is a list of - separated option keywords that pick the dump details and optimizations.

The 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 if there's any conflict, the later options override the earlier ones on the command line. Periodt.

๐ŸŒˆ Which kinds of messages get emitted

  • optimized โ€” prints info 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 got successfully vectorized. ๐Ÿ‘‘
  • missed โ€” prints info about missed optimizations. Individual passes control which info goes into the output.
  • note โ€” prints verbose info about optimizations, like certain transformations and more detailed messages about decisions etc.
  • all โ€” prints detailed optimization information. This includes optimized, missed, and note.

๐ŸŽ€ The verbosity knob

  • internals โ€” by default only "high-level" messages get emitted. This option enables extra, more detailed messages, which are likely only interesting to GCC developers. Fr fr, it's giving deep lore.

๐Ÿฆ‹ Which optimizations to include

One or more of these keywords can 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, leaving out 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 goes out onto stderr. Even though multiple -fopt-info options are accepted, only one of them can include a filename. If other filenames are provided, then all but the first such option are ignored. ๐Ÿ™ˆ

Note that the output filename gets overwritten in the case of multiple translation units. If you want a combined output from multiple translation units, use stderr instead. ๐Ÿ’€

In the following example, the optimization info goes to stderr:

gcc -O3 -fopt-info

This example:

gcc -O3 -fopt-info-missed=missed.all

outputs a 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. 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 doesn't 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.

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, and it 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 @ me.

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 these extra bits of data for each message:

  • the execution count of the code being optimized, along with metadata about whether this came from actual profile data or was just an estimate, letting consumers prioritize messages by code hotness, ๐Ÿ”ฅ
  • the function name of the code being optimized, where applicable,
  • the "inlining chain" for the code being optimized, so that when a function is inlined into several different places (which might themselves be inlined), the reader can tell the copies apart,
  • objects identifying those parts of the message that refer to expressions, statements or symbol-table nodes, which of these categories they are, and, when available, their source code location,
  • the GCC pass that emitted the message, and
  • the location in GCC's own code from which the message was emitted.

Additionally, some messages are logically nested within other messages, reflecting implementation details of the optimization passes. ๐ŸŽ€

  • -fsched-verbose=n โ€” on targets that actually use instruction scheduling, this controls how much debugging output the scheduler prints into the dump files. For n greater than zero, -fsched-verbose outputs the same info as -fdump-rtl-sched1 and -fdump-rtl-sched2. For n greater than one, it also outputs basic block probabilities, detailed ready list information and unit/insn info. For n greater than two, it includes RTL at abort point, control-flow and regions info. And for n over four, -fsched-verbose also includes dependence info. scheduler lore unlocked ๐Ÿ’…
  • -fenable-kind-pass, -fdisable-kind-pass=range-list โ€” this is the whole set of options used to explicitly disable/enable optimization passes. Important vibe check: these are intended for use for debugging GCC. Compiler users should use regular options for enabling/disabling passes instead.
    • -fdisable-ipa-pass โ€” Disable IPA pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended with a sequential number starting from 1.
    • -fdisable-rtl-pass, -fdisable-rtl-pass=range-list โ€” Disable RTL pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended with a sequential number starting from 1. range-list is a comma-separated list of function ranges or assembler names. Each range is a number pair separated by a colon. The range is inclusive in both ends. If the range is trivial, the number pair can be simplified as a single number. If the function's call graph node's uid falls within one of the specified ranges, the pass is disabled for that function. The uid is shown in the function header of a dump file, and the pass names can be dumped by using option -fdump-passes.
    • -fdisable-tree-pass, -fdisable-tree-pass=range-list โ€” Disable tree pass pass. See -fdisable-rtl for the description of option arguments.
    • -fenable-ipa-pass โ€” Enable IPA pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended with a sequential number starting from 1.
    • -fenable-rtl-pass, -fenable-rtl-pass=range-list โ€” Enable RTL pass pass. See -fdisable-rtl for option argument description and examples.
    • -fenable-tree-pass, -fenable-tree-pass=range-list โ€” Enable tree pass pass. See -fdisable-rtl for the description of option arguments.

Here are some examples showing uses of these options โ€” copy these exactly, bestie:

                   # disable ccp1 for all functions
                      -fdisable-tree-ccp1
                   # disable complete unroll for function whose cgraph node uid is 1
                      -fenable-tree-cunroll=1
                   # disable gcse2 for functions at the following ranges [1,1],
                   # [300,400], and [400,1000]
                   # disable gcse2 for functions foo and foo2
                      -fdisable-rtl-gcse2=foo,foo2
                   # disable early inlining
                      -fdisable-tree-einline
                   # disable ipa inlining
                      -fdisable-ipa-inline
                   # enable tree full unroll
                      -fenable-tree-unroll
  • -fchecking, -fchecking=n โ€” Enable internal consistency checking. The default depends on the compiler configuration. -fchecking=2 enables further internal consistency checking that might affect code generation. so yes, it can change the output โ€” respect it ๐Ÿซถ
  • -frandom-seed=string โ€” This option provides a seed that GCC uses in place of random numbers in generating certain symbol names that have to be different in every compiled file. It is also used to place unique stamps in coverage data files and the object files that produce them. You can use the -frandom-seed option to produce reproducibly identical object files. The string can either be a number (decimal, octal or hex) or an arbitrary string (in which case it's converted to a number by computing CRC32). The string should be different for every file you compile. reproducible build girlies stay winning โœจ
  • -save-temps โ€” Store the usual "temporary" intermediate files permanently; name them as auxiliary output files, as specified described under -dumpbase and -dumpdir. When used in combination with the -x command-line option, -save-temps is sensible enough to avoid overwriting an input source file with the same extension as an intermediate file. The corresponding intermediate file may be obtained by renaming the source file before using -save-temps.
  • -save-temps=cwd โ€” Equivalent to -save-temps -dumpdir ./. short and iconic ๐Ÿ’…
  • -save-temps=obj โ€” Equivalent to -save-temps -dumpdir outdir/, where outdir/ is the directory of the output file specified after the -o option, including any directory separators. If the -o option is not used, the -save-temps=obj switch behaves like -save-temps=cwd.
  • -time[=file] โ€” Report the CPU time taken by each subprocess in the compilation sequence. For C source files, this is the compiler proper and assembler (plus the linker if linking is done). Without the specification of an output file, the output looks like this:
        # cc1 0.12 0.01
        # as 0.00 0.01

The first number on each line is the "user time", that is time spent executing the program itself. The second number is "system time", time spent executing operating system routines on behalf of the program. Both numbers are in seconds.

With the specification of an output file, the output is appended to the named file, and it looks like this:

        0.12 0.01 cc1 <options>
        0.00 0.01 as <options>

The "user time" and the "system time" are moved before the program name, and the options passed to the program are displayed, so that one can later tell what file was being compiled, and with which options. receipts: kept ๐Ÿ“

  • -fdump-final-insns[=file] โ€” Dump the final internal representation (RTL) to file. If the optional argument is omitted (or if file is .), the name of the dump file is determined by appending .gkd to the dump base name, see -dumpbase.
  • -fcompare-debug[=opts] โ€” If no error occurs during compilation, run the compiler a second time, adding opts and -fcompare-debug-second to the arguments passed to the second compilation. Dump the final internal representation in both compilations, and print an error if they differ. If the equal sign is omitted, the default -gtoggle is used. The environment variable GCC_COMPARE_DEBUG, if defined, non-empty and nonzero, implicitly enables -fcompare-debug. If GCC_COMPARE_DEBUG is defined to a string starting with a dash, then it is used for opts, otherwise the default -gtoggle is used. -fcompare-debug=, with the equal sign but without opts, is equivalent to -fno-compare-debug, which disables the dumping of the final representation and the second compilation, preventing even GCC_COMPARE_DEBUG from taking effect. To verify full coverage during -fcompare-debug testing, set GCC_COMPARE_DEBUG to say -fcompare-debug-not-overridden, which GCC rejects as an invalid option in any actual compilation (rather than preprocessing, assembly or linking). To get just a warning, setting GCC_COMPARE_DEBUG to -w%n-fcompare-debug not overridden will do. this is compiler-dev deep magic, no cap ๐Ÿงš
  • -fcompare-debug-second โ€” This option is implicitly passed to the compiler for the second compilation requested by -fcompare-debug, along with options to silence warnings, and omitting other options that would cause the compiler to produce output to files or to standard output as a side effect. Dump files and preserved temporary files are renamed so as to contain the .gk additional extension during the second compilation, to avoid overwriting those generated by the first. When this option is passed to the compiler driver, it causes the first compilation to be skipped, which makes it useful for little other than debugging the compiler proper.
  • -gtoggle โ€” Turn off generation of debug info, if leaving out this option generates it, or turn it on at level 2 otherwise. The position of this argument in the command line does not matter; it takes effect after all other options are processed, and it does so only once, no matter how many times it is given. This is mainly intended to be used with -fcompare-debug. one toggle, one job ๐Ÿ’…
  • -fvar-tracking-assignments-toggle โ€” Toggle -fvar-tracking-assignments, in the same way that -gtoggle toggles -g.
  • -Q โ€” Makes the compiler print out each function name as it is compiled, and print some statistics about each pass when it finishes. chaotic but useful โœจ
  • -ftime-report โ€” Makes the compiler print some statistics about the time consumed by each pass when it finishes.
  • -ftime-report-details โ€” Record the time consumed by infrastructure parts separately for each pass.
  • -fira-verbose=n โ€” Control the verbosity of the dump file for the integrated register allocator. The default value is 5. If the value n is greater or equal to 10, the dump output is sent to stderr using the same format as n minus 10.
  • -flto-report โ€” Prints a report with internal details on the workings of the link-time optimizer. The contents of this report vary from version to version. It is meant to be useful to GCC developers when processing object files in LTO mode (via -flto). Disabled by default.
  • -flto-report-wpa โ€” Like -flto-report, but only print for the WPA phase of link-time optimization.
  • -fmem-report โ€” Makes the compiler print some statistics about permanent memory allocation when it finishes.
  • -fmem-report-wpa โ€” Makes the compiler print some statistics about permanent memory allocation for the WPA phase only.
  • -fpre-ipa-mem-report, -fpost-ipa-mem-report โ€” Makes the compiler print some statistics about permanent memory allocation before or after interprocedural optimization.
  • -fmultiflags โ€” This option enables multilib-aware "TFLAGS" to be used to build target libraries with options different from those the compiler is configured to use by default, through the use of specs.

Like TFLAGS, this lets the target libraries get built for portable baseline environments while the compiler itself defaults to the more demanding ones. Thatโ€™s lowkey useful because users can easily override the defaults the compiler is configured to use to build their own programs โ€” if those defaults arenโ€™t ideal for their target environment โ€” whereas rebuilding the runtime libraries is usually not as easy or desirable. ๐Ÿ’…

Unlike TFLAGS, using specs lets different flags get selected for different multilibs. The way to accomplish that is to 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. (iykyk ๐Ÿซถ)

Itโ€™s also useful to check that TFLAGS are being used to build all target libraries, by configuring a non-bootstrap compiler with --with-specs='%{!fmultiflags:%emissing TFLAGS}' and building the compiler and target libraries. ๐ŸŒˆ

  • -fprofile-report โ€” makes the compiler print some statistics about consistency of the (estimated) profile and effect of individual passes. Itโ€™s giving โ€œreport card for your optimization eraโ€ ๐Ÿ“Š
  • -fstack-usage โ€” makes the compiler output stack usage information for the program, on a per-function basis. The filename for the dump is made by appending .su to the auxname. auxname is generated from the name of the output file, if explicitly specified and it is not an executable, otherwise it is the basename of the source file. An entry is made up of three fields:
    • the name of the function.
    • a number of bytes.
    • one or more qualifiers: static, dynamic, bounded.

The qualifier static means that the function manipulates the stack statically: a fixed number of bytes are allocated for the frame on function entry and released on function exit; no stack adjustments are otherwise made in the function. The second field is this fixed number of bytes.

The qualifier dynamic means that the function manipulates the stack dynamically: in addition to the static allocation described above, stack adjustments are made in the body of the function, for example to push/pop arguments around function calls. If the qualifier bounded is also present, 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 it is not present, the amount of these adjustments is not bounded at compile time and the second field only represents the bounded part. ๐Ÿซง

  • -fstats โ€” emit statistics about front-end processing at the end of the compilation. This option is supported only by the C++ front end, and the information is generally only useful to the G++ development team. ๐Ÿ‘‘
  • -fdbg-cnt-list โ€” print the name and the counter upper bound for all debug counters. Debug-counter tea, served hot โ˜•
  • -fdbg-cnt=counter-value-list โ€” set the internal debug counter lower and upper bound. counter-value-list is a comma-separated list of name:lower_bound1-upper_bound1 [:lower_bound2-upper_bound2...] tuples which sets the name of the counter and 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 second, third, fourth, tenth and eleventh invocation. For dbg_cnt(tail_call) true is returned for first 10 invocations. ๐Ÿ’€
  • -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. No cap, itโ€™s literally just the name ๐Ÿ“›
  • -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 -, without spaces between multiple switches. This is supposed to ease shell processing. ๐Ÿš
  • -print-multi-os-directory โ€” print the path to OS libraries for the selected multilib, relative to some lib subdirectory. If OS libraries are present in the lib subdirectory and no multilibs are used, this is usually just ., if OS libraries are present in libsuffix sibling directories this prints e.g. ../lib64, ../lib or ../lib32, or if OS libraries are present in lib/subdir subdirectories it prints e.g. amd64, sparcv9 or ev6. ๐Ÿ—‚๏ธ
  • -print-multiarch โ€” print the path to OS libraries for the selected multiarch, relative to some lib subdirectory.
  • -print-prog-name=program โ€” like -print-file-name, but searches for a program such as cpp. Finding programs core ๐Ÿ”Ž
  • -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. You can do:

gcc -nostdlib <files>... `gcc -print-libgcc-file-name`
  • -print-search-dirs โ€” print the name of the configured installation directory and a list of program and library directories gcc searches โ€” and donโ€™t do anything else.

This is useful when gcc prints the error message installation problem, cannot exec cpp0: No such file or directory. To resolve this you either need to put cpp0 and the other compiler components where gcc expects to find them, or you can set the environment variable GCC_EXEC_PREFIX to the directory where you installed them. Donโ€™t forget the trailing /. ๐Ÿšจ

  • -print-sysroot โ€” print the target sysroot directory that is 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. ๐ŸŒซ๏ธ
  • -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. ๐ŸŽ€
  • -dumpmachine โ€” print the compilerโ€™s target machine (for example, i686-pc-linux-gnu) โ€” and donโ€™t do anything else.
  • -dumpversion โ€” print the compiler version (for example, 3.0, 6.3.0 or 7) โ€” and donโ€™t do anything else. This is the compiler version used in filesystem paths and specs. Depending on how the compiler has been configured it can be just a single number (major version), two numbers separated by a dot (major and minor version) or three numbers separated by dots (major, minor and patchlevel version). ๐Ÿ”ข
  • -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. โœจ
  • -dumpspecs โ€” print the compilerโ€™s built-in specs โ€” and donโ€™t do anything else. (This is used when GCC itself is being built.) ๐Ÿ› ๏ธ

๐Ÿ› ๏ธ Machine-Dependent Options ๐Ÿ› ๏ธ

Each target machine supported by GCC can have its own options โ€” for example, to allow you to 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. ๐Ÿงš

Some configurations of the compiler also support additional target-specific options, usually for compatibility with other compilers on the same platform. ๐Ÿ’–

๐Ÿฆ‹ AArch64 Options ๐Ÿฆ‹

These options are defined for AArch64 implementations:

  • -mabi=name โ€” generate code for the specified data model. Permissible values are ilp32 for SysV-like data model where int, long int and pointers are 32 bits, and lp64 for 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 ๐Ÿšซ

  • -mbig-endian โ€” generate big-endian code. This is the default when GCC is configured for an aarch64_be-*-* target.
  • -mgeneral-regs-only โ€” generate code which uses only the general-purpose registers. This will prevent the compiler from using floating-point and Advanced SIMD registers but will not impose any restrictions on the assembler. ๐Ÿ’…
  • -mlittle-endian โ€” generate little-endian code. This is the default when GCC is configured for an aarch64-*-* but not an aarch64_be-*-* target.
  • -mcmodel=tiny โ€” generate code for the tiny code model. The program and its statically defined symbols must be within 1MB of each other. Programs can be statically or dynamically linked.
  • -mcmodel=small โ€” generate code for the small code model. The program and its statically defined symbols must be within 4GB of each other. Programs can be statically or dynamically linked. This is the default code model. ๐Ÿ‘‘
  • -mcmodel=large โ€” generate code for the large code model. This makes no assumptions about addresses and sizes of sections. Programs can be statically linked only. The -mcmodel=large option is incompatible with -mabi=ilp32, -fpic and -fPIC. ๐Ÿ’€
  • -mstrict-align, -mno-strict-align โ€” avoid or allow generating memory accesses that may not be aligned on a natural object boundary as described in the architecture specification. ๐Ÿ“
  • -momit-leaf-frame-pointer, -mno-omit-leaf-frame-pointer โ€” omit or keep the frame pointer in leaf functions. The former behavior is the default. ๐Ÿƒ
  • -mstack-protector-guard=guard, -mstack-protector-guard-reg=reg, -mstack-protector-guard-offset=offset โ€” generate stack protection code using canary at guard. Supported locations are global for a global canary or sysreg for a canary in an appropriate system register.

With the latter choice the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which system register to use as base register for reading the canary, and from what offset from that base register. There is no default register or offset as this is entirely for use within the Linux kernel. ๐Ÿง

  • -mtls-dialect=desc โ€” use TLS descriptors as the thread-local storage mechanism for dynamic accesses of TLS variables. This is the default. ๐Ÿงต
  • -mtls-dialect=traditional โ€” bestie, this tells it to use traditional TLS as the thread-local storage mechanism whenever it does dynamic accesses of TLS variables. Old school, but it works ๐Ÿ’…
  • -mtls-size=size โ€” sets the bit size of immediate TLS offsets. Valid values are 12, 24, 32, 48. Heads up though: this one needs binutils 2.26 or newer, no cap โœจ
  • -mfix-cortex-a53-835769, -mno-fix-cortex-a53-835769 โ€” turns the workaround for the ARM Cortex-A53 erratum number 835769 on or off. What does the workaround do, you ask? It literally inserts a NOP instruction between memory instructions and 64-bit integer multiply-accumulate instructions. Iconic little band-aid ๐Ÿฉน
  • -mfix-cortex-a53-843419, -mno-fix-cortex-a53-843419 โ€” same energy, different erratum: enables or disables the workaround for the ARM Cortex-A53 erratum number 843419. Plot twist: this workaround is made at link time, so all this does is pass the corresponding flag to the linker. Middle-man behavior fr fr ๐Ÿ˜ญ
  • -mlow-precision-recip-sqrt, -mno-low-precision-recip-sqrt โ€” enables or disables the reciprocal square root approximation. Lowkey important: this option only has an effect if -ffast-math or -funsafe-math-optimizations is used as well. Enabling it reduces precision of reciprocal square root results to about 16 bits for single precision and to 32 bits for double precision. So, faster but slightly blurrier ๐Ÿฆ‹
  • -mlow-precision-sqrt, -mno-low-precision-sqrt โ€” enables or disables the square root approximation. Same deal: it only has an effect if -ffast-math or -funsafe-math-optimizations is used as well. Enabling reduces precision of square root results to about 16 bits for single precision and to 32 bits for double precision. And the fun part โ€” if enabled, it implies -mlow-precision-recip-sqrt ๐ŸŽ€
  • -mlow-precision-div, -mno-low-precision-div โ€” enables or disables the division approximation. You already know the rule: only has an effect if -ffast-math or -funsafe-math-optimizations is used as well. Enabling reduces precision of division results to about 16 bits for single precision and to 32 bits for double precision โœจ
  • -mtrack-speculation, -mno-track-speculation โ€” enables or disables generation of extra code to track speculative execution through conditional branches. The tracking state can then be used by the compiler when expanding calls to __builtin_speculation_safe_copy so it can generate a more efficient code sequence. Detective mode ๐Ÿ”
  • -moutline-atomics, -mno-outline-atomics โ€” enables or disables calls to out-of-line helpers to implement atomic operations. These helpers will, at runtime, figure out if the LSE instructions from ARMv8.1-A can be used; if not, they'll fall back to the load/store-exclusive instructions that are present in the base ARMv8.0 ISA. Adaptive queen ๐Ÿ‘‘

Also: this option is only applicable when compiling for the base ARMv8.0 instruction set. If you're using a later revision, e.g. -march=armv8.1-a or -march=armv8-a+lse, the ARMv8.1-Atomics instructions will be used directly. Same applies when using -mcpu= and the selected cpu supports the lse feature. And yes โ€” this option is on by default ๐Ÿ’–

  • -march=name โ€” specify the name of the target architecture and, optionally, one or more feature modifiers. The form is:
-march=arch{+[no]feature}*

Here's the run-down of permissible values for arch and the features they enable by default:

  • armv8-a : Armv8-A : includes +fp, +simd by default
  • armv8.1-a : Armv8.1-A : includes armv8-a, +crc, +lse, +rdma
  • armv8.2-a : Armv8.2-A : includes armv8.1-a
  • armv8.3-a : Armv8.3-A : includes armv8.2-a, +pauth
  • armv8.4-a : Armv8.4-A : includes armv8.3-a, +flagm, +fp16fml, +dotprod
  • armv8.5-a : Armv8.5-A : includes armv8.4-a, +sb, +ssbs, +predres
  • armv8.6-a : Armv8.6-A : includes armv8.5-a, +bf16, +i8mm
  • armv8.7-a : Armv8.7-A : includes armv8.6-a, +ls64
  • armv8.8-a : Armv8.8-a : includes armv8.7-a, +mops
  • armv9-a : Armv9-A : includes armv8.5-a, +sve, +sve2
  • armv9.1-a : Armv9.1-A : includes armv9-a, +bf16, +i8mm
  • armv9.2-a : Armv9.2-A : includes armv9.1-a, +ls64
  • armv9.3-a : Armv9.3-A : includes armv9.2-a, +mops
  • armv8-r : Armv8-R : includes armv8-r

The value native is available on native AArch64 GNU/Linux and causes the compiler to pick the architecture of the host system. Real talk though โ€” this option has no effect if the compiler is unable to recognize the architecture of the host system.

The permissible values for feature are listed in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Where conflicting feature modifiers are specified, the right-most feature is used. Right-most wins, always ๐Ÿ’…

GCC uses name to determine what kind of instructions it can emit when generating assembly code. And if -march is specified without either of -mtune or -mcpu also being specified, the code is tuned to perform well across a range of target processors implementing the target architecture. Versatile icon โœจ

  • -mtune=name โ€” specify the name of the target processor for which GCC should tune the performance of the code. Permissible values for this option are: generic, cortex-a35, cortex-a53, cortex-a55, cortex-a57, cortex-a72, cortex-a73, cortex-a75, cortex-a76, cortex-a76ae, cortex-a77, cortex-a65, cortex-a65ae, cortex-a34, cortex-a78, cortex-a78ae, cortex-a78c, ares, exynos-m1, emag, falkor, neoverse-512tvb, neoverse-e1, neoverse-n1, neoverse-n2, neoverse-v1, neoverse-v2, grace, qdf24xx, saphira, phecda, xgene1, vulcan, octeontx, octeontx81, octeontx83, octeontx2, octeontx2t98, octeontx2t96 octeontx2t93, octeontx2f95, octeontx2f95n, octeontx2f95mm, a64fx, thunderx, thunderxt88, thunderxt88p1, thunderxt81, tsv110, thunderxt83, thunderx2t99, thunderx3t110, zeus, cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a73.cortex-a35, cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55, cortex-r82, cortex-x1, 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. Cute little duo ๐Ÿซถ

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 that 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 is more specific than the default tuning described below ๐Ÿ”ฅ

Additionally, on native AArch64 GNU/Linux systems the value native tunes performance to the host system. This option has no effect if the compiler is unable to recognize the processor of the host system.

Where none of -mtune=, -mcpu= or -march= are specified, the code is tuned to perform well across a range of target processors.

Heads up bestie: this option cannot be suffixed by feature modifiers. Periodt.
  • -mcpu=name โ€” specify the name of the target processor, optionally suffixed by one or more feature modifiers. The form is:
-mcpu=cpu{+[no]feature}*

where the permissible values for cpu are the same as those available for -mtune. The permissible values for feature are documented in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Where conflicting feature modifiers are specified, the right-most feature is used ๐Ÿ‘‘

GCC uses name to determine what kind of instructions it can emit when generating assembly code (as if by -march) and to determine the target processor for which to tune for performance (as if by -mtune). Where this option is used in conjunction with -march or -mtune, those options take precedence over the appropriate part of this option. They're the main characters here, ngl.

-mcpu=neoverse-512tvb is special in that it does not refer to a specific core, but instead refers to all Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits a cycle. Unless overridden by -march, -mcpu=neoverse-512tvb generates code that can run on a Neoverse V1 core, since Neoverse V1 is the first Neoverse core with these properties. And unless overridden by -mtune, -mcpu=neoverse-512tvb tunes code in the same way as for -mtune=neoverse-512tvb ๐Ÿ’œ

  • -moverride=string โ€” overrides tuning decisions made by the back-end in response to a -mtune= switch. Big caveat babe: the syntax, semantics, and accepted values for string in this option are not guaranteed to be consistent across releases. So don't get attached ๐Ÿ˜ญ

This option is only intended to be useful when developing GCC. It's for the devs, not for us.

  • -mverbose-cost-dump โ€” enables verbose cost model dumping in the debug dump files. This option is provided for use in debugging the compiler. Compiler-dev exclusive โœจ
  • -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. And fun fact: this is enabled by default for -mcmodel=tiny ๐ŸŽ€
  • -msign-return-address=scope โ€” select the function scope on which return address signing will be applied. Permissible values are none, which disables return address signing, non-leaf, which enables pointer signing for functions which are not leaf functions, and all, which enables pointer signing for all functions. The default value is none.
Ngl this one's been deprecated by -mbranch-protection. Upgrade your faves bestie ๐Ÿ’€
  • -mbranch-protection=none|standard|pac-ret[+leaf+b-key]|bti โ€” select the branch protection features to use. none is the default and turns off all types of branch protection. standard turns on all types of branch protection features โ€” and if a feature has additional tuning options, then standard sets it to its standard level. pac-ret[+leaf] turns on return address signing to its standard level: signing functions that save the return address to memory (non-leaf functions will practically always do this) using the a-key. The optional argument leaf can be used to extend the signing to include leaf functions. The optional argument b-key can be used to sign the functions with the B-key instead of the A-key. And bti turns on branch target identification mechanism. Protect yourself queen ๐Ÿ›ก๏ธ
  • -mharden-sls=opts โ€” enables compiler hardening against straight line speculation (SLS). opts is a comma-separated list of the following options:
    • retbr
    • blr

Ngl bestie, the SLS hardening situation is literally just two vibes: -mharden-sls=all turns every SLS hardening on, and -mharden-sls=none turns all of it off. That's the whole story, no cap. ๐Ÿ’…

  • -msve-vector-bits=bits โ€” tells GCC exactly how many bits live in an SVE vector register. Heads up though: this only does anything when SVE is actually enabled, so don't expect magic otherwise. โœจ

So here's the tea on SVE codegen: GCC supports two whole forms of it. There's "vector-length agnostic" output, which works no matter what size your vector register is, and "vector-length specific" output, which lets GCC make assumptions about the vector length whenever that's useful for optimization reasons. ๐ŸŽ€

The possible values of bits are: scalable, 128, 256, 512, 1024 and 2048. Pick scalable and you get vector-length agnostic output. Lowkey important: at present -msve-vector-bits=128 also generates vector-length agnostic output for big-endian targets. Every other value generates vector-length specific code. ๐Ÿฆ‹

Fr fr though: the behavior of these values may change in future releases, and no value except scalable should be relied on for producing code that's portable across different hardware SVE vector lengths. Like, don't build your whole personality on it. ๐Ÿ˜ญ

The default is -msve-vector-bits=scalable, which produces vector-length agnostic code. Iconic, honestly.

โœจ -march and -mcpu Feature Modifiers โœจ

Feature modifiers used with -march and -mcpu can be any of the following and their inverses nofeature. Yes bestie, every single one has an inverse, go wild. ๐Ÿ’œ

  • 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. Careful: 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. Same deal โ€” 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.

Feature crypto implies aes, sha2, and simd, which implies fp. Conversely, nofp implies nosimd, which implies nocrypto, noaes and nosha2. It's giving chain reaction, honestly. ๐ŸŒ€


๐ŸŒธ 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 allows code to run on hardware variants that lack these registers. Very "make it work on the cheap one" of it. ๐Ÿ’€
  • -mprefer-short-insn-regs โ€” preferentially allocate registers that allow short instruction generation. This can result in increased instruction count, so this may either reduce or increase overall code size. Coin flip energy, lowkey.
  • -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. Just... vibe padding. ๐ŸŽ€
  • -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 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.
Big warning bestie: this option changes the ABI; compiling a program with a different stack offset than the libraries have been compiled with generally does not work. This option can be useful if you want to evaluate if a different stack offset would give you better code, but to actually use a different stack offset to build working programs, it is recommended to configure the toolchain with the appropriate --with-stack-offset=num option. ๐Ÿ˜ญ
  • -mno-round-nearest โ€” make the scheduler assume that the rounding mode has been set to truncating. The default is -mround-nearest.
  • -mlong-calls โ€” if not otherwise specified by an attribute, assume all calls might be beyond the offset range of the b / bl instructions, and therefore load the function address into a register before performing a (otherwise direct) call. This is the default.
  • -mshort-calls โ€” if not otherwise specified by an attribute, assume all direct calls are in the range of the b / bl instructions, so use these instructions for direct calls. The default is -mlong-calls.
  • -msmall16 โ€” assume addresses can be loaded as 16-bit unsigned values. This does not apply to function addresses for which -mlong-calls semantics are in effect.
  • -mfp-mode=mode โ€” set the prevailing mode of the floating-point unit. This determines the floating-point mode that is provided and expected at function call and return time. Making this mode match the mode you predominantly need at function start can make your programs smaller and faster by avoiding unnecessary mode switches. Efficiency slay. โญ

mode can be set to one the following values:

  • caller โ€” any mode at function entry is valid, and retained or restored when the function returns, and when it calls other functions. This mode is useful for compiling libraries or other compilation units you might want to incorporate into different programs with different prevailing FPU modes, and the convenience of being able to use a single object file outweighs the size and speed overhead for any extra mode switching that might be needed, compared with what would be needed with a more specific choice of prevailing FPU mode. ๐Ÿซถ
  • truncate โ€” the mode for floating-point math that truncates, aka rounds toward zero ๐Ÿซถ and yeah, that includes converting from floating-point to integer.
  • round-nearest โ€” the mode for floating-point math with round-to-nearest-or-even rounding. classic, balanced, no drama ๐Ÿ’…
  • int โ€” the mode for doing integer math in the FPU, like integer multiply, or integer multiply-and-accumulate. yes bestie, the FPU does integers sometimes, it's giving versatile โœจ

The default is -mfp-mode=caller.


  • -mno-split-lohi, -mno-postinc, -mno-postmodify โ€” codegen tweaks that turn off, 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 โ€” switches the preferred SIMD mode to SImode. The default is -mvect-double, which uses DImode as the preferred SIMD mode.
  • -max-vect-align=num โ€” the maximum alignment for SIMD vector mode types. num can be 4 or 8. Default is 8. Heads up though โ€” this is an ABI change, even though lots of library function interfaces are unaffected if they don't use SIMD vector modes anywhere that messes with the size and/or alignment of the relevant types ๐Ÿ‘€
  • -msplit-vecmove-early โ€” splits vector moves into single word moves before reload. In theory this gives better register allocation, but so far the reverse seems to be generally the case. not the serve anyone expected ๐Ÿ˜ญ
  • -m1reg-reg โ€” pick a register to hold the constant -1, which makes loading small negative constants and certain bitmasks faster. Allowed values for reg are r43 and r63 (which mean use that register as a fixed register), and none (which means no register is used for this). The default is -m1reg-none.

๐ŸŒˆ AMD GCN Options

These options are defined specifically for the AMD GCN port.

  • -march=gpu
  • -mtune=gpu โ€” set the architecture type or tuning for gpu. Supported values for gpu are:
    • fiji โ€” compile for GCN3 Fiji devices (gfx803). Support deprecated; availability depends on how GCC has been configured, see --with-arch and --with-multilib-list.
    • 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. On some devices this feature can be enabled per-process. The compiled code must match the device mode. The default is any, for devices that support it.
  • -mstack-size=bytes โ€” how many bytes of stack space each GPU thread (wave-front) gets requested. Beware: there may be a lot of threads and only limited memory available ๐Ÿ˜ฌ The size of the stack allocation can also affect 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. Right now this option is a placeholder for support that is not yet implemented โ€” it's giving coming soon ๐ŸŽ€

๐Ÿน ARC Options

The following options control the architecture variant for which code is being compiled:

  • -mbarrel-shifter โ€” generate instructions supported by the barrel shifter. This is the default unless -mcpu=ARC601 or -mcpu=ARCEM is in effect.
  • -mjli-always โ€” force a call to a function using the jli_s instruction. Only valid for the ARCv2 architecture.
  • -mcpu=cpu โ€” set the 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 โ€” stop the lr and sr instructions from using FPX extension aux registers.
  • -mea โ€” generate extended arithmetic instructions. Currently only divaw, adds, subs, and sat16 are supported. Only valid for -mcpu=ARC700.
  • -mno-mpy โ€” don't 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. Only valid for -mcpu=ARC600.
  • -mnorm โ€” generate norm instructions. This is the default if -mcpu=ARC700 is in effect.
  • -mspfp
  • -mspfp-compact โ€” generate single-precision FPX instructions, tuned for the compact implementation.
  • -mspfp-fast โ€” generate single-precision FPX instructions, tuned for the fast implementation.
  • -msimd โ€” enable generation of ARC SIMD instructions via target-specific builtins. Only valid for -mcpu=ARC700.
  • -msoft-float โ€” this option is ignored; it's provided for compatibility purposes only. Software floating-point code is emitted by default, and that default can be overridden by the FPX options: -mspfp, -mspfp-compact, or -mspfp-fast for single precision, and -mdpfp, -mdpfp-compact, or -mdpfp-fast for double precision ๐Ÿซถ
  • -mswap โ€” generate swap instructions.
  • -matomic โ€” enables use of the locked load/store conditional extension to implement atomic memory built-in functions. Not available for ARC 6xx or ARC EM cores.
  • -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 the thread pointer register number.
  • -mmpy-option=multo โ€” compile ARCv2 code with a multiplier design option. You can specify multo as either a string or a numeric value. wlh1 is the default value. The recognized values are:
    • 0, none โ€” no multiplier available.
    • 1, w โ€” 16x16 multiplier, fully pipelined. Enables these instructions: mpyw and mpyuw.
    • 2, wlh1 โ€” 32x32 multiplier, fully pipelined (1 stage). Additionally enables: mpy, mpyu, mpym, mpymu, and mpy_s.
    • 3, wlh2 โ€” 32x32 multiplier, fully pipelined (2 stages). Additionally enables: mpy, mpyu, mpym, mpymu, and mpy_s.
    • 4, wlh3 โ€” two 16x16 multipliers, blocking, sequential. Additionally enables: mpy, mpyu, mpym, mpymu, and mpy_s.
    • 5, wlh4 โ€” one 16x16 multiplier, blocking, sequential. Additionally enables: mpy, mpyu, mpym, mpymu, and mpy_s.
    • 6, wlh5 โ€” one 32x4 multiplier, blocking, sequential. Additionally enables: mpy, mpyu, mpym, mpymu, and mpy_s.
    • 7, plus_dmpy โ€” ARC HS SIMD support.
    • 8, plus_macd โ€” ARC HS SIMD support.
    • 9, plus_qmacw โ€” ARC HS SIMD support.

This option is only available for ARCv2 cores.

  • -mfpu=fpu โ€” enables support for specific floating-point hardware extensions for ARCv2 cores. Supported values for fpu are:
    • fpus โ€” enables support for single-precision floating-point hardware extensions.
    • fpud โ€” enables support for double-precision floating-point hardware extensions. Single-precision floating-point extension is also enabled. Not available for ARC EM.
  • fpuda โ€” turns on support for double-precision floating-point hardware extensions via double-precision assist instructions ๐ŸŽ€ the single-precision floating-point extension gets switched on too. This one's only available for ARC EM, no cap.
  • fpuda_div โ€” same double-precision-assist deal, but bestie it also brings single-precision floating-point, square-root, and divide extensions along for the ride โœจ Only available for ARC EM.
  • fpuda_fma โ€” double-precision FP hardware extensions through double-precision assist instructions, plus single-precision floating-point and fused multiply and add hardware extensions are enabled too ๐Ÿ”ฅ Only available for ARC EM.
  • fpuda_all โ€” the whole double-precision assist situation, and all single-precision floating-point hardware extensions are enabled as well ๐Ÿ‘‘ 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. Heads up: 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 โ€” tells the compiler which general-purpose registers the processor automatically saves/restores on interrupt entry and exit ๐Ÿซถ register-range is written as two registers separated by a dash. The range always starts with "r0" and the upper limit is the "fp" register. blink and lp_count are optional. This option is only valid for ARC EM and ARC HS cores, periodt.
  • -mrgf-banked-regs=number โ€” sets how many registers get replicated in the second register bank when a fast interrupt comes in ๐Ÿงš Fast interrupts are the ones with the highest priority level P0. These interrupts save only the PC and STATUS32 registers, specifically to dodge memory transactions during interrupt entry and exit sequences. Use this when you're running fast interrupts on an ARC V2 family processor. 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. Default width is locked in at 32 bits. If the width is less than 32, the compiler won't try to transform loops in your program to use the zero-delay loop mechanism unless it knows the "lp_count" register can hold the required loop-counter value. Depending on the width you pick, the compiler and run-time library might still use the loop mechanism for various needs, so yeah. 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 ๐ŸŽ€ This option defines the "__ARC_RF16__" preprocessor macro.
  • -mbranch-index โ€” enables use of "bi" or "bih" instructions to implement jump tables ๐Ÿ”ฅ

The following options get passed straight through to the assembler, and they also define preprocessor macro symbols ๐Ÿ‘‡

  • -mdsp-packa โ€” passed down to the assembler to enable the DSP Pack A extensions. Also sets the preprocessor symbol "__Xdsp_packa". Heads up bestie: 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 gets annotated ๐Ÿ–๏ธ

  • -misize โ€” annotates 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 one's 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 is the 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 the generated code ๐Ÿง 

  • -mlong-calls โ€” generates calls as register indirect calls, which gives you access to the full 32-bit address range ๐Ÿ‘‘
  • -mmedium-calls โ€” don't use less than a 25-bit addressing range for calls, which is the offset available for an unconditional branch-and-link instruction. Conditional execution of function calls is suppressed so the 25-bit range can be used instead of the 21-bit range you'd get with conditional branch-and-link. This is the default for tool chains built for "arc-linux-uclibc" and "arceb-linux-uclibc" targets.
  • -G num โ€” puts definitions of externally-visible data in a small data section if that data is no bigger than num bytes. The default value of num is 4 for any ARC configuration, or 8 when there are double load/store operations ๐Ÿ’–
  • -mno-sdata โ€” don't generate sdata references. This is the default for tool chains built for "arc-linux-uclibc" and "arceb-linux-uclibc" targets.
  • -mvolatile-cache โ€” uses ordinarily cached memory accesses for volatile references. This is the default โญ
  • -mno-volatile-cache โ€” enables cache bypass for volatile references ๐Ÿฆ‹

The following options fine tune code generation, iykyk ๐Ÿ”ง

  • -malign-call โ€” does nothing. Preserved for backward compatibility ๐Ÿ™ˆ
  • -mauto-modify-reg โ€” enables the use of pre/post modify with register displacement.
  • -mbbit-peephole โ€” enables bbit peephole2.
  • -mno-brcc โ€” disables a target-specific pass in arc_reorg that generates compare-and-branch ("brcc") instructions. It has no effect on generation of these instructions driven by the combiner pass ๐Ÿ’…
  • -mcase-vector-pcrel โ€” uses PC-relative switch case tables so case tables can be shortened. This is the default for -Os โœจ
  • -mcompact-casesi โ€” enables the compact "casesi" pattern. This is the default for -Os, and it's only available for ARCv1 cores. Heads up: this option is deprecated ๐Ÿ’€
  • -mno-cond-exec โ€” disables the ARCompact-specific pass that generates conditional execution instructions.

Okay so, real talk: because of delay slot scheduling and the interactions between operand numbers, literal sizes, instruction lengths, and support for conditional execution, the target-independent pass for generating conditional execution is often lacking ๐Ÿ˜ญ That's why the ARC port keeps a special pass around that hunts for more conditional execution generation opportunities after register allocation, branch shortening, and delay slot scheduling have already happened. This pass generally (but not always!) improves performance and code size, at the cost of extra compilation time โ€” which is exactly why there's an option to switch it off. And if you're hitting problems with call instructions exceeding their allowable offset range because they got conditionalized, you should consider using -mmedium-calls instead ๐Ÿซถ

  • -mearly-cbranchsi โ€” enables pre-reload use of the "cbranchsi" pattern.
  • -mexpand-adddi โ€” expands "adddi3" and "subdi3" at RTL generation time into "add.f", "adc" etc. This option is deprecated ๐Ÿ’€
  • -mindexed-loads โ€” enables the use of indexed loads. Lowkey this can be problematic, because some optimizers then assume indexed stores exist โ€” which is not the case ๐Ÿ˜ฌ
  • -mlra โ€” enables Local Register Allocation. This is still experimental for ARC, so by default the compiler uses standard reload (i.e. -mno-lra).
  • -mlra-priority-none โ€” don't indicate any priority for target registers.
  • -mlra-priority-compact โ€” indicate target register priority for r0..r3 / r12..r15.
  • -mlra-priority-noncompact โ€” reduce target register priority for r0..r3 / r12..r15.
  • -mmillicode โ€” when optimizing for size (using -Os), prologues and epilogues that have to save or restore a large number of registers often get shortened by calling a special function in libgcc โ€” that's called a millicode call ๐ŸŽ€ Since these calls can pose performance issues and/or cause linking issues when you link in a nonstandard way, this option exists so you can turn millicode call generation on or off.
  • -mcode-density-frame โ€” lets the compiler emit "enter" and "leave" instructions. These are only valid for CPUs with the code-density feature ๐Ÿ”ฅ
  • -mmixed-code โ€” does nothing. Preserved for backward compatibility ๐Ÿ™ˆ
  • -mq-class โ€” bestie, this oneโ€™s deprecated ๐Ÿซ . It enables q instruction alternatives, and itโ€™s the default for -Os.
  • -mRcq โ€” literally does nothing. Preserved for backward compatibility, periodt. ๐Ÿ’€
  • -mRcw โ€” also does nothing. Preserved for backward compatibility. We love a harmless icon. โœจ
  • -msize-level=level โ€” fine-tune size optimization with regards to instruction lengths and alignment. The recognized values for level are:
    • 0 โ€” no size optimization. This level is deprecated and treated like 1.
    • 1 โ€” short instructions are used opportunistically.
    • 2 โ€” in addition, alignment of loops and of code after barriers are dropped.
    • 3 โ€” in addition, optional data alignment is dropped, and the option Os is enabled.

This defaults to 3 when -Os is in effect. Otherwise, the behavior when this is not set is equivalent to level 1. ๐ŸŽ€

  • -mtune=cpu โ€” set instruction scheduling parameters for cpu, overriding any implied by -mcpu=. Supported values for cpu are:
    • ARC600 โ€” tune for ARC600 CPU.
    • ARC601 โ€” tune for ARC601 CPU.
    • ARC700 โ€” tune for ARC700 CPU with standard multiplier block.
    • ARC700-xmac โ€” tune for ARC700 CPU with XMAC block.
    • ARC725D โ€” tune for ARC725D CPU.
    • ARC750D โ€” tune for ARC750D CPU.
    • core3 โ€” tune for ARCv2 core3 type CPU. This option enable usage of "dbnz" instruction.
    • release31a โ€” tune for ARC4x release 3.10a.
  • -mmultcost=num โ€” cost to assume for a multiply instruction, with 4 being equal to a normal instruction.
  • -munalign-prob-threshold=probability โ€” does nothing. Preserved for backward compatibility. ๐Ÿซถ
โš ๏ธ The following options are 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. Letโ€™s get into it. ๐Ÿฆ‹

  • -mabi=name โ€” generate code for the specified ABI. Permissible values are: apcs-gnu, atpcs, aapcs, aapcs-linux and iwmmxt.
  • -mapcs-frame โ€” generate a stack frame that is compliant with the ARM Procedure Call Standard for all functions, even if this is not strictly necessary for correct execution of the code. Specifying -fomit-frame-pointer with this option causes the stack frames not to be generated for leaf functions. The default is -mno-apcs-frame. This option is deprecated. ๐Ÿ˜ญ
  • -mapcs โ€” this is a synonym for -mapcs-frame and is deprecated.
  • -mthumb-interwork โ€” generate code that supports calling between the ARM and Thumb instruction sets. Without this option, on pre-v5 architectures, the two instruction sets cannot be reliably used inside one program. The default is -mno-thumb-interwork, since slightly larger code is generated when -mthumb-interwork is specified. In AAPCS configurations this option is meaningless. ๐Ÿซ 
  • -mno-sched-prolog โ€” prevent the reordering of instructions in the function prologue, or the merging of those instruction with the instructions in the functionโ€™s body. This means that all functions start with a recognizable set of instructions (or in fact one of a choice from a small set of different function prologues), and this information can be used to locate the start of functions inside an executable piece of code. The default is -msched-prolog. ๐Ÿ”
  • -mfloat-abi=name โ€” specifies which floating-point ABI to use. Permissible values are: soft, softfp and hard.
    • Specifying soft causes GCC to generate output containing library calls for floating-point operations.
    • softfp allows the generation of code using hardware floating-point instructions, but still uses the soft-float calling conventions.
    • hard allows generation of floating-point instructions and uses FPU-specific calling conventions.

The default depends on the specific target configuration. Note that the hard-float and soft-float ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries. No cap, this one matters. โš ๏ธ

  • -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. Slay. โœจ
  • -mbig-endian โ€” generate code for a processor running in big-endian mode; the default is to compile code for a little-endian processor.
  • -mbe8, -mbe32 โ€” when linking a big-endian image select between BE8 and BE32 formats. The option has no effect for little-endian images and is ignored. The default is dependent on the selected target architecture. For ARMv6 and later architectures the default is BE8, for older architectures the default is BE32. BE32 format has been deprecated by ARM. ๐Ÿซก
  • -march=name[+extension...] โ€” this specifies the name of the target ARM architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. This option can be used in conjunction with or instead of the -mcpu= option.

Permissible names are: armv4t, armv5t, armv5te, armv6, armv6j, armv6k, armv6kz, armv6t2, armv6z, armv6zk, armv7, armv7-a, armv7ve, armv8-a, armv8.1-a, armv8.2-a, armv8.3-a, armv8.4-a, armv8.5-a, armv8.6-a, 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. Iconic behavior, honestly. ๐Ÿ‘‘

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 and the VFPv3 floating-point instructions. The extensions +neon and +neon-vfpv3 can be used as aliases for this extension.
  • +vfpv3 โ€” the VFPv3 floating-point instructions, with 32 double-precision registers.
  • +vfpv3-d16-fp16 โ€” the VFPv3 floating-point instructions, with 16 double-precision registers and the half-precision floating-point conversion operations.
  • +vfpv3-fp16 โ€” the VFPv3 floating-point instructions, with 32 double-precision registers and the half-precision floating-point conversion operations.
  • +vfpv4-d16 โ€” the VFPv4 floating-point instructions, with 16 double-precision registers.
  • +vfpv4 โ€” the VFPv4 floating-point instructions, with 32 double-precision registers.
  • +neon-fp16 โ€” the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations.
  • +neon-vfpv4 โ€” the Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions ๐Ÿ’…
  • +nosimd โ€” turns off the Advanced SIMD instructions (and no, it does not disable floating point, bestie) ๐Ÿซถ
  • +nofp โ€” turns off the floating-point and Advanced SIMD instructions, periodt ๐Ÿ’€
  • armv7ve โ€” the extended version of the ARMv7-A architecture with support for virtualization โœจ
    • +fp โ€” the VFPv4 floating-point instructions, with 16 double-precision registers. The extension +vfpv4-d16 can be used as an alias for this extension. ๐ŸŽ€
    • +simd โ€” the Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions. The extension +neon-vfpv4 can be used as an alias for this extension. ๐ŸŒธ
    • +vfpv3-d16 โ€” the VFPv3 floating-point instructions, with 16 double-precision registers. ๐Ÿ’–
    • +vfpv3 โ€” the VFPv3 floating-point instructions, with 32 double-precision registers. โญ
    • +vfpv3-d16-fp16 โ€” the VFPv3 floating-point instructions, with 16 double-precision registers and the half-precision floating-point conversion operations. ๐Ÿฆ‹
    • +vfpv3-fp16 โ€” the VFPv3 floating-point instructions, with 32 double-precision registers and the half-precision floating-point conversion operations. ๐Ÿ“
    • +vfpv4-d16 โ€” the VFPv4 floating-point instructions, with 16 double-precision registers. ๐Ÿงš
    • +vfpv4 โ€” the VFPv4 floating-point instructions, with 32 double-precision registers. ๐Ÿ’œ
    • +neon โ€” the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. The extension +neon-vfpv3 can be used as an alias for this extension. ๐ŸŒˆ
    • +neon-fp16 โ€” the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations. ๐ŸŽ€
    • +nosimd โ€” turns off the Advanced SIMD instructions (still not disabling floating point, iykyk) ๐Ÿ™ˆ
    • +nofp โ€” turns off the floating-point and Advanced SIMD instructions. ๐Ÿ’€
  • armv8-a โ€” the ARMv8-A vibe, with its own extension menu ๐Ÿ‘‘
    • +crc โ€” the Cyclic Redundancy Check (CRC) instructions. ๐Ÿ”ฅ
    • +simd โ€” the ARMv8-A Advanced SIMD and floating-point instructions. โœจ
    • +crypto โ€” the cryptographic instructions. ๐Ÿ”
    • +nocrypto โ€” turns off the cryptographic instructions. ๐Ÿ™…โ€โ™€๏ธ
    • +nofp โ€” turns off the floating-point, Advanced SIMD and cryptographic instructions. ๐Ÿ’€
    • +sb โ€” Speculation Barrier Instruction. ๐Ÿ›ก๏ธ
    • +predres โ€” Execution and Data Prediction Restriction Instructions. ๐Ÿง 
  • armv8.1-a โ€” the next glow-up of the ARMv8 menu ๐Ÿฆ‹
    • +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 โ€” turns off the cryptographic instructions. ๐Ÿ™…โ€โ™€๏ธ
    • +nofp โ€” turns off the floating-point, Advanced SIMD and cryptographic instructions. ๐Ÿ’€
    • +sb โ€” Speculation Barrier Instruction. ๐Ÿ›ก๏ธ
    • +predres โ€” Execution and Data Prediction Restriction Instructions. ๐Ÿง 
  • armv8.2-a, armv8.3-a โ€” both of these share the exact same extension lineup, no cap ๐Ÿ’…
    • +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 โ€” turns off the cryptographic extension. ๐Ÿ™…โ€โ™€๏ธ
    • +nofp โ€” turns off 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 โ€” more ARMv8 flavor, and yes the list is 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 โ€” turns off the cryptographic extension. ๐Ÿ™…โ€โ™€๏ธ
    • +nofp โ€” turns off 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 โ€” this one gets the same extension set as 8.4-a, periodt ๐ŸŒˆ
    • +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 โ€” turns off the cryptographic extension. ๐Ÿ™…โ€โ™€๏ธ
    • +nofp โ€” turns off 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 lineup as 8.5-a again, bestie, keep scrolling ๐Ÿฆ‹
    • +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 โ€” turns off the cryptographic extension. ๐Ÿ™…โ€โ™€๏ธ
    • +nofp โ€” turns off 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 ARMv7-R menu, real-time bestie energy โญ
    • +fp.sp โ€” the single-precision VFPv3 floating-point instructions. The extension +vfpv3xd can be used as an alias for this extension. ๐Ÿ’…
    • +fp โ€” the VFPv3 floating-point instructions with 16 double-precision registers. The extension +vfpv3-d16 can be used as an alias for this extension. ๐ŸŽ€
    • +vfpv3xd-d16-fp16 โ€” the single-precision VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations. ๐Ÿฆ‹
    • +vfpv3-d16-fp16 โ€” the VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations. ๐ŸŒธ
    • +nofp โ€” turns off the floating-point extension. ๐Ÿ™…โ€โ™€๏ธ
    • +idiv โ€” the ARM-state integer division instructions. โž—
    • +noidiv โ€” turns off the ARM-state integer division extension. ๐Ÿ’€
  • armv7e-m โ€” microcontroller vibes, but make it floating-point ๐Ÿงš
    • +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 โ€” turns off the floating-point extensions. ๐Ÿ™…โ€โ™€๏ธ
  • armv8.1-m.main โ€” the M-profile main-character architecture ๐Ÿ‘‘
    • +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 โ€” turns off the floating-point extension. ๐Ÿ™…โ€โ™€๏ธ
  • +cdecp0, +cdecp1, ... , +cdecp7 โ€” turns the Custom Datapath Extension (CDE) ON for whichever coprocessors you name, and the numbers you give have to be in the range 0 to 7 ๐Ÿ’…
  • +pacbti โ€” enables the Pointer Authentication and Branch Target Identification Extension, iconic security behavior honestly ๐Ÿซถ

armv8-m.main

  • +dsp โ€” the DSP instructions, yes ma'am โœจ
  • +nodsp โ€” disables that DSP extension. we contain multitudes ๐Ÿ’€
  • +fp โ€” the single-precision floating-point instructions.
  • +fp.dp โ€” the single- and double-precision floating-point instructions. go big ๐ŸŒธ
  • +nofp โ€” disables the floating-point extension.
  • +cdecp0, +cdecp1, ... , +cdecp7 โ€” enables the Custom Datapath Extension (CDE) on the selected coprocessors, per the numbers in the options, 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 โ€” disables the cryptographic instructions.
  • +nofp โ€” disables the floating-point, Advanced SIMD and cryptographic instructions. all of them. gone. ๐Ÿ’€

-march=native makes the compiler 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. like it just shrugs and moves on, no cap ๐Ÿ˜ญ

-mtune=name ๐Ÿ‘‘

This one tells GCC the name of the target ARM processor it should tune the performance of the code for. For some ARM implementations you genuinely get better performance by using this option โ€” it's giving "dress for the job you want" but for codegen ๐ŸŽ€

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.

That list is long bestie, like a group chat read receipt list, but every single one is valid ๐Ÿ’…

On top of that, this option can also say "tune the performance of the code for a big.LITTLE system." Permissible names for that are:

cortex-a15.cortex-a7, cortex-a17.cortex-a7,
cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a72.cortex-a35,
cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55.

-mtune=generic-arch says GCC should tune for a blend of processors within architecture arch ๐ŸŒˆ The aim is to generate code that runs well on the current most popular processors, balancing between optimizations that benefit some CPUs in the range and avoiding performance pitfalls of other CPUs. Heads up though: 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 lowkey the extension options do not affect the tuning of the generated code. they're just there. vibes only โœจ

-mtune=native makes the compiler auto-detect the CPU of the build computer. At present this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect ๐Ÿ˜ญ


-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) โœจ So it's kind of the overachiever of the family, doing two jobs at once.

Where this option is used in conjunction with -march or -mtune, those options take precedence over the appropriate part of this option. periodt ๐Ÿ‘‘

Many of the supported CPUs implement optional architectural extensions. Where this is so, the architectural extensions are normally enabled by default. If implementations that lack the extension exist, then the extension syntax can be used to disable those extensions that have been omitted ๐ŸŽ€

For floating-point and Advanced SIMD (Neon) instructions, the settings of the options -mfloat-abi and -mfpu must also be considered: floating-point and Advanced SIMD instructions will only be used if -mfloat-abi is not set to soft; and any setting of -mfpu other than auto will override the available floating-point and SIMD extension instructions. iykyk ๐Ÿ’…

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. yes, the whole giant list again. copy paste energy, honestly ๐Ÿ’€

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 disables 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 makes the compiler auto-detect the CPU of the build computer. At present this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect ๐Ÿ˜ญ


-mfpu=name ๐ŸŒธ

This one specifies what floating-point hardware (or hardware emulation) is available on the target. Permissible names are: auto, vfpv2, vfpv3, vfpv3-fp16, vfpv3-d16, vfpv3-d16-fp16, vfpv3xd, vfpv3xd-fp16, neon-vfpv3, neon-fp16, vfpv4, vfpv4-d16, fpv4-sp-d16, neon-vfpv4, fpv5-d16, fpv5-sp-d16, fp-armv8, neon-fp-armv8 and crypto-neon-fp-armv8.

Note that neon is an alias for neon-vfpv3 and vfp is an alias for vfpv2 ๐Ÿ‘‘

The setting auto is the default and is special โœจ It causes the compiler to select the floating-point and Advanced SIMD instructions based on the settings of -mcpu and -march.

If the selected floating-point hardware includes the NEON extension (e.g. -mfpu=neon), note that floating-point operations are not generated by GCC's auto-vectorization pass unless -funsafe-math-optimizations is also specified. This is because NEON hardware does not fully implement the IEEE 754 standard for floating-point arithmetic (in particular denormal values are treated as zero), so the use of NEON instructions may lead to a loss of precision. not me warning you about the math, but like, precision loss is real bestie ๐Ÿ˜ญ

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


  • -mstructure-size-boundary=n โ€” okay so this one rounds the size of all structures and unions 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 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.

๐Ÿšจ deprecated alert ๐Ÿšจ This option is deprecated. iykyk
  • -mabort-on-noreturn โ€” generate a call to the function abort at the end of a noreturn function. It is executed if the function tries to return. so it's like a little "bestie, no" at the end of the function ๐Ÿ’…
  • -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. fr fr, pointer calls are doing their own thing โœจ

  • -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. runtime's main character moment ๐Ÿซถ
  • -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. the way that default flips is so specific ๐Ÿ’€
  • -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). literally a name tag for your stack frame ๐ŸŽ€

  • -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. do not use this for real code, bestie ๐Ÿ˜ญ
  • -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. yes, that's the default named right there โ€” keep it exactly as written ๐Ÿ’œ
  • -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. auto is lowkey the main character here โœจ
  • -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. conflict noted, no cap โš ๏ธ
  • -mfix-cortex-m3-ldrd โ€” some Cortex-M3 cores can cause data corruption when ldrd instructions with overlapping destination and base registers are used. This option avoids generating these instructions. This option is enabled by default when -mcpu=cortex-m3 is specified. data corruption is not the vibe ๐Ÿ˜ญ
  • -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. byte-at-a-time is giving slow era, honestly ๐ŸŒ

  • -mneon-for-64bits โ€” this option is deprecated and has no effect. deprecated + no effect = ghosted ๐Ÿ‘ป
  • -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. future GCC may switch it up, so stay tuned ig ๐Ÿ‘€
  • -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. compiler debugging only, bestie โ€” not for your everyday build ๐Ÿซถ
  • -mverbose-cost-dump โ€” enable verbose cost model dumping in the debug dump files. This option is provided for use in debugging the compiler.
  • -mpure-code โ€” do not allow constant data to be placed in code sections. Additionally, when compiling for ELF object format give all text sections the ELF processor-specific section attribute SHF_ARM_PURECODE. This option is only available when generating non-pic code for M-profile targets.
  • -mcmse โ€” generate secure code as per the ARMv8-M Security Extensions: Requirements on Development Tools Engineering Specification, which can be found on https://developer.arm.com/documentation/ecm0359818/latest/. secure code era, slay ๐Ÿ”โœจ
  • -mfix-cmse-cve-2021-35465 โ€” okay so there's a potential security issue with the VLLDM instruction on some M-profile devices when you're using CMSE (CVE-2021-365465), and this option mitigates it ๐Ÿ’… It's on by default when -mcpu= is used with cortex-m33, cortex-m35p, cortex-m55, cortex-m85 or star-mc1. And if you ever need to turn the mitigation back off, that's what -mno-fix-cmse-cve-2021-35465 is for ๐Ÿซถ
  • -mstack-protector-guard=guard โ€” generates stack protection code with the canary living at guard. The supported locations are global (for a global canary) or tls (for a canary you can get at via the TLS register), bestie.
  • -mstack-protector-guard-offset=offset โ€” pairs up with the one above. Heads up though: this one is for use with -fstack-protector-guard=tls and not for use in user-land code ๐Ÿ™ˆ
  • -mfdpic, -mno-fdpic โ€” picks the FDPIC ABI, which represents pointers to functions with 64-bit function descriptors. When the compiler is configured for arm-*-uclinuxfdpiceabi targets, this is on by default and it implies -fPIE if you didn't give any of the PIC/PIE-related options. On other targets it only switches on the FDPIC-specific code generation bits, so you gotta explicitly hand it the PIC/PIE-related options yourself, no cap.
โš ๏ธ Heads up: static linking is not supported here, because it would still involve the dynamic linker when the program self-relocates. If that behavior is actually acceptable to you, use -static and -Wl,-dynamic-linker options.

The opposite -mno-fdpic option is useful (and required, fr) 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]] โ€” enables branch protection features (armv8.1-m.main only โญ). Breaking it down:
    • none โ€” generate code with no branch protection and no return address signing.
    • standard[+leaf] โ€” generate code with all branch protection features on at their standard level.
    • pac-ret[+leaf] โ€” generate code with return address signing at its standard level, which means signing all functions that save the return address to memory.
    • leaf โ€” when return address signing is enabled, also sign leaf functions even if they don't write the return address to memory.
    • +bti โ€” add landing-pad instructions at the permitted targets of indirect branch instructions.

If the +pacbti architecture extension isn't 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 stays backwards-compatible with earlier versions of the architecture, but you can flip the extra security on 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.

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


๐ŸŒฝ AVR Options ๐ŸŒฝ

These options are defined for AVR implementations, bestie:

  • -mmcu=mcu โ€” specify the AVR instruction set architecture (ISA) or device type. The default for this option is avr2.

The following AVR devices and ISAs are supported. Note: 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 (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) ๐Ÿซถ

  • 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.
  • 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 โ€” "XMEGA" devices with up to 64 KiB of combined program memory and RAM, and with program memory visible in the RAM address space โœจ mcu = attiny202, attiny204, attiny212, attiny214, attiny402, attiny404, attiny406, attiny412, attiny414, attiny416, 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.
  • "avrxmega4" โ€” "XMEGA" girlies 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 (she's got the whole package, no cap โœจ). mcu = "atxmega64a1", "atxmega64a1u".
  • "avrxmega6" โ€” "XMEGA" devices with more than 128 KiB of program memory, like, a lot of it ๐Ÿซถ 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. main character energy fr ๐Ÿ’… mcu = "atxmega128a1", "atxmega128a1u", "atxmega128a4u".
  • "avrtiny" โ€” "TINY" Tiny core devices with 512 B up to 4 KiB of program memory. smol but mighty ๐Ÿฃ mcu = "attiny4", "attiny5", "attiny9", "attiny10", "attiny102", "attiny104", "attiny20", "attiny40".
  • "avr1" โ€” this ISA is implemented by the minimal AVR core and it's supported for assembler only. no C compiler shenanigans here, bestie. mcu = "attiny11", "attiny12", "attiny15", "attiny28", "at90s1200".

  • -mabsdata โ€” assume that all data in static storage can be accessed by LDS / STS instructions. Heads up: this option only does anything on reduced Tiny devices like ATtiny40. Also peep the absdata AVR Variable Attributes variable attribute if you wanna know more ๐Ÿ‘€
  • -maccumulate-args โ€” accumulate outgoing function arguments and acquire/release the needed stack space for them once, in the function prologue/epilogue. Without this option, outgoing arguments are pushed before calling a function and popped afterwards.

Popping the arguments after the function call can be expensive on AVR, so accumulating the stack space might lead to smaller executables, because the arguments don't need to be removed from the stack after such a function call ๐Ÿ˜Œ

This option can lead to reduced code size for functions that perform several calls to functions that get their arguments on the stack โ€” like calls to printf-like functions. iykyk.

  • *-mbranch-cost=cost* โ€” 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. periodt.
  • -mcall-prologues โ€” function prologues/epilogues are expanded as calls to appropriate subroutines. Code size gets smaller. it's giving minimalism โœจ
  • *-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. so like, check your build first, bestie ๐ŸŽ€
  • -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 no_gccisr function attribute (AVR Function Attributes). 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 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. so like, iconic but unhinged.
  • -mmain-is-OS_task โ€” do not save registers in main. The effect is the same like attaching attribute OS_task (AVR Function Attributes) 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. pick your fighter ๐Ÿ’€
  • -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. sneaky but valid ๐Ÿ˜Œ

Relaxing must be turned on if linker stubs are needed โ€” see the section on EIND and linker stubs below. don't skip it ๐Ÿ‘‡

  • -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. she stays in her lane ๐Ÿ’…

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

extra instructions = extra vibe tax, ngl.

  • -mtiny-stack โ€” only change the lower 8 bits of the stack pointer. that's it. that's the whole option ๐Ÿ“
  • -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. bye bestie ๐Ÿ‘‹
  • -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. you're on your own now, respectfully ๐Ÿ™ˆ

This option can also serve as a replacement for the older way of specifying custom device-specs files that needed -B some-path to point to a directory which contains a folder named device-specs which contains a specs file named specs-mcu, where mcu was specified by -mmcu=mcu.

  • -Waddr-space-convert โ€” warn about conversions between address spaces in the case where the resulting address space is not contained in the incoming address space.
  • -Wmisspelled-isr โ€” warn if the ISR is misspelled, i.e. without __vector prefix. Enabled by default. she's always watching ๐Ÿ”ฅ

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 โ€” read carefully bestie, this part is important ๐Ÿซถ

  • 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. so like, don't be weird with it.
  • 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. trampoline but make it assembly ๐Ÿ˜ญ
  • 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. (rude, honestly ๐Ÿ’€)
  • The default linker script is arranged for code with EIND = 0. If code is supposed to work for a setup with EIND != 0, a custom linker script has to be used in order to place the sections whose name start with .trampolines into the segment where EIND points to.
  • The startup code from libgcc never sets EIND. Notice that startup code is a blend of code from libgcc and AVR-LibC. For the impact of AVR-LibC on EIND, see the AVR-LibC user manual (https://www.nongnu.org/avr-libc/user-manual/).
  • It is legitimate for user-specific startup code to set up EIND early, for example by means of initialization code located in section .init3. Such code runs prior to general startup code that initializes RAM and calls constructors, but after the bit of startup code from AVR-LibC that sets EIND to the segment where the vector table is located.
#include <avr/io.h>

static void
__attribute__((section(".init3"),naked,used,no_instrument_function))
init3_set_eind (void)
{
  __asm volatile ("ldi r24,pm_hh8(__trampolines_start)\n\t"
                  "out %i0,r24" :: "n" (&EIND) : "r24","memory");
}

The __trampolines_start symbol is defined in the linker script. fancy โœจ

  • Stubs are generated automatically by the linker if the following two conditions are met:
    • <The address of a label is taken by means of the gs modifier> (short for generate stubs) like so:
LDI r24, lo8(gs(<func>))
LDI r25, hi8(gs(<func>))
  • <The final location of that label is in a code segment> outside the segment where the stubs are located.
  • The compiler emits such gs modifiers for code labels in the following situations:
  • Taking address of a function or code label.
  • Computed goto.
  • If prologue-save function is used, see -mcall-prologues command-line option.
  • Switch/case dispatch tables. If you do not want such dispatch tables you can specify the -fno-jump-tables command-line option.
  • C and C++ constructors/destructors called during startup/shutdown.
  • If the tools hit a gs() modifier explained above.

Jumping to non-symbolic addresses like so is not supported:

int main (void)
{
    /* Call function at word address 0x2 */
    return ((int(*)(void)) 0x2)();
}

Instead, a stub has to be set up, i.e. the function has to be called through a symbol (func_4 in the example):

int main (void)
{
    extern int func_4 (void);

    /* Call function at byte address 0x4 */
    return func_4();
}

and the application be linked with -Wl,--defsym,func_4=0x4. Alternatively, func_4 can be defined in the linker script.


๐Ÿงš Handling of the RAMPD, RAMPX, RAMPY and RAMPZ Special Function Registers

Some AVR devices support memories larger than the 64 KiB range that can be accessed with 16-bit pointers. To access memory locations outside this 64 KiB range, the content of a RAMP register is used as high part of the address: the X, Y, Z address register is concatenated with the RAMPX, RAMPY, RAMPZ special function register, respectively, to get a wide address. Similarly, RAMPD is used together with direct addressing.

  • The startup code initializes the RAMP special function registers with zero.
  • If a AVR Named Address Spaces, named address space other than generic or __flash is used, then RAMPZ is set as needed before the operation.
  • If the device supports RAM larger than 64 KiB and the compiler needs to change RAMPZ to accomplish an operation, RAMPZ is reset to zero after the operation.
  • If the device comes with a specific RAMP register, the ISR prologue/epilogue saves/restores that SFR and initializes it with zero in case the ISR code might (implicitly) use it.
  • RAM larger than 64 KiB is not supported by GCC for AVR targets. If you use inline assembler to read from locations outside the 16-bit address range and change one of the RAMP registers, you must reset it to zero after the access.
โš ๏ธ That last one is a real vibe-killer if you ignore it โ€” touch a RAMP register in inline asm and forget to zero it back out, and everything downstream is chaos ๐Ÿ˜ญ

๐ŸŒˆ AVR Built-in Macros

GCC defines several built-in macros so that the user code can test for the presence or absence of features. Almost any of the following built-in macros are deduced from device capabilities and thus triggered by the -mmcu= command-line option.

For even more AVR-specific built-in macros see AVR Named Address Spaces and AVR Built-in Functions.

__AVR_ARCH__

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

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

  • -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.
๐Ÿ’€ Real talk: these bad boys are compiler-internal plumbing. Hand-setting them is giving "I read half a wiki page and now nothing compiles" energy. Documented for completeness only, bestie ๐Ÿ™ˆ

๐Ÿ–ค Blackfin Options

(next part energy โ€” this is where the Blackfin era begins โœจ)

  • -mcpu=cpu[-sirevision] โ€” bestie, this one tells GCC exactly which target Blackfin processor you're on. Right now cpu can be any 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. That's the whole roster, no cap ๐Ÿ’…

The optional sirevision is literally the silicon revision of your target chip, and any workarounds available for that revision get switched on. If sirevision is none, zero workarounds โ€” none, nada. If sirevision is any, then all the workarounds for the targeted processor get enabled. The __SILICON_REVISION__ macro gets defined to two hex digits representing the major and minor numbers of the silicon revision. But if sirevision is none, then __SILICON_REVISION__ is not defined at all. And if sirevision is any, __SILICON_REVISION__ is defined to be 0xffff. If you just skip the optional sirevision entirely, GCC assumes the latest known silicon revision of the targeted Blackfin processor. Fingers crossed energy โœจ

GCC also defines a preprocessor macro for whichever cpu you specified. For the bfin-elf toolchain, this option makes the hardware BSP that libgloss provides get linked in โ€” unless you passed -msim. ๐Ÿซถ

Don't pass this option at all? Then bf532 is your default processor, periodt.

Heads up: support for bf561 is incomplete ๐Ÿ˜ญ for bf561, only the preprocessor macro gets defined. That's it. That's the whole feature.
  • -msim โ€” says your program is gonna run on the simulator, so the simulator BSP from libgloss gets linked in. This only does anything for the bfin-elf toolchain. Also, some other options โ€” like -mid-shared-library and -mfdpic โ€” lowkey imply -msim on their own.
  • -momit-leaf-frame-pointer โ€” don't keep the frame pointer in a register for leaf functions. The way this slays: it skips the instructions that save, set up and restore frame pointers, and frees up one extra register in leaf functions. Free real estate ๐ŸŽ€
  • -mspecld-anomaly โ€” when enabled, the compiler makes sure the generated code doesn't contain speculative loads after jump instructions. Use this and __WORKAROUND_SPECULATIVE_LOADS gets defined.
  • -mno-specld-anomaly โ€” don't generate the extra code that prevents speculative loads from happening.
  • -mcsync-anomaly โ€” when enabled, the compiler makes sure the generated code doesn't have CSYNC or SSYNC instructions too soon after conditional branches. Use this and __WORKAROUND_SPECULATIVE_SYNCS gets defined.
  • -mno-csync-anomaly โ€” don't generate extra code to prevent CSYNC or SSYNC instructions from showing up too soon after a conditional branch.
  • -mlow64k โ€” when enabled, the compiler is free to take advantage of knowing that the entire program fits into the low 64k of memory. Tiny program privilege ๐ŸŒธ
  • -mno-low64k โ€” assume the program is arbitrarily large. This is the default.
  • -mstack-check-l1 โ€” do stack checking using info that the uClinux kernel places into L1 scratchpad memory.
  • -mid-shared-library โ€” generate code that supports shared libraries via the library ID method. This lets you do execute in place and shared libraries in an environment with no virtual memory management. It implies -fPIC, and with a bfin-elf target it also 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 this library or executable won't link against any other ID shared libraries. That lets the compiler use faster code for jumps and calls. Speedy queen โญ
  • -mno-leaf-id-shared-library โ€” don't assume the code being compiled won't link against any ID shared libraries. You get slower code for jump and call insns, and that's the tradeoff.
  • *-mshared-library-id=n* โ€” specifies the identification number of the ID-based shared library you're compiling. A value of 0 generates more compact code; any other value forces the allocation of that number to the current library, but it's no more space- or time-efficient than just omitting this option entirely. ๐Ÿ™ˆ
  • -msep-data โ€” generate code that lets the data segment live in a different area of memory from the text segment. This enables execute in place in an environment without virtual memory management, by eliminating relocations against the text section.
  • -mno-sep-data โ€” generate code that assumes the data segment follows the text segment. This is the default.
  • -mlong-calls, -mno-long-calls โ€” tells the compiler to do function calls by first loading the address of the function into a register, then doing a subroutine call on that register. You need this switch if the target function sits outside the 24-bit addressing range of the offset-based version of the subroutine call instruction. ๐Ÿ“ž

This feature is not enabled by default. Passing -mno-long-calls restores the default behavior. Note that these switches have zero effect on how the compiler generates code to handle function calls via function pointers โ€” those are a whole different vibe.

  • -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), all in the interest of performance. Living dangerously for speed ๐Ÿ”ฅ
  • -minline-plt โ€” enable inlining of PLT entries in function calls to functions that aren't known to bind locally. Has no effect without -mfdpic.
  • -mmulticore โ€” build a standalone application for multicore Blackfin processors. This causes proper start files and link scripts that support multicore to be used, and defines the macro __BFIN_MULTICORE. It can only be used with -mcpu=bf561[-sirevision].

This option can be used together with -mcorea or -mcoreb, which selects the one-application-per-core programming model. Without -mcorea or -mcoreb, you get the single-application/dual-core programming model โ€” and in that model, the main function of Core B should be named coreb_main.

If you don't use this option at all, the single-core application programming model is what you get.

  • -mcorea โ€” build a standalone application for Core A of BF561 when you're using the one-application-per-core programming model. Proper start files and link scripts get 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 you're using the one-application-per-core programming model. Proper start files and link scripts get used to support Core B, and the macro __BFIN_COREB is defined. When you use this option, 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 get 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 figure out 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 sits adjacent to the .neardata section. Put small read-only data into the .rodata section. The corresponding sections used for large pieces of data are .fardata, .far and .const. Small data getting the VIP treatment ๐ŸŽ€
  • -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. Everything gets in, no bouncer.
  • -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, all uninitialized data in the .far section, and all constant data into the .const section.

๐Ÿฆ‹ CRIS Options ๐Ÿฆ‹

These options are defined specifically for the CRIS ports, iykyk.

  • *-march=architecture-type*, *-mcpu=architecture-type* โ€” generate code for the specified architecture. Your choices for architecture-type are v3, v8 and v10, for respectively ETRAX 4, ETRAX 100, and ETRAX 100 LX. Default is v0.
  • *-mtune=architecture-type* โ€” tune everything applicable about the generated code to architecture-type, except for the ABI and the set of available instructions. The choices for architecture-type are the same as for -march=architecture-type.
  • *-mmax-stack-frame=n* โ€” warn when the stack frame of a function exceeds n bytes. Keeping an eye on your stack's growth ๐ŸŒฑ
  • -metrax4, -metrax100 โ€” these two are synonyms for -march=v3 and -march=v8 respectively.
  • -mmul-bug-workaround, -mno-mul-bug-workaround โ€” work around a bug in the muls and mulu instructions for CPU models where it applies. This option is disabled by default.
  • -mpdebug โ€” enable CRIS-specific verbose debug-related information in the assembly code. This option also has the effect of turning off the #NO_APP formatted-code indicator to the assembler at the beginning of the assembly file.
  • -mcc-init โ€” don't use condition-code results from a previous instruction; always emit compare and test instructions before using condition codes. Baby steps, always verify ๐Ÿ’…
  • -mno-side-effects โ€” don't 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 โ€” okay so these bad boys arrange (and the no- versions eliminate the arranging of ๐Ÿ’…) the alignment for the stack frame, individual data, and constants so everything lines up for the biggest single data access size your chosen CPU model can handle. Default? 32-bit alignment, periodt. Important vibe check tho: ABI details like structure layout are not affected by these options, so don't come for me if your structs don't move.
  • -m32-bit, -m16-bit, -m8-bit โ€” basically the same energy as the stack-/data-/const-align options up above, except these arrange for the stack frame, writable data, and constants to all be 32-bit, 16-bit, or 8-bit aligned respectively. The default is 32-bit alignment โœจ.
  • -mno-prologue-epilogue, -mprologue-epilogue โ€” with -mno-prologue-epilogue, the normal function prologue and epilogue that set up the stack frame get yeeted ๐Ÿ™ˆ โ€” no return instructions, no return sequences generated in the code.
Use this one only together with your own eyeballs inspecting the compiled code, bestie. No warnings, no errors get generated even when call-saved registers must be saved or storage for local variables needs to be allocated. It'll just silently not do it. ๐Ÿ’€
  • -melf โ€” legacy no-op option. It does literally nothing, she's just here for the nostalgia ๐ŸŽ€.
  • -sim โ€” this one 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. Let's get into it ๐Ÿ’–

  • -march=arch โ€” specify the C-SKY target architecture. Valid values for arch are: ck801, ck802, ck803, ck807, and ck810. The default is ck810.
  • -mcpu=cpu โ€” specify the C-SKY target processor. Valid values for cpu are: ck801, ck801t, ck802, ck802t, ck802j, ck803, ck803h, ck803t, ck803ht, ck803f, ck803fh, ck803e, ck803eh, ck803et, ck803eht, ck803ef, ck803efh, ck803ft, ck803eft, ck803efht, ck803r1, ck803hr1, ck803tr1, ck803htr1, ck803fr1, ck803fhr1, ck803er1, ck803ehr1, ck803etr1, ck803ehtr1, ck803efr1, ck803efhr1, ck803ftr1, ck803eftr1, ck803efhtr1, ck803s, ck803st, ck803se, ck803sf, ck803sef, ck803seft, ck807e, ck807ef, ck807, ck807f, ck810e, ck810et, ck810ef, ck810eft, ck810, ck810v, ck810f, ck810t, ck810fv, ck810tv, ck810ft, and ck810ftv. Yes that's a lot of them, she's an icon with many looks ๐Ÿ‘‘
  • -mbig-endian, -EB, -mlittle-endian, -EL โ€” select big- or little-endian code. The default is little-endian.
  • -mfloat-abi=name โ€” specifies which floating-point ABI to use. Permissible values are: soft, softfp and hard.

Specifying soft 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. Also heads up ๐Ÿšจ: 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 and matching, iykyk.

  • -mhard-float, -msoft-float โ€” select hardware or software floating-point implementations. The default is soft float.
  • -mdouble-float, -mno-double-float โ€” when -mhard-float is in effect, enable generation of double-precision float instructions. This is the default except when compiling for CK803.
  • -mfdivdu, -mno-fdivdu โ€” when -mhard-float is in effect, enable generation of "frecipd", "fsqrtd", and "fdivd" instructions. This is the default except when compiling for CK803.
  • -mfpu=fpu โ€” select the floating-point processor. This option can only be used with -mhard-float. Values for fpu are fpv2_sf (equivalent to -mno-double-float -mno-fdivdu), fpv2 (-mdouble-float -mno-divdu), and fpv2_divd (-mdouble-float -mdivdu).
  • -melrw, -mno-elrw โ€” enable the extended "lrw" instruction. This option defaults to on for CK801 and off otherwise.
  • -mistack, -mno-istack โ€” enable interrupt stack instructions; the default is off. The -mistack option is required to handle the "interrupt" and "isr" function attributes.
  • -mmp โ€” enable multiprocessor instructions; the default is off.
  • -mcp โ€” enable coprocessor instructions; the default is off.
  • -mcache โ€” enable coprocessor instructions; the default is off. (Yes, it says coprocessor. That's what the page says, don't @ me ๐Ÿซถ)
  • -msecurity โ€” enable C-SKY security instructions; the default is off.
  • -mtrust โ€” enable C-SKY trust instructions; the default is off.
  • -mdsp, -medsp, -mvdsp โ€” enable C-SKY DSP, Enhanced DSP, or Vector DSP instructions, respectively. All of these options default to off.
  • -mdiv, -mno-div โ€” generate divide instructions. Default is off.
  • -msmart, -mno-smart โ€” generate code for Smart Mode, using only registers numbered 0-7 to allow use of 16-bit instructions. This option is ignored for CK801 where this is the required behavior, and it defaults to on for CK802. For other targets, the default is off.
  • -mhigh-registers, -mno-high-registers โ€” generate code using the high registers numbered 16-31. This option is not supported on CK801, CK802, or CK803, and is enabled by default for other processors.
  • -manchor, -mno-anchor โ€” generate code using global anchor symbol addresses.
  • -mpushpop, -mno-pushpop โ€” generate code using "push" and "pop" instructions. This option defaults to on.
  • -mmultiple-stld, -mstm, -mno-multiple-stld, -mno-stm โ€” generate code using "stm" and "ldm" instructions. This option isn't supported on CK801 but is enabled by default on other processors.
  • -mconstpool, -mno-constpool โ€” create constant pools in the compiler instead of deferring it to the assembler. This option is the default and required for correct code generation on CK801 and CK802, and is optional on other processors.
  • -mstack-size, -mno-stack-size โ€” emit ".stack_size" directives for each function in the assembly output. This option defaults to off.
  • -mccrt, -mno-ccrt โ€” generate code for the C-SKY compiler runtime instead of libgcc. This option defaults to off.
  • -mbranch-cost=n โ€” set the branch costs to roughly "n" instructions. The default is 1.
  • -msched-prolog, -mno-sched-prolog โ€” permit scheduling of function prologue and epilogue sequences.
Lowkey a warning: 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.
  • -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, and it's giving chaotic energy fr. 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. Sneaky but okay ๐Ÿ’€

  • -Fdir โ€” add the framework directory dir to the head of the list of directories to be searched for header files. These directories are interleaved with those specified by -I options and are scanned in a left-to-right order.

A framework directory is a directory with frameworks in it. A framework is a directory with a Headers and/or PrivateHeaders directory contained directly in it that ends in .framework. The name of a framework is the name of this directory excluding the .framework. Headers associated with the framework are found in one of those two directories, with Headers being searched first. A subframework is a framework directory that is in a framework's Frameworks directory. Includes of subframework headers can only appear in a header of a framework that contains the subframework, or in a sibling subframework header. Two subframeworks are siblings if they occur in the same framework. A subframework should not have the same name as a framework; a warning is issued if this is violated. Currently a subframework cannot have subframeworks; in the future, the mechanism may be extended to support this. The standard frameworks can be found in /System/Library/Frameworks and /Library/Frameworks. An example include looks like #include <Framework/header.h>, where Framework denotes the name of the framework and header.h is found in the PrivateHeaders or Headers directory.

  • -iframeworkdir โ€” like -F except the directory is a treated as a system directory. The main difference between this -iframework and -F is that with -iframework the compiler does not warn about constructs contained within header files found via dir. This option is valid only for the C family of languages.
  • -gused โ€” emit debugging information for symbols that are used. For stabs debugging format, this enables -feliminate-unused-debug-symbols. This is by default ON ๐Ÿ‘‘
  • -gfull โ€” emit debugging information for all symbols and types.
  • -fconstant-cfstrings โ€” the -fconstant-cfstrings is an alias for -mconstant-cfstrings.
  • -mconstant-cfstrings โ€” when the NeXT runtime is being used (the default on these systems), override any -fconstant-string-class setting and cause "@"..."" literals to be laid out as constant CoreFoundation strings.
  • -mmacosx-version-min=version โ€” tells everyone the earliest MacOS X your executable will run on is version. Cute typical values 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 here is literally 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. Flexible queen behavior ๐Ÿ’…
  • -mkernel โ€” enable kernel development mode, aka main character energy for kernel devs ๐Ÿ‘‘. This 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. It's giving "I do everything" and honestly, it does.
  • -mone-byte-bool โ€” overrides the defaults for "bool" so that "sizeof(bool)==1". By default sizeof(bool) is 4 when compiling for Darwin/PowerPC and 1 when compiling for Darwin/x86, so this option has no effect on x86. Ngl, x86 said "not my problem" ๐Ÿ™ˆ
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 (yes bestie, legacy support, we respect her ๐ŸŒธ).
  • -all_load โ€” loads all members of static archive libraries. See man ld(1) for more information. She's thorough, she's extra, she's iconic โœจ
  • -arch_errors_fatal โ€” cause the errors having to do with files that have the wrong architecture to be fatal. No mercy, no survivors, periodt ๐Ÿ’€
  • -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. Glow up from executable to library, we love a transformation arc ๐Ÿฆ‹
  • -force_cpusubtype_ALL โ€” this causes GCC's output file to have the ALL subtype, instead of one controlled by the -mcpu or -march option.

Okay so now we got a whole pile of options that are just passed straight through to the Darwin linker. The Darwin linker man page describes them in detail โ€” I'm just handing you the full guest list, every single name, no gatekeeping ๐Ÿซถ:

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

And yeah, before you come for me in the replies โ€” -sectobjectsymbols, -segs_read_only_addr and -segs_read_write_addr each show up twice in the list. That's literally what the page says, I'm not duplicating anything, I'm just being faithful ๐Ÿ˜Œ These options are passed to the Darwin linker. The Darwin linker man page describes them in detail.


๐Ÿ’œ DEC Alpha Options ๐Ÿ’œ

These -m options are defined for the DEC Alpha implementations. Retro tech era, but make it slay ๐ŸŽ€

  • -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. Yeah, makes no sense, don't ask, that's just how she is ๐Ÿ™ƒ

  • -mfp-reg, -mno-fp-regs โ€” generate code that uses (does not use) the floating-point register set. -mno-fp-regs implies -msoft-float. If the floating-point register set 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. Important caveat bestie, don't skip that part โš ๏ธ

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.
  • -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. Speed vs. precision, the eternal struggle ๐Ÿ˜ญ
  • -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. A field in the floating-point control register (fpcr, see Alpha architecture reference manual) controls the rounding mode in effect. The C library initializes this register for rounding towards plus infinity. Thus, unless your program modifies the fpcr, d corresponds to round towards plus infinity.
  • -mtrap-precision=trap-precision โ€” in the Alpha architecture, floating-point traps are imprecise. This means without software assistance it is impossible to recover from a floating trap and program execution normally needs to be terminated ๐Ÿ’€. GCC can generate code that can assist operating system trap handlers in determining the exact location that caused a floating-point trap. Depending on the requirements of an application, different levels of precision can be selected:
    • p โ€” program precision. This option is the default and means a trap handler can only identify which program caused a floating-point exception.
    • f โ€” function precision. The trap handler can determine the function that caused a floating-point exception.
    • i โ€” instruction precision. The trap handler can determine the exact instruction that caused a floating-point exception.

Other Alpha compilers provide the equivalent options called -scope_safe and -resumption_safe.

  • -mieee-conformant โ€” this option marks the generated code as IEEE conformant. You must not use this option unless you also specify -mtrap-precision=i and either -mfp-trap-mode=su or -mfp-trap-mode=sui. Its only effect is to emit the line .eflag 48 in the function prologue of the generated assembly file. Tiny effect, big requirements, she's high maintenance and we stan ๐ŸŒˆ
  • -mbuild-constants โ€” normally GCC examines a 32- or 64-bit integer constant to see if it can construct it from smaller constants in two or three instructions. If it cannot, it outputs the constant as a literal and generates code to load it from the data segment at run time.

Use this option to require GCC to construct all integer constants using code, even if it takes more instructions (the maximum is six).

You typically use this option to build a shared library dynamic loader. Itself a shared library, it must relocate itself in memory before it can find the variables and constants in its own data segment. It's giving self-made, self-relocating, self-obsessed ๐Ÿ’…

  • -mbwx, -mno-bwx, -mcix, -mno-cix, -mfix, -mno-fix, -mmax, -mno-max โ€” indicate whether GCC should generate code to use the optional BWX, CIX, FIX and MAX instruction sets. The default is to use the instruction sets supported by the CPU type specified via -mcpu= option or that of the CPU on which GCC was built if none is specified. Let the CPU decide, she knows herself best โœจ
  • -mfloat-vax, -mfloat-ieee โ€” bestie, one of these makes your code use VAX F and G floating-point arithmetic instead of IEEE single and double precision, and the other one makes it not do that. Pick your fighter ๐Ÿ’…
  • -mexplicit-relocs, -mno-explicit-relocs โ€” okay so story time ๐Ÿ“– back in the day, older Alpha assemblers literally had no way to generate symbol relocations except through assembler macros, and those macros? They do not allow optimal instruction scheduling. Rude. But GNU binutils as of version 2.12 supports a shiny new syntax that lets the compiler explicitly mark which relocations should apply to which instructions โœจ This option is mostly useful for debugging, since GCC detects the assembler's capabilities when it is built and sets the default accordingly. iykyk ๐Ÿซถ
  • -msmall-data, -mlarge-data โ€” when -mexplicit-relocs is in effect, static data is accessed via gp-relative relocations. With -msmall-data, objects 8 bytes long or smaller get parked in a small data area (the .sdata and .sbss sections) and are accessed via 16-bit relocations off of the $gp register. The tradeoff? It limits the size of the small data area to 64KB, but it lets the variables be directly accessed via a single instruction. slay โšก

The default is -mlarge-data. With this option the data area is limited to just below 2GB. Programs that require more than 2GB of data must use malloc or mmap to allocate the data in the heap instead of in the program's data segment. no cap, that's the rule ๐Ÿ˜ค

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 thus reachable with a branch instruction. And when -msmall-data is used, the compiler can assume that all local symbols share the same $gp value, which means it can reduce the number of instructions required for a function call from 4 to 1. efficiency icon ๐Ÿ’…

The default is -mlarge-text.

  • *-mcpu=cpu_type* โ€” sets the instruction set and 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 chooses the default values for the instruction set from the processor you specify. If you do not 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. (three whole spellings, she's flexible ๐Ÿ’–)
  • 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 โ€” same energy but *only sets the instruction scheduling parameters for machine type *cpu_type. The instruction set is not changed. periodt.

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. Heads up: this number is **highly dependent on the memory access patterns used by the application and the size of the external cache on the machine. ๐Ÿ˜ญ

Valid options for time are:

  • number โ€” A decimal number representing clock cycles.
  • L1, L2, L3, main โ€” The compiler contains estimates of the number of clock cycles for "typical" EV4 & EV5 hardware for the Level 1, 2 & 3 caches (also called Dcache, Scache, and Bcache), as well as to main memory. Note that L3 is only valid for EV5. ๐Ÿ‘‘

๐Ÿงš eBPF Options ๐Ÿงš

  • *-mframe-limit=bytes* โ€” 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* โ€” 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, latest and native. that's a whole lotta versions bestie ๐Ÿซถ
  • -mbig-endian โ€” Generate code for a big-endian target.
  • -mlittle-endian โ€” Generate code for a little-endian target. This is the default. ๐Ÿฃ
  • -mjmpext โ€” Enable generation of extra conditional-branch instructions. Enabled for CPU v2 and above.
  • -mjmp32 โ€” Enable 32-bit jump instructions. Enabled for CPU v3 and above.
  • -malu32 โ€” Enable 32-bit ALU instructions. Enabled for CPU v3 and above.
  • *-mcpu=version* โ€” specifies which version of the eBPF ISA to target. Newer versions may not be supported by all kernels. The default is v3.

Supported values for version are:

  • v1 โ€” The first stable eBPF ISA with no special features or extensions.
  • v2 โ€” Supports the jump extensions, as in -mjmpext.
  • v3 โ€” All features of v2, plus:
    • 32-bit jump operations, as in -mjmp32
    • 32-bit ALU operations, as in -malu32
  • -mco-re โ€” Enable BPF Compile Once - Run Everywhere (CO-RE) support. Requires 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. bespoke, we love to see it ๐Ÿ’…

  • -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. โš ๏ธ careful bestie
  • -mno-lsim โ€” Assume that runtime support has been provided and so there is no need to include the simulator library (libsim.a) on the linker command line.

๐Ÿฆ‹ FT32 Options ๐Ÿฆ‹

These options are defined specifically for the FT32 port.

  • -msim โ€” Specifies that the program will be run on the simulator. This causes an alternate runtime startup and library to be linked. You must not use this option when generating programs that will run on real hardware; you must provide your own runtime library for whatever I/O functions are needed. ๐Ÿซถ seriously, don't
  • -mlra โ€” Enable Local Register Allocation. This is still experimental for FT32, so by default the compiler uses standard reload. ๐Ÿงช
  • -mnodiv โ€” Do not use div and mod instructions.
  • -mft32b โ€” Enable use of the extended instructions of the FT32B processor.
  • -mcompress โ€” Compress all code using the Ft32B code compression scheme.
  • -mnopm โ€” Do not generate code that reads program memory.

๐Ÿ‘‘ FRV Options ๐Ÿ‘‘

  • -mgpr-32 โ€” Only use the first 32 general-purpose registers.
  • -mgpr-64 โ€” Use all 64 general-purpose registers. go big or go home โœจ
  • -mfpr-32 โ€” Use only the first 32 floating-point registers.
  • -mfpr-64 โ€” Use all 64 floating-point registers.
  • -mhard-float โ€” Use hardware instructions for floating-point operations.
  • -msoft-float โ€” Use library routines for floating-point operations.
  • -malloc-cc โ€” Dynamically allocate condition code registers.
  • -mfixed-cc โ€” Do not try to dynamically allocate condition code registers, only use icc0 and fcc0.
  • -mdword โ€” Change ABI to use double word insns.
  • -mno-dword โ€” Do not use double word instructions.
  • -mdouble โ€” Use floating-point double instructions.
  • -mno-double โ€” Do not use floating-point double instructions.
  • -mmedia โ€” Use media instructions.
  • -mno-media โ€” Do not use media instructions.
  • -mmuladd โ€” Use multiply and add/subtract instructions.
  • -mno-muladd โ€” Do not use multiply and add/subtract instructions.
  • -mfdpic โ€” Select the FDPIC ABI, which uses function descriptors to represent pointers to functions. Without any PIC/PIE-related options, it implies -fPIE. With -fpic or -fpie, it assumes GOT entries and small data are within a 12-bit range from the GOT base address; with -fPIC or -fPIE, GOT offsets are computed with 32 bits. With a bfin-elf target, this option implies -msim. ๐Ÿ˜ฎโ€๐Ÿ’จ big brain stuff
  • -minline-plt โ€” Enable inlining of PLT entries in function calls to functions that are not known to bind locally. It has no effect without -mfdpic. It's enabled by default if optimizing for speed and compiling for shared libraries (i.e., -fPIC or -fpic), or when an optimization option such as -O3 or above is present in the command line.
  • -mTLS โ€” Assume a large TLS segment when generating thread-local code. (note the capital letters bestie, they matter ๐Ÿ‘€)
  • -mtls โ€” Do not assume a large TLS segment when generating thread-local code.
  • -mgprel-ro โ€” Enable the use of GPREL relocations in the FDPIC ABI for data that is known to be in read-only sections. It's enabled by default, except for -fpic or -fpie: even though it may help make the global offset table smaller, it trades 1 instruction for 4. With -fPIC or -fPIE, it trades 3 instructions for 4, one of which may be shared by multiple symbols, and it avoids the need for a GOT entry for the referenced symbol, so it's more likely to be a win. If it is not, -mno-gprel-ro can be used to disable it. math girlie behaviour ๐Ÿ’€
  • -multilib-library-pic โ€” Link with the (library, not FD) pic libraries. It's implied by -mlibrary-pic, as well as by -fPIC and -fpic without -mfdpic. You should never have to use it explicitly. like ever. ๐Ÿ™ˆ
  • -mlinked-fp โ€” follows that EABI rule where you always get a frame pointer whenever a stack frame exists, no exceptions ๐Ÿ’… it's on by default, and honestly if you wanna break up with it, -mno-linked-fp is right there.
  • -mlong-calls โ€” makes function calls use indirect addressing so you can call stuff outside the current compilation unit. basically it lets functions live anywhere in the 32-bit address space, wanderers welcome ๐ŸŒˆ
  • -malign-labels โ€” tries to line labels up all pretty on an 8-byte boundary by dropping NOPs into the previous packet. heads up tho: this literally only does anything when VLIW packing is enabled, and it does not make new packets, it just sprinkles NOPs into the ones you already have ๐ŸŽ€
  • -mlibrary-pic โ€” generate position-independent EABI code. yes queen, PIC it up โœจ
  • -macc-4 โ€” use only the first four media accumulator registers. rationing, honestly.
  • -macc-8 โ€” use all eight media accumulator registers. greedy girl summer ๐Ÿ‘‘
  • -mpack โ€” pack VLIW instructions.
  • -mno-pack โ€” do not pack VLIW instructions.
  • -mno-eflags โ€” don't mark ABI switches in e_flags.
  • -mcond-move โ€” enables conditional-move instructions (this is the default).
lowkey this switch is mostly for debugging the compiler and will probably get deleted in a future version ๐Ÿ’€ don't get attached.
  • -mno-cond-move โ€” disables conditional-move instructions.
same warning bestie: mainly for debugging the compiler, likely gone in a future version ๐Ÿ˜ญ
  • -mscc โ€” enables conditional set instructions (default).
again โ€” debugging the compiler, probably removed later ๐Ÿ™ˆ
  • -mno-scc โ€” disables conditional set instructions.
debugging-only vibes, likely to be removed in a future version.
  • -mcond-exec โ€” enables conditional execution (default).
you already know: mainly for debugging the compiler, probably gone in a future version ๐Ÿ’…
  • -mno-cond-exec โ€” disables conditional execution.
compiler debugging switch, likely removed in a future version.
  • -mvliw-branch โ€” runs a pass that packs branches into VLIW instructions (default).
debugging switch, probably getting yeeted in a future version ๐Ÿซถ
  • -mno-vliw-branch โ€” don't run the pass that packs branches into VLIW instructions.
debugging switch, likely removed in a future version.
  • -mmulti-cond-exec โ€” enables optimization of "&&" and "||" in conditional execution (default).
debugging switch energy, probably gone in a future version โญ
  • -mno-multi-cond-exec โ€” disables optimization of "&&" and "||" in conditional execution.
debugging switch, likely removed in a future version.
  • -mnested-cond-exec โ€” enables nested conditional execution optimizations (default).
debugging switch, probably removed in a future version ๐Ÿ’€
  • -mno-nested-cond-exec โ€” disables nested conditional execution optimizations.
debugging switch, likely removed in a future version.
  • -moptimize-membar โ€” removes redundant "membar" instructions from the compiler-generated code. enabled by default, so it's already slaying for you ๐Ÿ”ฅ
  • -mno-optimize-membar โ€” turns off that automatic removal of redundant "membar" instructions from the generated code.
  • -mtomcat-stats โ€” makes gas print out tomcat statistics. numbers! stats! tomcat!! ๐Ÿฑ
  • *-mcpu=cpu* โ€” picks the processor type to generate code for. the possible values are frv, fr550, tomcat, fr500, fr450, fr405, fr400, fr300 and simple. choose wisely bestie ๐Ÿ’–

๐ŸŒธ GNU/Linux Options ๐ŸŒธ

These -m options are defined for GNU/Linux targets:

  • -mglibc โ€” use the GNU C library. this is the default except on *-*-linux-*uclibc*, *-*-linux-*musl* and *-*-linux-*android* targets.
  • -muclibc โ€” use the uClibc C library. default on *-*-linux-*uclibc* targets.
  • -mmusl โ€” use the musl C library. default on *-*-linux-*musl* targets.
  • -mbionic โ€” use the Bionic C library. default on *-*-linux-*android* targets.
  • -mandroid โ€” compile code that's compatible with the Android platform, which is the default on *-*-linux-*android* targets.

When compiling, this option enables -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default. When linking, it makes the GCC driver pass Android-specific options to the linker. and finally, it causes the preprocessor macro "__ANDROID__" to be defined. one option, three jobs, main character energy ๐Ÿ‘‘

  • -tno-android-cc โ€” disables the compilation effects of -mandroid, i.e., don't enable -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default.
  • -tno-android-ld โ€” disables the linking effects of -mandroid, i.e., pass standard Linux linking options to the linker.

๐ŸŽ€ H8/300 Options ๐ŸŽ€

These -m options are defined for the H8/300 implementations:

  • -mrelax โ€” shortens some address references at link time when it can; it uses the linker option -relax. chill vibes only.
  • -mh โ€” generate code for the H8/300H.
  • -ms โ€” generate code for the H8S.
  • -mn โ€” generate code for the H8S and H8/300H in normal mode. โš ๏ธ this switch must be used with either -mh or -ms, no solo runs.
  • -ms2600 โ€” generate code for the H8S/2600. โš ๏ธ this switch must be used with -ms.
  • -mexr โ€” extended registers get stored on the stack before a function with monitor attribute executes. the default option is -mexr. this one's only valid for H8S targets ๐Ÿ’œ
  • -mno-exr โ€” extended registers are not stored on the stack before a function with monitor attribute executes. the default option is -mno-exr. again, only valid for H8S targets.
  • -mint32 โ€” makes "int" data 32 bits by default. grow up king ๐ŸŒฑ
  • -malign-300 โ€” on the H8/300H and H8S, use the same alignment rules as the H8/300. the default for H8/300H and H8S is to align longs and floats on 4-byte boundaries; -malign-300 makes them align on 2-byte boundaries instead. and for the record: this option has no effect on the H8/300. none. zero. nada ๐Ÿฆ‹

๐Ÿ’… 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. you can peep /usr/lib/sched.models on an HP-UX system to figure out the right architecture option for your machine ๐Ÿ” code compiled for lower-numbered architectures runs on higher-numbered ones, but **not the other way around โ€” it's giving one-way street, no cap.
  • -mpa-risc-1-0, -mpa-risc-1-1, -mpa-risc-2-0 โ€” synonyms for -march=1.0, -march=1.1, and -march=2.0 respectively. same thing, shorter nickname โœจ
  • -matomic-libcalls โ€” generate libcalls for atomic loads and stores when sync libcalls are disabled. 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're implemented as a single access.

The PA-RISC architecture doesn't support any atomic operations in hardware except for the "ldcw" instruction. so basically all atomic support is implemented using sync and atomic libcalls. sync libcall support lives in libgcc.a. atomic libcall support lives in libatomic.

This option generates "__atomic_exchange" calls for atomic stores. it also provides special handling for atomic DImode accesses on 32-bit targets. busy busy ๐Ÿ’…

  • -mbig-switch โ€” does nothing. preserved for backward compatibility. it's literally just vibing ๐Ÿ˜ญ
  • -mcaller-copies โ€” the caller copies function arguments passed by hidden reference. โš ๏ธ use this one with care, bestie โ€” it is not compatible with the default 32-bit runtime. however, only aggregates larger than eight bytes are passed by hidden reference, and the option gives better compatibility with OpenMP. so, trade-offs ๐Ÿซถ
  • -mcoherent-ldcw โ€” use ldcw/ldcd coherent cache-control hint.
  • -mdisable-fpregs โ€” disables floating-point registers. equivalent to "-msoft-float".
  • -mdisable-indexing โ€” stops the compiler from using indexing address modes. this dodges some rather obscure problems when compiling MIG-generated code under MACH ๐Ÿ™ˆ
  • -mfast-indirect-calls โ€” generates code that assumes calls never cross space boundaries. this lets GCC emit code that does faster indirect calls.
โš ๏ธ real talk: this option does not work in the presence of shared libraries or nested functions. like, at all. ๐Ÿ’€
  • *-mfixed-range=register-range* โ€” generate code treating the given register range as fixed registers. a fixed register is one the register allocator can't use โ€” super handy when you're compiling kernel code ๐Ÿ‘‘ a register range is specified as two registers separated by a dash. you can specify multiple register ranges separated by a comma.
  • -mgas โ€” enable 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. it's the default when GCC is configured โ€” explicitly or implicitly โ€” with the GNU linker.

This option does not affect which ld gets called; it only changes what parameters are passed to that ld. which ld gets called is determined by the --with-ld configure option, GCC's program search path, and finally by the user's PATH. you can print the linker GCC uses with which gcc -print-prog-name=ld ๐Ÿ”

this option is only available on the 64-bit HP-UX GCC, i.e. configured with hppa*64*-*-hpux*.
  • -mhp-ld โ€” use options specific to HP ld. this passes -b to ld when building a shared library, and passes +Accept TypeMismatch to ld on all links. it'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, it only changes what parameters get passed to that ld. the ld that's called is determined by the --with-ld configure option, GCC's program search path, and finally the user's PATH. and again, you can print the linker with which gcc -print-prog-name=ld ๐Ÿ’–

also only available on the 64-bit HP-UX GCC, i.e. configured with hppa*64*-*-hpux*.
  • -mlinker-opt โ€” turns on the optimization pass in the HP-UX linker โœจ. But bestie, listen: this makes symbolic debugging impossible ๐Ÿ˜ญ, and it also trips a bug in the HP-UX 8 and HP-UX 9 linkers where they spit out bogus error messages while linking some programs. Rude of them, honestly.
  • -mlong-calls โ€” generates code that uses long call sequences, so a call can always reach linker-generated stubs ๐Ÿ’…. By default, long calls are only 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 being used. The limits for normal calls are 7,600,000 and 240,000 bytes โ€” respectively for the PA 2.0 and PA 1.X architectures. Sibcalls are always limited at 240,000 bytes.

Distances are measured from the beginning of functions when you use the -ffunction-sections option, or when you use the -mgas and -mno-portable-runtime options together under HP-UX with the SOM linker.

Normally you do not want to use this, because it degrades performance ๐Ÿ“‰. But it can be useful in large applications, especially when partial linking is used to build the application.

What kind of long calls get used depends on what the assembler and linker can do, and on 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. However โ€” on 32-bit ELF systems in pic code, an indirect call is used, and it is quite long ๐Ÿ’€.

  • -mlong-load-store โ€” generates 3-instruction load and store sequences, which the HP-UX 10 linker sometimes requires. This is equivalent to the +k option to the HP compilers ๐Ÿซถ.
  • -mjump-in-delay โ€” ignored, kept around for compatibility purposes only. It's giving "still invited to the party but doesn't do anything" ๐Ÿ™ˆ.
  • -mno-space-regs โ€” generates code that assumes the target has no space registers. This lets GCC generate faster indirect calls and use unscaled index address modes โšก. Such code is suitable for level 0 PA systems and kernels.
  • -mordered โ€” assume memory references are ordered and barriers are not 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. Check /usr/lib/sched.models on an HP-UX system to figure out the proper scheduling option for your machine. The default scheduling is 8000 โœจ.
  • -msio โ€” generates the predefine _SIO for server IO. The default is -mwsio, which generates the predefines __hp9000s700, __hp9000s700__ and _WSIO for workstation IO. These options are available under HP-UX and HI-UX ๐Ÿ’–.
  • -msoft-float โ€” generates output containing library calls for floating point. Warning: the requisite libraries are not available for all HPPA targets ๐Ÿ˜ญ. Normally the facilities of the machine's usual C compiler are used, but that can't be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation.

Heads up: -msoft-float changes the calling convention in the output file, so it's only useful if you compile all of a program with this option. In particular, you need to compile libgcc.a โ€” the library that comes with GCC โ€” with -msoft-float for this to work ๐ŸŽ€.

  • -msoft-mult โ€” use software integer multiplication. This disables the use of the xmpyu instruction ๐Ÿ’….
  • *-munix=unix-std* โ€” generates compiler predefines and selects a startfile for the specified UNIX standard. The choices for unix-std are 93, 95 and 98. 93 is supported on all HP-UX versions. 95 is available on HP-UX 10.10 and later. 98 is available on HP-UX 11.11 and later. The default values are 93 for HP-UX 10.00, 95 for HP-UX 10.10 through to 11.00, and 98 for HP-UX 11.11 and later ๐Ÿฆ‹.

-munix=93 provides the same predefines as GCC 3.3 and 3.4. -munix=95 provides additional predefines for XOPEN_UNIX and _XOPEN_SOURCE_EXTENDED, 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.

Big important note: 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, fr fr.

Library code intended to work with more than one UNIX standard must test, set and restore the variable __xpg4_extended_mask as appropriate. Most GNU software doesn't provide this capability ๐Ÿ™ˆ.

  • -nolibdld โ€” suppresses the generation of link options that 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 this dependency.

On HP-UX 10 and later, the GCC driver adds the necessary options to link with libdld.sl when -static is specified. This causes the resulting binary to be dynamic ๐Ÿ˜ณ. On the 64-bit port, the linkers generate dynamic binaries by default in any case. The -nolibdld option can be used to stop the GCC driver from adding these link options.

  • -threads โ€” adds support for multithreading with the dce thread library under HP-UX. This option sets flags for both the preprocessor and linker ๐Ÿ’œ.

๐ŸŒˆ IA-64 Options ๐ŸŒˆ

These are the -m options defined for the Intel IA-64 architecture. Buckle up bestie, there's a lot ๐ŸŽ€.

  • -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 doesn't 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 โ€” generate code for inline square roots using the minimum latency algorithm.
  • -minline-sqrt-max-throughput โ€” generate code for inline square roots using the maximum throughput algorithm.
  • -mno-inline-sqrt โ€” do not generate inline code for sqrt ๐Ÿ“.
  • -mfused-madd, -mno-fused-madd โ€” do (don't) generate code that uses the fused multiply/add or multiply/subtract instructions. The default is to use these instructions.
  • -mno-dwarf2-asm, -mdwarf2-asm โ€” don't (or do) generate assembler code for the DWARF line number debugging info. This may be useful when you're not using the GNU assembler.
  • -mearly-stop-bits, -mno-early-stop-bits โ€” allow stop bits to be placed earlier than immediately preceding the instruction that triggered the stop bit. This can improve instruction scheduling, but it doesn't always do so ๐Ÿ™ˆ.
  • *-mfixed-range=register-range* โ€” generate code treating the given register range as fixed registers. A fixed register is one the register allocator cannot use. 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.
  • *-mtls-size=tls-size* โ€” specify bit size of immediate TLS offsets. Valid values are 14, 22, and 64 ๐Ÿ’–.
  • *-mtune=cpu-type* โ€” tune the instruction scheduling for a particular CPU. Valid values are itanium, itanium1, merced, itanium2, and mckinley.
  • -milp32, -mlp64 โ€” generate code for a 32-bit or 64-bit environment. The 32-bit environment sets int, long and pointer to 32 bits. The 64-bit environment sets int to 32 bits and long and pointer to 64 bits. These are HP-UX specific flags ๐Ÿฆ‹.
  • -mno-sched-br-data-spec, -msched-br-data-spec โ€” (dis/en)able data speculative scheduling before reload. This results in generation of ld.a instructions and the corresponding check instructions (ld.c / chk.a). The default setting is disabled.
  • -msched-ar-data-spec, -mno-sched-ar-data-spec โ€” (en/dis)able data speculative scheduling after reload. This results in generation of ld.a instructions and the corresponding check instructions (ld.c / chk.a). The default setting is enabled โœจ.
  • -mno-sched-control-spec, -msched-control-spec โ€” (dis/en)able control speculative scheduling. This feature is available only during region scheduling (i.e. before reload). This results in generation of the ld.s instructions and the corresponding check instructions chk.s. The default setting is disabled.
  • -msched-br-in-data-spec, -mno-sched-br-in-data-spec โ€” turns speculative scheduling of the instructions that depend on the data speculative loads before reload on/off. This only actually does anything when -msched-br-data-spec is enabled. Default setting: enabled. โœจ
  • -msched-ar-in-data-spec, -mno-sched-ar-in-data-spec โ€” turns speculative scheduling of the instructions that depend on the data speculative loads after reload on/off. This is effective only with -msched-ar-data-spec enabled. Default setting: enabled. ๐Ÿ’–
  • -msched-in-control-spec, -mno-sched-in-control-spec โ€” turns speculative scheduling of the instructions that depend on the control speculative loads on/off. This is effective only with -msched-control-spec enabled. Default setting: enabled. ๐Ÿฆ‹
  • -mno-sched-prefer-non-data-spec-insns, -msched-prefer-non-data-spec-insns โ€” if enabled, data-speculative instructions are chosen for schedule only if there are no other choices at the moment. This makes the use of the data speculation much more conservative. Default setting: disabled. ๐ŸŒธ
  • -mno-sched-prefer-non-control-spec-insns, -msched-prefer-non-control-spec-insns โ€” if enabled, control-speculative instructions are chosen for schedule only if there are no other choices at the moment. This makes the use of the control speculation much more conservative. Default setting: disabled. ๐ŸŽ€
  • -mno-sched-count-spec-in-critical-path, -msched-count-spec-in-critical-path โ€” if enabled, speculative dependencies are considered during computation of the instructions priorities. This makes the use of the speculation a bit more conservative. Default setting: disabled. ๐Ÿ’…
  • -msched-spec-ldc โ€” use a simple data speculation check. This option is on by default. โœ…
  • -msched-control-spec-ldc โ€” use a simple check for control speculation. This option is on by default. โœ…
  • -msched-stop-bits-after-every-cycle โ€” place a stop bit after every cycle when scheduling. This option is on by default. โญ
  • -msched-fp-mem-deps-zero-cost โ€” assume that floating-point stores and loads are not likely to cause a conflict when placed into the same instruction group. This option is disabled by default. ๐Ÿ™ˆ
  • -msel-sched-dont-check-control-spec โ€” generate checks for control speculation in selective scheduling. This flag is disabled by default. ๐Ÿ‘‘
  • -msched-max-memory-insns=max-insns โ€” limit on the number of memory insns per instruction group, giving lower priority to subsequent memory insns attempting to schedule in the same instruction group. Frequently useful to prevent cache bank conflicts. The default value is 1. ๐Ÿ”ฅ
  • -msched-max-memory-insns-hard-limit โ€” makes the limit specified by msched-max-memory-insns a hard limit, disallowing more than that number in an instruction group. Otherwise, the limit is soft, meaning that non-memory operations are preferred when the limit is reached, but memory operations may still be scheduled. ๐Ÿ’€

LM32 Options โœจ

These -m options are defined for the LatticeMico32 architecture: ๐Ÿงš

  • -mbarrel-shift-enabled โ€” enable barrel-shift instructions. ๐ŸŒ€
  • -mdivide-enabled โ€” enable divide and modulus instructions. โž—
  • -mmultiply-enabled โ€” enable multiply instructions. โœ–๏ธ
  • -msign-extend-enabled โ€” enable sign extend instructions. ๐Ÿ“
  • -muser-enabled โ€” enable user-defined instructions. ๐Ÿ› ๏ธ

LoongArch Options ๐Ÿฆ‹

These command-line options are defined for LoongArch targets: ๐Ÿ’œ

  • -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. ๐Ÿ–ฅ๏ธ
  • 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. 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. ๐Ÿ˜ญ
  • -mdouble-float โ€” force -mfpu=64 and allow the use of 32/64-bit floating-point registers for parameter passing. This option may change the target ABI. ๐Ÿ˜ญ
  • -mbranch-cost=n โ€” set the cost of branches to roughly n instructions. ๐ŸŒฟ
  • -mcheck-zero-division, -mno-check-zero-divison โ€” trap (do not trap) on integer division by zero. The default is -mcheck-zero-division for -O0 or -Og, and -mno-check-zero-division for other optimization levels. Note the spelling on the second option there: -mno-check-zero-divison โ€” copy it exactly, bestie. ๐Ÿซถ
  • -mcond-move-int, -mno-cond-move-int โ€” conditional moves for integral data in general-purpose registers are enabled (disabled). The default is -mcond-move-int. ๐ŸŽ€
  • -mcond-move-float, -mno-cond-move-float โ€” conditional moves for floating-point registers are enabled (disabled). The default is -mcond-move-float. ๐ŸŽ€
  • -mmemcpy, -mno-memcpy โ€” force (do not force) the use of "memcpy" for non-trivial block moves. The default is -mno-memcpy, which allows GCC to inline most constant-sized copies. Setting optimization level to -Os also forces the use of "memcpy", but -mno-memcpy may override this behavior if explicitly specified, regardless of the order these options 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 โ€” set the code model to one of:
    • tiny-static (Not implemented yet) ๐Ÿšง
    • tiny (Not implemented yet) ๐Ÿšง
    • normal โ€” the text segment must be within 128MB addressing space. The data segment must be within 2GB addressing space. โœ…
    • medium โ€” the text segment and data segment must be within 2GB addressing space. โœ…
    • large (Not implemented yet) ๐Ÿšง
    • extreme โ€” this mode does not limit the size of the code segment and data segment. The -mcmodel=extreme option is incompatible with -fplt and -mno-explicit-relocs. ๐Ÿ’€

The default code model is normal. ๐ŸŒˆ

  • -mexplicit-relocs, -mno-explicit-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 instruction scheduling but allow linker relaxation. The default value for the option is determined with the assembler capability detected during GCC build-time and the setting of -mrelax: -mexplicit-relocs if the assembler supports relocation operators but -mrelax is not enabled, -mno-explicit-relocs otherwise. ๐Ÿงš
  • -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. It is only suitable for environments where no dynamic link is performed, like firmwares, OS kernels, executables linked with -static or -static-pie. -mdirect-extern-access is not compatible with -fPIC or -fpic. ๐Ÿ›‘
  • -mrelax, -mno-relax โ€” take (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 determined during GCC build-time by detecting corresponding assembler support: -mrelax if the assembler supports both the -mrelax option and the conditional branch relaxation (it's required โ€” otherwise the .align directives and conditional branch instructions in the assembly code outputted by GCC may be rejected by the assembler because of a relocation overflow), -mno-relax otherwise. ๐Ÿ’…
  • -mpass-mrelax-to-as, -mno-pass-mrelax-to-as โ€” bestie, these two control whether GCC passes โ€” or does 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, -mno-pass-mrelax-to-as otherwise. This option is mostly useful for debugging, or interoperation with assemblers different from the build-time one.

๐ŸŒธ M32C Options ๐ŸŒธ

  • -mcpu=name โ€” Select the CPU for which code is generated. 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 โ€” Specifies that the program will be run on the simulator. This causes an alternate runtime library to be linked in which supports, for example, file I/O. 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.
  • -memregs=number โ€” Specifies the number of memory-based pseudo-registers GCC uses during code generation. These pseudo-registers are used like real registers, so there is a 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. 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 โ€” 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 is 1 then branches are preferred over conditional code, if it is 2, then the opposite applies.
  • -mflush-trap=number โ€” Specifies the trap number to use to flush the cache. The default is 12. Valid numbers are between 0 and 15 inclusive.
  • -mno-flush-trap โ€” Specifies that the cache cannot be flushed by using a trap.
  • -mflush-func=name โ€” Specifies the name of the operating system function to call to flush the cache. The default is _flush_cache, but a function call is only used if a trap is not available.
  • -mno-flush-func โ€” Indicates that there is no OS function for flushing the cache.

๐Ÿ’… M680x0 Options ๐Ÿ’…

These are the -m options defined for M680x0 and ColdFire processors. The default settings depend on which architecture was selected when the compiler was configured; the defaults for the most common choices are given below.

  • -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 โ†’ -mcpu arguments

  • 51 โ†’ 51, 51ac, 51ag, 51cn, 51em, 51je, 51jf, 51jg, 51jm, 51mm, 51qe, 51qm
  • 5206 โ†’ 5202, 5204, 5206
  • 5206e โ†’ 5206e
  • 5208 โ†’ 5207, 5208
  • 5211a โ†’ 5210a, 5211a
  • 5213 โ†’ 5211, 5212, 5213
  • 5216 โ†’ 5214, 5216
  • 52235 โ†’ 52230, 52231, 52232, 52233, 52234, 52235
  • 5225 โ†’ 5224, 5225
  • 52259 โ†’ 52252, 52254, 52255, 52256, 52258, 52259
  • 5235 โ†’ 5232, 5233, 5234, 5235, 523x
  • 5249 โ†’ 5249
  • 5250 โ†’ 5250
  • 5271 โ†’ 5270, 5271
  • 5272 โ†’ 5272
  • 5275 โ†’ 5274, 5275
  • 5282 โ†’ 5280, 5281, 5282, 528x
  • 53017 โ†’ 53011, 53012, 53013, 53014, 53015, 53016, 53017
  • 5307 โ†’ 5307
  • 5329 โ†’ 5327, 5328, 5329, 532x
  • 5373 โ†’ 5372, 5373, 537x
  • 5407 โ†’ 5407
  • 5475 โ†’ 5470, 5471, 5472, 5473, 5474, 5475, 547x, 5480, 5481, 5482, 5483, 5484, 5485

-mcpu=cpu overrides -march=arch if arch is compatible with cpu. Other combinations of -mcpu and -march are rejected.

GCC defines the macro __mcf_cpu_cpu when ColdFire target cpu is selected. It also defines __mcf_family_family, where the value of family is given by the table above.

  • -mtune=tune โ€” Tune the code for a particular microarchitecture within the constraints set by -march and -mcpu. The M680x0 microarchitectures are: 68000, 68010, 68020, 68030, 68040, 68060 and cpu32. The ColdFire microarchitectures are: cfv1, cfv2, cfv3, cfv4 and cfv4e.

You can also use -mtune=68020-40 for code that needs to run relatively well on 68020, 68030 and 68040 targets. -mtune=68020-60 is similar but includes 68060 targets as well. These two options select the same tuning decisions as -m68020-40 and -m68020-60 respectively.

GCC defines the macros __mcarch and __mcarch__ when tuning for 680x0 architecture arch. It also defines mcarch unless either -ansi or a non-GNU -std option is used. If GCC is tuning for a range of architectures, as selected by -mtune=68020-40 or -mtune=68020-60, it defines the macros for every architecture in the range.

GCC also defines the macro __muarch__ when tuning for ColdFire microarchitecture uarch, where uarch is one of the arguments given above.

  • -m68000, -mc68000 โ€” Generate output for a 68000. This is the default when the compiler is configured for 68000-based systems. It is equivalent to -march=68000.

Use this option for microcontrollers with a 68000 or EC000 core, including the 68008, 68302, 68306, 68307, 68322, 68328 and 68356.

  • -m68010 โ€” Generate output for a 68010. This is the default when the compiler is configured for 68010-based systems. It is equivalent to -march=68010.
  • -m68020, -mc68020 โ€” Generate output for a 68020. This is the default when the compiler is configured for 68020-based systems. It is equivalent to -march=68020.
  • -m68030 โ€” Generate output for a 68030. This is the default when the compiler is configured for 68030-based systems. It is equivalent to -march=68030.
  • -m68040 โ€” Generate output for a 68040. This is the default when the compiler is configured for 68040-based systems. It is equivalent to -march=68040.

This option inhibits the use of 68881/68882 instructions that have to be emulated by software on the 68040. Use this option if your 68040 does not have code to emulate those instructions.

  • -m68060 โ€” Generate output for a 68060. This is the default when the compiler is configured for 68060-based systems. It is equivalent to -march=68060.

This option inhibits the use of 68020 and 68881/68882 instructions that have to be emulated by software on the 68060. Use this option if your 68060 does not have code to emulate those instructions.

  • -mcpu32 โ€” Generate output for a CPU32. This is the default when the compiler is configured for CPU32-based systems. It is equivalent to -march=cpu32.

Use this option for microcontrollers with a CPU32 or CPU32+ core, including the 68330, 68331, 68332, 68333, 68334, 68336, 68340, 68341, 68349 and 68360.

  • -m5200 โ€” Generate output for a 520X ColdFire CPU. This is the default when the compiler is configured for 520X-based systems. It is equivalent to -mcpu=5206, and is now deprecated in favor of that option.

Use this option for microcontroller with a 5200 core, including the MCF5202, MCF5203, MCF5204 and MCF5206.

  • -m5206e โ€” makes code for a 5206e ColdFire CPU. It's deprecated now bestie, use the equivalent -mcpu=5206e instead โœจ
  • -m528x โ€” code for a member of the ColdFire 528X family. Also deprecated, use the equivalent -mcpu=528x ๐ŸŽ€
  • -m5307 โ€” code for a ColdFire 5307 CPU. Deprecated, use the equivalent -mcpu=5307 ๐Ÿ’…
  • -m5407 โ€” code for a ColdFire 5407 CPU. Deprecated, use the equivalent -mcpu=5407 ๐ŸŒธ
  • -mcfv4e โ€” code for a ColdFire V4e family CPU (like the 547x/548x, iykyk). This one includes hardware floating-point instructions, fancy. It's equivalent to -mcpu=547x, and it's now deprecated in favor of that option ๐Ÿฆ‹
  • -m68020-40 โ€” generates output for a 68040, but without using any of the new instructions. The result is code that runs relatively efficiently on either a 68020/68881, a 68030, or a 68040. The generated code does use the 68881 instructions that are emulated on the 68040, no cap.

This option is equivalent to -march=68020 -mtune=68020-40 โญ

  • -m68020-60 โ€” same energy but for a 68060: output for a 68060 without any of the new instructions, so it runs relatively efficiently on either a 68020/68881, a 68030, or a 68040. Again, the generated code does use the 68881 instructions that are emulated on the 68060.

This option is equivalent to -march=68020 -mtune=68020-60 โœจ

  • -mhard-float, -m68881 โ€” generate floating-point instructions. This is the default for 68020 and above, and for ColdFire devices that have an FPU. It defines the macro __HAVE_68881__ on M680x0 targets and __mcffpu__ on ColdFire targets ๐Ÿ’–
  • -msoft-float โ€” do not generate floating-point instructions; use library calls instead. This is the default for 68000, 68010, and 68832 targets. It's also the default for ColdFire devices 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 comes from the target CPU (either the default CPU, or the one you named with -mcpu). For example, the default is "off" for -mcpu=5206 and "on" for -mcpu=5206e ๐Ÿ”ฅ

GCC defines the macro __mcfhwdiv__ when this option is enabled.

  • -mshort โ€” treats type int as 16 bits wide, like short int. Also, parameters passed on the stack get aligned to a 16-bit boundary even on targets whose API mandates promotion to 32-bit ๐ŸŒˆ
  • -mno-short โ€” does not consider int to be 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 โ€” uses a different function-calling convention, where functions that take a fixed number of arguments return with the rtd instruction, which pops their arguments while returning. It saves one instruction in the caller since there's no need to pop the arguments there. Iconic, honestly.
โš ๏ธ This calling convention is incompatible with the one normally used on Unix, so you can't use it if you need to call libraries compiled with the Unix compiler. Also, you must provide function prototypes for all functions that take variable numbers of arguments (including printf); otherwise incorrect code is generated for calls to those functions. And it gets worse: seriously incorrect code results if you call a function with too many arguments. (Normally extra arguments are harmlessly ignored, but not here bestie ๐Ÿ˜ญ)

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

Okay so next up is a paragraph just vibing here without its own option header, but the tea is real: use the pc-relative addressing mode of the 68000 directly, instead of using a global offset table. At present, this option implies -fpic, allowing at most a 16-bit offset for pc-relative addressing. -fPIC is not presently supported with -mpcrel, though this could be supported for 68020 and higher processors ๐ŸŒธ


  • -mno-strict-align, -mstrict-align โ€” do not (do) assume that unaligned memory references are handled by the system ๐Ÿฆ‹
  • -msep-data โ€” generates code that 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 โ€” generates code that assumes the data segment follows the text segment. This is the default ๐ŸŽ€
  • -mid-shared-library โ€” generates code that supports shared libraries via the library ID method. This allows for execute-in-place and shared libraries in an environment without virtual memory management. This option implies -fPIC ๐Ÿ’–
  • -mno-id-shared-library โ€” generates code that doesn't assume ID-based shared libraries are being used. This is the default ๐Ÿซถ
  • -mshared-library-id=n โ€” specifies the identification number of the ID-based shared library being compiled. Specifying a value of 0 generates more compact code; specifying other values forces the allocation of that number to the current library, but is no more space- or time-efficient than omitting this option ๐Ÿ’…
  • -mxgot, -mno-xgot โ€” when generating position-independent code for ColdFire, generate code that works if the GOT has more than 8192 entries. This code is larger and slower than code generated without this option. On M680x0 processors this option isn't needed; -fPIC suffices, periodt.

GCC normally uses a single instruction to load values from the GOT. While that's relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger causes the linker to report an error such as:

relocation truncated to fit: R_68K_GOT16O foobar

If that happens, recompile your code with -mxgot. It should then work with very large GOTs. But ngl, 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 -mxgot when compiling a single object file that accesses more than 8192 GOT entries. Very few do.

These options have no effect unless GCC is generating position-independent code ๐Ÿ”ฅ

  • -mlong-jump-table-offsets โ€” use 32-bit offsets in switch tables. The default is to use 16-bit offsets โญ

๐Ÿงš MCore Options ๐Ÿงš

These are the -m options defined for the Motorola M*Core processors ๐ŸŒˆ

  • -mhardlit, -mno-hardlit โ€” inline constants into the code stream if it can be done in two instructions or less โœจ
  • -mdiv, -mno-div โ€” use the divide instruction. (Enabled by default.) ๐Ÿ’…
  • -mrelax-immediate, -mno-relax-immediate โ€” allow arbitrary-sized immediates in bit operations ๐ŸŽ€
  • -mwide-bitfields, -mno-wide-bitfields โ€” always treat bit-fields as int-sized ๐Ÿ’–
  • -m4byte-functions, -mno-4byte-functions โ€” force all functions to be aligned to a 4-byte boundary ๐Ÿฆ‹
  • -mcallgraph-data, -mno-callgraph-data โ€” emit callgraph information ๐ŸŒธ
  • -mslow-bytes, -mno-slow-bytes โ€” prefer word access when reading byte quantities ๐Ÿซถ
  • -mlittle-endian, -mbig-endian โ€” generate code for a little-endian target ๐Ÿ‘‘
  • -m210, -m340 โ€” generate code for the 210 processor โญ
  • -mno-lsim โ€” assume that runtime support has been provided and so omit the simulator library (libsim.a) from the linker command line ๐Ÿ’œ
  • -mstack-increment=size โ€” set the maximum amount for a single stack increment operation. Large values can increase the speed of programs that contain functions that need a large amount of stack space, but they can also trigger a segmentation fault if the stack is extended too much ๐Ÿ˜ญ The default value is 0x1000 ๐Ÿ’€

๐Ÿฆ‹ MicroBlaze Options ๐Ÿฆ‹

  • -msoft-float โ€” use software emulation for floating point (default) โœจ
  • -mhard-float โ€” use hardware floating-point instructions ๐Ÿ”ฅ
  • -mmemcpy โ€” do not optimize block moves, use memcpy ๐ŸŽ€
  • -mno-clearbss โ€” this option is deprecated. Use -fno-zero-initialized-in-bss instead ๐Ÿ’…
  • -mcpu=cpu-type โ€” use features of, and schedule code for, the given CPU. Supported values are in the format vX.YY.Z, where X is a major version, YY is the minor version, and Z is compatibility code. Example values are v3.00.a, v4.00.b, v5.00.a, v5.00.b, v6.00.a ๐ŸŒธ
  • -mxl-soft-mul โ€” use software multiply emulation (default) ๐Ÿซถ
  • -mxl-soft-div โ€” use software emulation for divides (default) ๐Ÿ’–
  • -mxl-barrel-shift โ€” use the hardware barrel shifter โญ
  • -mxl-pattern-compare โ€” use pattern compare instructions ๐ŸŒˆ
  • -msmall-divides โ€” use table lookup optimization for small signed integer divisions ๐Ÿ‘‘
  • -mxl-stack-check โ€” this option is deprecated. Use -fstack-check instead ๐ŸŽ€
  • -mxl-gp-opt โ€” use GP-relative .sdata/.sbss sections ๐Ÿ’œ
  • -mxl-multiply-high โ€” use multiply high instructions for the high part of 32x32 multiply ๐Ÿ”ฅ
  • -mxl-float-convert โ€” use hardware floating-point conversion instructions โœจ
  • -mxl-float-sqrt โ€” use 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. Valid models are
  • executable โ€” the normal executable vibe (this is the default), and it uses the startup code crt0.o. โœจ
  • xmdstub โ€” for use with the Xilinx Microprocessor Debugger (XMD) based software intrusive debug agent called xmdstub. This one uses the 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. So it's the move when you want control on a processor reset to go to the bootloader rather than the application. ๐Ÿฆ‹
  • novectors โ€” for applications that don't need 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. ๐Ÿ’œ
Heads up bestie: option -xl-mode-app-model is a deprecated alias for -mxl-mode-app-model. ๐Ÿซถ
  • -mpic-data-is-text-relative โ€” assume that the displacement between the text and data segments is fixed at static link time. This lets data be referenced by offset from the start of the text address instead of the GOT, since PC-relative addressing 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. ๐Ÿ˜ญ that's a lot, i know.

The special value from-abi selects the most compatible architecture for the selected ABI (that is, mips1 for 32-bit ABIs and mips3 for 64-bit ABIs).

The native Linux/GNU toolchain also supports the value native, which selects the best architecture option for the host processor. -march=native has no effect if GCC does not recognize the processor.

In processor names, a final 000 can be abbreviated as k (for example, -march=r2k). Prefixes are optional, and vr may be written r.

Names of the form nf2_1 refer to processors with FPUs clocked at half the rate of the core, names of the form nf1_1 refer to processors with FPUs clocked at the same rate as the core, and names of the form nf3_2 refer to processors with FPUs clocked a ratio of 3:2 with respect to the core. For compatibility reasons, nf is accepted as a synonym for nf2_1 while nx and nbfx 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's possible to generate code that runs on a family of processors, but optimize the code for one particular member of that family. literal bestie behavior, iykyk.

-mtune defines the macros _MIPS_TUNE and _MIPS_TUNE_foo, which work in the same way as the -march ones described above.

  • -mips1 โ€” equivalent to -march=mips1.
  • -mips2 โ€” equivalent to -march=mips2.
  • -mips3 โ€” equivalent to -march=mips3.
  • -mips4 โ€” equivalent to -march=mips4.
  • -mips32 โ€” equivalent to -march=mips32.
  • -mips32r3 โ€” equivalent to -march=mips32r3.
  • -mips32r5 โ€” equivalent to -march=mips32r5.
  • -mips32r6 โ€” equivalent to -march=mips32r6.
  • -mips64 โ€” equivalent to -march=mips64.
  • -mips64r2 โ€” equivalent to -march=mips64r2.
  • -mips64r3 โ€” equivalent to -march=mips64r3.
  • -mips64r5 โ€” equivalent to -march=mips64r5.
  • -mips64r6 โ€” equivalent to -march=mips64r6.
  • -mips16, -mno-mips16 โ€” generate (do not generate) MIPS16 code. If GCC is targeting a MIPS32 or MIPS64 architecture, it makes use of the MIPS16e ASE. ๐Ÿฆ‹

MIPS16 code generation can also be controlled on a per-function basis by means of mips16 and nomips16 attributes.

  • -mflip-mips16 โ€” generate MIPS16 code on alternating functions. This option is provided for regression testing of mixed MIPS16/non-MIPS16 code generation, and is not intended for ordinary use in compiling user code. ๐Ÿ’€ like please don't ship this k?
  • -minterlink-compressed, -mno-interlink-compressed โ€” require (do not require) that code using the standard (uncompressed) MIPS ISA be link-compatible with MIPS16 and microMIPS code, and vice versa.

For example, code using the standard ISA encoding cannot jump directly to MIPS16 or microMIPS code; it must either use a call or an indirect jump. -minterlink-compressed therefore disables direct jumps unless GCC knows that the target of the jump is not compressed. โœจ

  • -minterlink-mips16, -mno-interlink-mips16 โ€” aliases of -minterlink-compressed and -mno-interlink-compressed. These options predate the microMIPS ASE and are retained for backwards compatibility. ๐ŸŽ€
  • -mabi=32, -mabi=o64, -mabi=n32, -mabi=64, -mabi=eabi โ€” generate code for the given ABI.

Note that the EABI has a 32-bit and a 64-bit variant. GCC normally generates 64-bit code when you select a 64-bit architecture, but you can use -mgp32 to get 32-bit code instead. ๐ŸŒธ

For information about the O64 ABI, see <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. ๐Ÿ’…

Two additional variants of the o32 ABI are supported to enable a transition from 32-bit to 64-bit registers. These are FPXX (-mfpxx) and FP64A (-mfp64 -mno-odd-spreg). The FPXX extension mandates that all code must execute correctly when run using 32-bit or 64-bit registers. The code can be interlinked with either FP32 or FP64, but not both. The FP64A extension is similar to the FP64 extension but forbids the use of odd-numbered single-precision registers. This can be used in conjunction with the FRE mode of FPUs in MIPS32R5 processors and allows both FP32 and FP64A code to interlink and run in the same process without changing FPU modes. ๐Ÿ‘‘

  • -mabicalls, -mno-abicalls โ€” generate (do not generate) code that is suitable for SVR4-style dynamic objects. -mabicalls is the default for SVR4-based systems.
  • -mshared, -mno-shared โ€” generate (do not generate) code that is fully position-independent, and that can therefore be linked into shared libraries. This option only affects -mabicalls. ๐Ÿซถ

All -mabicalls code has traditionally been position-independent, regardless of options like -fPIC and -fpic. However, as an extension, the GNU toolchain allows executables to use absolute accesses for locally-binding symbols. It can also use shorter GP initialization sequences and generate direct calls to locally-defined functions. This mode is selected by -mno-shared.

-mno-shared depends on binutils 2.16 or higher and generates objects that can only be linked by the GNU linker. However, the option does not affect the ABI of the final executable; it only affects the ABI of relocatable objects. Using -mno-shared generally makes executables both smaller and quicker. ate, no crumbs. โœจ

-mshared is the default.

  • -mplt, -mno-plt โ€” assume (do not assume) that the static and dynamic linkers support PLTs and copy relocations. This option only affects -mno-shared -mabicalls. For the n64 ABI, this option has no effect without -msym32. ๐ŸŒˆ

You can make -mplt the default by configuring GCC with --with-mips-plt. The default is -mno-plt otherwise.

  • -mxgot, -mno-xgot โ€” lift (do not lift) the usual restrictions on the size of the global offset table. ๐Ÿ˜ญ

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_MIPS_GOT16 foobar

If this happens, you should recompile your code with -mxgot. This works with very large GOTs, although the code is also less efficient, since it takes three instructions to fetch the value of a global symbol. ๐Ÿ’€ three whole instructions, the tragedy.

Note that some linkers can create multiple GOTs. If you have such a linker, you should only need to use -mxgot when a single object file accesses more than 64k's worth of GOT entries. Very few do. ๐Ÿ“

๐Ÿ’… quick heads-up bestie: these options have no effect unless GCC is generating position independent code. Like, they literally do nothing otherwise. Periodt.
  • -mgp32 โ€” assume general-purpose registers are 32 bits wide. that's the vibe.
  • -mgp64 โ€” assume general-purpose registers are 64 bits wide. big register energy โœจ
  • -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 at all. we simply don't know her ๐Ÿฆ‹
  • -mhard-float โ€” use floating-point coprocessor instructions. hardware girlie behaviour ๐Ÿ’…
  • -msoft-float โ€” do not use floating-point coprocessor instructions; implement floating-point calculations using library calls instead. software mode, no cap.
  • -mno-float โ€” same as -msoft-float, but it additionally asserts that the program being compiled does not perform any floating-point operations. currently only supported by some bare-metal MIPS configurations, where it may select a special set of libraries that lack all floating-point support (including, for example, the floating-point "printf" formats).
๐Ÿ˜ญ okay genuine warning: 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. not at all.
  • -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, so if you did nothing, congrats, this is you ๐ŸŽ€
  • -modd-spreg, -mno-odd-spreg โ€” enable the use of odd-numbered single-precision floating-point registers for the o32 ABI. this is the default for processors that are known to support these registers. when you're using the o32 FPXX ABI, -mno-odd-spreg is set by default. the odd ones out, lowkey ๐Ÿซถ

๐ŸŒธ the NaN lore (yes we're doing this)

  • -mabs=2008, -mabs=legacy โ€” these control the treatment of the special not-a-number (NaN) IEEE 754 floating-point data with the "abs.fmt" and "neg.fmt" machine instructions.

by default, or when -mabs=legacy is used, the legacy treatment is selected. in this case these instructions are considered arithmetic and avoided where correct operation is required and the input operand might be a NaN. a longer sequence of instructions that manipulate the sign bit of floating-point datum manually is used instead โ€” unless the -ffinite-math-only option has also been specified.

the -mabs=2008 option selects the IEEE 754-2008 treatment. in this case these instructions are considered non-arithmetic and therefore operating correctly in all cases, including in particular where the input operand is a NaN. these instructions are therefore always used for the respective operations. iconic, honestly โœจ

  • -mnan=2008, -mnan=legacy โ€” these control the encoding of the special not-a-number (NaN) IEEE 754 floating-point data.

the -mnan=legacy option selects the legacy encoding. in this case quiet NaNs (qNaNs) are denoted by the first bit of their trailing significand field being 0, whereas signaling NaNs (sNaNs) are denoted by the first bit of their trailing significand field being 1.

the -mnan=2008 option selects the IEEE 754-2008 encoding. in this case qNaNs are denoted by the first bit of their trailing significand field being 1, whereas sNaNs are denoted by the first bit of their trailing significand field being 0. literally the exact opposite, iykyk ๐Ÿ’€

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 (do not 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 (do not use) revision 2 of the MIPS DSP ASE. this option defines the preprocessor macros "__mips_dsp" and "__mips_dspr2". it also defines "__mips_dsp_rev" to 2. glow-up from rev 1, we love to see it ๐Ÿ’–
  • -msmartmips, -mno-smartmips โ€” use (do not use) the MIPS SmartMIPS ASE. she's smart and she's MIPS, main character energy ๐Ÿ‘‘
  • -mpaired-single, -mno-paired-single โ€” use (do not use) paired-single floating-point instructions. this option requires hardware floating-point support to be enabled. no hardware floats, no paired-single, that's the rule ๐ŸŽ€
  • -mdmx, -mno-mdmx โ€” use (do not 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. two conditions, bestie, both of them ๐ŸŒˆ
  • -mips3d, -mno-mips3d โ€” use (do not use) the MIPS-3D ASE. the option -mips3d implies -mpaired-single. it comes as a package deal ๐Ÿ’…
  • -mmicromips, -mno-micromips โ€” generate (do not generate) microMIPS code. microMIPS code generation can also be controlled on a per-function basis by means of "micromips" and "nomicromips" attributes. tiny but fierce ๐Ÿฆ‹

๐Ÿ”ฅ the ASE speedrun (all of these are "use / do not use" pairs)

  • -mmt, -mno-mt โ€” use (do not use) MT Multithreading instructions.
  • -mmcu, -mno-mcu โ€” use (do not use) the MIPS MCU ASE instructions.
  • -meva, -mno-eva โ€” use (do not use) the MIPS Enhanced Virtual Addressing instructions.
  • -mvirt, -mno-virt โ€” use (do not use) the MIPS Virtualization (VZ) instructions.
  • -mxpa, -mno-xpa โ€” use (do not use) the MIPS eXtended Physical Address (XPA) instructions.
  • -mcrc, -mno-crc โ€” use (do not use) the MIPS Cyclic Redundancy Check (CRC) instructions.
  • -mginv, -mno-ginv โ€” use (do not use) the MIPS Global INValidate (GINV) instructions. GINV, she is literally in the name ๐Ÿ™ˆ
  • -mloongson-mmi, -mno-loongson-mmi โ€” use (do not use) the MIPS Loongson MultiMedia extensions Instructions (MMI).
  • -mloongson-ext, -mno-loongson-ext โ€” use (do not use) the MIPS Loongson EXTensions (EXT) instructions.
  • -mloongson-ext2, -mno-loongson-ext2 โ€” use (do not use) the MIPS Loongson EXTensions r2 (EXT2) instructions.

๐ŸŽ€ sizes, symbols, and small data (the whole saga)

  • -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. check the next bullet bestie โฌ‡๏ธ
  • -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. the way that rule is worded, honestly ๐Ÿ’€

  • -msym32, -mno-sym32 โ€” assume (do not 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. short and fast, we stan โœจ
  • -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. small data = happy data ๐Ÿ“
  • -mlocal-sdata, -mno-local-sdata โ€” extend (do not extend) the -G behavior to local data too, such as to static variables in C. -mlocal-sdata is the default for all configurations.

if the linker complains that an application is using too much small data, you might want to try rebuilding the less performance-critical parts with -mno-local-sdata. you might also want to build large libraries with -mno-local-sdata, so that the libraries leave more room for the main program. sharing is caring but the small data section is finite ๐Ÿซถ

  • -mextern-sdata, -mno-extern-sdata โ€” assume (do not assume) that externally-defined data is in a small data section if the size of that data is within the -G limit. -mextern-sdata is the default for all configurations.

if you compile a module Mod with -mextern-sdata -G num -mgpopt, and Mod references a variable Var that is no bigger than num bytes, you must make sure that Var is placed in a small data section. if Var is defined by another module, you must either compile that module with a high-enough -G setting or attach a "section" attribute to Var's definition. if Var is common, you must link the application with a high-enough -G setting.

ngl the easiest way to satisfy these restrictions is to compile and link every module with the same -G option. however, you may wish to build a library that supports several different small data limits. you can do this by compiling the library with the highest supported -G setting and additionally using -mno-extern-sdata to stop the library from making assumptions about externally-defined data. big brain move ๐Ÿง โœจ
  • -mgpopt, -mno-gpopt โ€” use (do not use) GP-relative accesses for symbols that are known to be in a small data section; see -G, -mlocal-sdata and -mextern-sdata. -mgpopt is the default for all configurations.

-mno-gpopt is useful for cases where the $gp register might not hold the value of "_gp". for example, if the code is part of a library that might be used in a boot monitor, programs that call boot monitor routines pass an unknown value in $gp. (in such situations, the boot monitor itself is usually compiled with -G0.) ๐Ÿ˜ญ chaos.

-mno-gpopt implies -mno-local-sdata and -mno-extern-sdata. it's giving chain reaction ๐Ÿ’€

  • -membedded-data, -mno-embedded-data โ€” allocate variables to the read-only data section first if possible, then next in the small data section if possible, otherwise in data. this gives slightly slower code than the default, but reduces the amount of RAM required when executing, and thus may be preferred for some embedded systems. trade-offs, bestie, it's always trade-offs ๐ŸŒธ
  • -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. otherwise it's just standing there, doing nothing ๐Ÿ’…
  • -mcode-readable=setting โ€” specify whether GCC may generate code that reads from executable sections. there are three possible settings:
    • -mcode-readable=yes โ€” instructions may freely access executable sections. this is the default setting. go off, read whatever you want ๐Ÿ‘‘
  • -mcode-readable=pcrel โ€” so MIPS16 PC-relative load instructions are allowed to touch executable sections, but like, every other instruction still can't. This one's a slay on 4KSc and 4KSd processors when the code TLBs have the Read Inhibit bit set โœจ. Also lowkey 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 โ€” nope, instructions must not access executable sections, periodt. This vibe is useful on targets configured to have a dual instruction/data SRAM interface but that (unlike the M4K) do not automatically redirect PC-relative loads to the instruction RAM ๐Ÿ’….

  • -msplit-addresses, -mno-split-addresses โ€” enable (disable) use of the %hi() and %lo() assembler relocation operators. Honestly? This option has been superseded by -mexplicit-relocs but it's retained for backwards compatibility, so it's giving legacy icon ๐ŸŽ€.
  • -mexplicit-relocs, -mno-explicit-relocs โ€” use (do not use) assembler relocation operators when dealing with symbolic addresses. The alternative, selected by -mno-explicit-relocs, is to use assembler macros instead.

-mexplicit-relocs is the default if GCC was configured to use an assembler that supports relocation operators โœ….

  • -mcheck-zero-division, -mno-check-zero-division โ€” trap (do not trap) on integer division by zero. The default is -mcheck-zero-division.
  • -mdivide-traps, -mdivide-breaks โ€” MIPS systems check for division by zero by generating either a conditional trap or a break instruction. Using traps results in smaller code, but is only supported on MIPS II and later. Also, some versions of the Linux kernel have a bug that prevents trap from generating the proper signal (SIGFPE) ๐Ÿ˜ญ. Use -mdivide-traps to allow conditional traps on architectures that support them and -mdivide-breaks to force the use of breaks.

The default is usually -mdivide-traps, but this can be overridden at configure time using --with-divide=breaks. Divide-by-zero checks can be completely disabled using -mno-check-zero-division.

  • -mload-store-pairs, -mno-load-store-pairs โ€” enable (disable) an optimization that pairs consecutive load or store instructions to enable load/store bonding ๐Ÿซถ. This option is enabled by default but only takes effect when the selected architecture is known to support bonding.
  • -munaligned-access, -mno-unaligned-access โ€” enable (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 (do not force) the use of memcpy for non-trivial block moves. The default is -mno-memcpy, which allows GCC to inline most constant-sized copies โœจ.
  • -mlong-calls, -mno-long-calls โ€” disable (do not disable) use of the jal instruction. Calling functions using jal is more efficient but requires the caller and callee to be in the same 256 megabyte segment. This option has no effect on abicalls code. The default is -mno-long-calls.
  • -mmad, -mno-mad โ€” enable (disable) use of the mad, madu and mul instructions, as provided by the R4650 ISA ๐Ÿ”ฅ.
  • -mimadd, -mno-imadd โ€” enable (disable) use of the madd and msub integer instructions. The default is -mimadd on architectures that support madd and msub except for the 74k architecture where it was found to generate slower code ๐Ÿ’€.
  • -mfused-madd, -mno-fused-madd โ€” enable (disable) use of the floating-point multiply-accumulate instructions, when they are available. The default is -mfused-madd.

On the R8000 CPU when multiply-accumulate instructions are used, the intermediate product is calculated to infinite precision and is not subject to the FCSR Flush to Zero bit. This may be undesirable in some circumstances ๐Ÿ™ˆ. On other processors the result is numerically identical to the equivalent computation using separate multiply, add, subtract and negate instructions.

  • -nocpp โ€” tell the MIPS assembler to not run its preprocessor over user assembler files (with a .s suffix) when assembling them.

  • -mfix-24k, -mno-fix-24k โ€” work around the 24K E48 (lost data on stores during refill) errata. The workarounds are implemented by the assembler rather than by GCC ๐Ÿงš.
  • -mfix-r4000, -mno-fix-r4000 โ€” work around certain R4000 CPU errata:
    • A double-word or a variable shift may give an incorrect result if executed immediately after starting an integer division.
    • A double-word or a variable shift may give an incorrect result if executed while an integer multiplication is in progress.
    • An integer division may give an incorrect result if started in a delay slot of a taken branch or a jump.
  • -mfix-r4400, -mno-fix-r4400 โ€” work around certain R4400 CPU errata:
    • A double-word or a variable shift may give an incorrect result if executed immediately after starting an integer division.
  • -mfix-r10000, -mno-fix-r10000 โ€” work around certain R10000 errata:
    • ll/sc sequences may not behave atomically on revisions prior to 3.0. They may deadlock on revisions 2.6 and earlier ๐Ÿ’€.

This option can only be used if the target architecture supports branch-likely instructions. -mfix-r10000 is the default when -march=r10000 is used; -mno-fix-r10000 is the default otherwise.

  • -mfix-r5900, -mno-fix-r5900 โ€” do not attempt to schedule the preceding instruction into the delay slot of a branch instruction placed at the end of a short loop of six instructions or fewer and always schedule a nop instruction there instead. The short loop bug under certain conditions causes loops to execute only once or twice, due to a hardware bug in the R5900 chip ๐Ÿ˜ญ. The workaround is implemented by the assembler rather than by GCC.
  • -mfix-rm7000, -mno-fix-rm7000 โ€” work around the RM7000 dmult/dmultu errata. The workarounds are implemented by the assembler rather than by GCC.
  • -mfix-vr4120, -mno-fix-vr4120 โ€” work around certain VR4120 errata:
    • dmultu does not always produce the correct result.
    • div and ddiv do not always produce the correct result if one of the operands is negative.

The workarounds for the division errata rely on special functions in libgcc.a. At present, these functions are only provided by the mips64vr*-elf configurations.

Other VR4120 errata require a NOP to be inserted between certain pairs of instructions. These errata are handled by the assembler, not by GCC itself.

  • -mfix-vr4130 โ€” work around the VR4130 mflo/mfhi errata. The workarounds are implemented by the assembler rather than by GCC, although GCC avoids using mflo and mfhi if the VR4130 macc, macchi, dmacc and dmacchi instructions are available instead ๐Ÿ‘‘
  • -mfix-sb1, -mno-fix-sb1 โ€” work around certain SB-1 CPU core errata. (This flag currently works around the SB-1 revision 2 "F1" and "F2" floating-point errata.)

  • -mr10k-cache-barrier= setting โ€” specify whether GCC should insert cache barriers to avoid the side effects of speculation on R10K processors.

In common with many processors, the R10K tries to predict the outcome of a conditional branch and speculatively executes instructions from the "taken" branch. It later aborts these instructions if the predicted outcome is wrong. However, on the R10K, even aborted instructions can have side effects ๐Ÿ˜ณ.

This problem only affects kernel stores and, depending on the system, kernel loads. As an example, a speculatively-executed store may load the target memory into cache and mark the cache line as dirty, even if the store itself is later aborted. If a DMA operation writes to the same area of memory before the "dirty" line is flushed, the cached data overwrites the DMA-ed data. See the R10K processor manual for a full description, including other potential problems.

One workaround is to insert cache barrier instructions before every memory access that might be speculatively executed and that might have side effects even if aborted. -mr10k-cache-barrier=setting controls GCC's implementation of this workaround. It assumes that aborted accesses to any byte in the following regions does 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 ๐Ÿซถ.

If the input program contains a function declaration such as:

void foo (void);

then the implementation of foo must allow j foo and jal foo to be executed speculatively. GCC honors this restriction for functions it compiles itself. It expects non-GCC functions (such as hand-written assembly code) to do the same.

The option has three forms:

  • -mr10k-cache-barrier=load-store โ€” insert a cache barrier before a load or store that might be speculatively executed and that might have side effects even if aborted.
  • -mr10k-cache-barrier=store โ€” insert a cache barrier before a store that might be speculatively executed and that might have side effects even if aborted.
  • -mr10k-cache-barrier=none โ€” disable the insertion of cache barriers. This is the default setting.

  • -mflush-func= func, -mno-flush-func โ€” specifies the function to call to flush the I and D caches, or to not call any such function. If called, the function must take the same arguments as the common _flush_func, that is, the address of the memory range for which the cache is being flushed, the size of the memory range, and the number 3 (to flush both caches) ๐ŸŒธ. The default depends on the target GCC was configured for, but commonly is either _flush_func or __cpu_flush.
  • mbranch-cost=num โ€” sets the cost of branches to roughly num "simple" instructions ๐ŸŽ€. Heads up though: this cost is only a heuristic and is not guaranteed to give you consistent results across releases. A zero cost redundantly selects the default, which is based on the -mtune setting.
  • -mbranch-likely, -mno-branch-likely โ€” turn the use of Branch Likely instructions on or off, regardless of whatever the default is for the architecture you picked ๐Ÿ‘‘. By default, Branch Likely instructions may be generated if your selected architecture supports them. The exception? MIPS32 and MIPS64 architectures and the processors that implement them โ€” for those, Branch Likely instructions are not generated by default, because MIPS32 and MIPS64 specifically deprecate their use ๐Ÿซถ.
  • -mcompact-branches=never โ€” ensures compact branch instructions will never be generated ๐Ÿšซ.
  • -mcompact-branches=optimal โ€” this is the default โœจ. It causes a delay slot branch to be used if one is available in the current ISA and the delay slot is successfully filled. If the delay slot is not filled, a compact branch gets chosen if one is available.
  • -mcompact-branches=always โ€” ensures a compact branch instruction will be generated if it's available for MIPS Release 6 onwards. If a compact branch instruction is not available (or pre-R6), a delay slot form of the branch is used instead.
ok so a couple of caveats on these compact-branch flags, bestie, don't skip this ๐Ÿ’€ โ€” these options control which form of branches will be generated. If -mcompact-branches=always is used for MIPS16/microMIPS targets, it will just be ignored right now. The behaviour for MIPS16/microMIPS may change in future, since they do have some compact branch instructions.
  • -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. It only has an effect when optimizing for the VR4130, and it normally makes code faster โ€” 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.
๐Ÿšจ real talk: when compiling code for single processor systems, it's generally safe to use "synci". BUT on many multi-core (SMP) systems it does not invalidate the instruction caches on all cores and may lead to undefined behavior. You've been warned ๐Ÿ’….
  • -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 โ€” no help from the compiler needed ๐Ÿซก.
  • -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, bestie:

  • -mlibfuncs, -mno-libfuncs โ€” specify that intrinsic library functions are being compiled, passing all values in registers, no matter the size ๐Ÿ“ฆ.
  • -mepsilon, -mno-epsilon โ€” generate floating-point comparison instructions that compare with respect to the "rE" epsilon register ๐ŸŒˆ.
  • -mabi=mmixware, -mabi=gnu โ€” generate code that passes function parameters and return values that (in the called function) are seen as registers $0 and up โ€” as opposed to the GNU ABI, which uses global registers $231 and up ๐Ÿ‘‘
  • -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. This generally leads to short and fast code, but the number of different data items that can be addressed is limited. Which means: 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 โ€” generate code to avoid bugs in the multiply instructions for the MN10300 processors. This is the default โœจ.
  • -mno-mult-bug โ€” do not generate code to avoid bugs in the multiply instructions for the MN10300 processors ๐Ÿ’€.
  • -mam33 โ€” generate code using features specific to the AM33 processor ๐Ÿ”ฅ.
  • -mno-am33 โ€” do not generate code using features specific to the AM33 processor. This is the default ๐ŸŽ€.
  • -mam33-2 โ€” generate code using features specific to the AM33/2.0 processor ๐Ÿ’œ.
  • -mam34 โ€” generate code using features specific to the AM34 processor โญ.
  • -mtune=cpu-type โ€” use the timing characteristics of the indicated CPU type when scheduling instructions. This does not change the targeted processor type ๐Ÿซก. The CPU type must be one of mn10300, am33, am33-2 or am34.
  • -mreturn-pointer-on-d0 โ€” when generating a function that returns a pointer, return the pointer in both "a0" and "d0" ๐ŸŽฏ. Otherwise, the pointer is returned only in "a0", and attempts to call such functions without a prototype result in errors. Note that this option is on by default โ€” use -mno-return-pointer-on-d0 to disable it.
  • -mno-crt0 โ€” do not link in the C run-time initialization object file ๐Ÿšซ.
  • -mrelax โ€” indicate to the linker that it should perform a relaxation optimization pass to shorten branches, calls and absolute memory addresses ๐ŸŒ€. This option only has an effect when used on the command line for the final link step.
๐Ÿ˜ญ heads up: this option makes symbolic debugging impossible. Like, fully. Plan accordingly.
  • -mliw โ€” allow the compiler to generate Long Instruction Word instructions if the target is the AM33 or later. This is the default โœจ. This option defines the preprocessor macro "__LIW__".
  • -mno-liw โ€” do not allow the compiler to generate Long Instruction Word instructions. This option defines the preprocessor macro "__NO_LIW__" ๐Ÿšซ.
  • -msetlb โ€” allow the compiler to generate the SETLB and Lcc instructions if the target is the AM33 or later. This is the default ๐Ÿ‘‘. This option defines the preprocessor macro "__SETLB__".
  • -mno-setlb โ€” do not allow the compiler to generate SETLB or Lcc instructions. This option defines the preprocessor macro "__NO_SETLB__" ๐Ÿ™ˆ.

๐Ÿฆ‹ MOXIE OPTIONS ๐Ÿฆ‹

  • -meb โ€” generate big-endian code. This is the default for moxie-*-* configurations ๐Ÿ’–.
  • -mel โ€” generate little-endian code ๐ŸŒธ.
  • -mmul.x โ€” generate mul.x and umul.x instructions. This is the default for moxiebox-*-* configurations โญ.
  • -mno-crt0 โ€” do not link in the C run-time initialization object file ๐Ÿšซ.

๐ŸŽ€ MSP430 OPTIONS ๐ŸŽ€

These options are defined for the MSP430:

  • -masm-hex โ€” force assembly output to always use hex constants ๐Ÿ”ข. Normally such constants are signed decimals, but this option is available for testsuite and/or aesthetic purposes ๐Ÿ’….
  • -mmcu= โ€” bestie, this is the โ€œpick your MCUโ€ knob ๐Ÿ’…. It makes a C preprocessor symbol from the MCU name: uppercase it, then slap __ on the front and back. That symbol is what msp430.h uses to pull in an MCU-specific extra header file.

The option also sets which ISA to use. If the MCU name is known to only support the 430 ISA, then 430 gets selected; otherwise itโ€™s the 430X ISA. The generic MCU name msp430 can also be used to select the 430 ISA, and the generic msp430x MCU name selects the 430X ISA.

It also adds an MCU-specific linker script 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 causes the linker to search for a script called xxx.ld.

The ISA and hardware multiply support for the different MCUs are hard-coded into GCC. But an external devices.csv file can extend device support beyond whatโ€™s hard-coded.

GCC searches for devices.csv in this precedence order โ€” first method wins over the second, and the second wins over the third:

  • Include path specified with -I and -L โ€” devices.csv is 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 devices.csv is found, this directory is also registered as an include path and linker library path. Header files and linker scripts in this directory can therefore be used without manually specifying -I and -L on the command line.
  • The msp430-elf{,bare}/include/devices directory โ€” finally, GCC will examine msp430-elf{,bare}/include/devices from the toolchain root directory. This directory does not exist in a default installation, but if the user has created it and copied devices.csv there, then the MCU data will be read. As above, this directory is also registered as an include path and linker library path.

If none of the above search methods find devices.csv, then the hard-coded MCU data is used.

  • -mwarn-mcu, -mno-warn-mcu โ€” turns warnings on or off for conflicts between the MCU name from -mmcu and the ISA set by -mcpu and/or the hardware multiply support set by -mhwmult. It also toggles warnings about unrecognized MCU names. This option is on by default โœจ.
  • -mcpu= โ€” specifies the ISA to use. Accepted values are msp430, msp430x and msp430xv2. This option is deprecated ๐Ÿซ  โ€” use -mmcu= to select the ISA instead.
  • -msim โ€” link to the simulator runtime libraries and linker script. Overrides any scripts that would be selected by -mmcu=.
  • -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 โ€” passed to the assembler and linker, and lets the linker do certain optimizations that canโ€™t happen until the final link. iconic linker behavior, no cap.
  • mhwmult= โ€” describes the type of hardware multiply supported by the target. Accepted values are none for no hardware multiply, 16bit for the original 16-bit-only multiply supported by early MCUs, 32bit for the 16/32-bit multiply supported by later MCUs, and f5series for the 16/32-bit multiply supported by F5-series MCUs. You can also give a value of auto, which tells GCC to deduce hardware multiply support from the MCU name provided by -mmcu. If no -mmcu option is specified, or if the MCU name is not 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, however, the hardware multiplier is invoked inline โ€” bigger code, but faster code.

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. The tiny implementations of these functions are not reentrant, so use them with caution in multi-threaded applications ๐Ÿ˜ญ.

Support for streams has been removed, and the string to be printed will always be sent to stdout via the write syscall. The string is not buffered before it is sent to write.

This option requires Newlib Nano IO, so GCC must be configured with --enable-newlib-nano-formatted-io.

  • -mmax-inline-shift= โ€” takes an integer between 0 and 64 inclusive, and sets the maximum number of inline shift instructions that should be emitted to perform a shift operation by a constant amount. When this value needs to be exceeded, an mspabi helper function is used instead. The default value is 4.

This only affects cases where a shift by multiple positions cannot be completed with a single instruction (e.g. all shifts >1 on the 430 ISA).

Shifts of a 32-bit value are at least twice as costly, so the value passed for this option is divided by 2 and the resulting value is used instead.

  • -mcode-region=, -mdata-region= โ€” these tell the compiler where to place functions and data that do not have one of the "lower", "upper", "either" or "section" attributes. Possible values are "lower", "upper", "either" or "any". The first three behave like the corresponding attribute. The fourth possible value, "any", is the default. It leaves placement entirely up to the linker script and how it assigns the standard sections (.text, .data, etc) to the memory regions.
  • -msilicon-errata= โ€” passes on a request to the assembler to enable the fixes for the named silicon errata.
  • -msilicon-errata-warn= โ€” passes on a request to the assembler to enable warning messages when a silicon errata might need to be applied.
  • -mwarn-devices-csv, -mno-warn-devices-csv โ€” warn if devices.csv is not found or there are 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.
  • -mno-ext-perf โ€” do not generate performance extension instructions.
  • -mext-perf2 โ€” generate performance extension 2 instructions.
  • -mno-ext-perf2 โ€” do not generate performance extension 2 instructions.
  • -mext-string โ€” generate string extension instructions.
  • -mno-ext-string โ€” do not generate string extension instructions.
  • -mv3push โ€” generate v3 push25/pop25 instructions.
  • -mno-v3push โ€” do not generate v3 push25/pop25 instructions.
  • -m16-bit โ€” generate 16-bit instructions.
  • -mno-16-bit โ€” do not generate 16-bit instructions.
  • -misr-vector-size=num โ€” specify the size of each interrupt vector, which must be 4 or 16.
  • -mcache-block-size=num โ€” specify the size of each cache block, which must be a power of 2 between 4 and 512.
  • -march=arch โ€” specify the name of the target architecture.
  • -mcmodel=code-model โ€” set the code model to one of:
    • small โ€” all the data and read-only data segments must be within 512KB addressing space. The text segment must be within 16MB addressing space.
    • medium โ€” the data segment must be within 512KB while the read-only data segment can be within 4GB addressing space. The text segment should be still within 16MB addressing space.
    • large โ€” all the text and data segments can be within 4GB addressing space.
  • -mctor-dtor โ€” enable constructor/destructor feature.
  • -mrelax โ€” guide linker to relax instructions.

๐Ÿฆ‹ Nios II Options ๐Ÿฆ‹

These are the options defined for the Altera Nios II processor.

  • -G num โ€” put global and static objects less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS sections. The default value of num is 8.
  • -mgpopt=option, -mgpopt, -mno-gpopt โ€” generate (do not generate) GP-relative accesses. The following option names are recognized:
    • none โ€” do not generate GP-relative accesses.
    • local โ€” generate GP-relative accesses for small data objects that are not external, weak, or uninitialized common symbols. Also use GP-relative addressing for objects that have been explicitly placed in a small data section via a "section" attribute.
    • global โ€” as for local, but also generate GP-relative accesses for small data objects that are external, weak, or common. If you use this option, you must ensure that all parts of your program (including libraries) are compiled with the same -G setting.
    • data โ€” generate GP-relative accesses for all data objects in the program. If you use this option, the entire data and BSS segments of your program must fit in 64K of memory and you must use an appropriate linker script to allocate them within the addressable range of the global pointer.
  • all โ€” makes GCC generate GP-relative addresses for function pointers as well as data pointers. ๐Ÿซถ Heads up though: if you use this, your entire text, data, and BSS segments have to fit inside 64K of memory, and you must use an appropriate linker script to allocate them within the addressable range of the global pointer. That's the whole deal, no wiggle room.
  • -mgpopt is literally the same thing as -mgpopt=local, and -mno-gpopt is the same thing as -mgpopt=none. โœจ

The default is -mgpopt โ€” except when -fpic or -fPIC is specified to generate position-independent code. Also note that the Nios II ABI does not permit GP-relative accesses from shared libraries, so don't even try it bestie. ๐Ÿšซ

You may need to pass -mno-gpopt explicitly when you're building programs that include large amounts of small data, including large GOT data sections. Why? Because in that case the 16-bit offset for GP-relative addressing may just not be big enough to let you access the entire small data section. ๐Ÿ˜ญ It's giving "too much stuff, not enough offset."

  • -mgprel-sec=regexp โ€” lets you name extra sections that can be accessed via GP-relative addressing. It's most useful when you pair it 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 sections you specify are in addition to the standard ".sdata" and ".sbss" small-data sections that -mgpopt already recognizes.
  • -mr0rel-sec=regexp โ€” names the sections that can be accessed via a 16-bit offset from "r0" โ€” that is, the low 32K or high 32K of the 32-bit address space. Most useful in conjunction with "section" attributes on variable declarations and a custom linker script, and the regexp here is a POSIX Extended Regular Expression too. ๐ŸŽ€

In contrast to using 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 it's very much a "you build it, you name it" situation.

  • -mel, -meb โ€” generate little-endian (the default) or big-endian (experimental ๐Ÿ‘€) code, respectively.
  • -march=arch โ€” specifies the name of the target Nios II architecture. GCC uses this name to figure out what kind of instructions it's allowed to 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. Cute, right? ๐Ÿฆ‹

  • -mbypass-cache, -mno-bypass-cache โ€” force all load and store instructions to always bypass the cache by using I/O variants of the instructions. The default is not to bypass the cache.
  • -mno-cache-volatile, -mcache-volatile โ€” volatile memory accesses 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 โ€” don't 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 the compiler emitting the "mul", "mulx" and "div" family of instructions. 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 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 turns on 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. ๐Ÿซก Custom instructions taking two double-precision source operands expect the first operand in the 64-bit register X. The other operand (or the 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.

  • 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.
Not me letting you in on this: you can gain more local control over generation of Nios II custom instructions by using the target("custom-insn=N") and target("no-custom-insn") function attributes or pragmas. ๐Ÿ’…
  • -mcustom-fpu-cfg=name โ€” enables a predefined, named set of custom instruction encodings (see -mcustom-insn above). Currently, the following sets are defined:
    • -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 given by individual -mcustom-insn= options override those given by -mcustom-fpu-cfg=, regardless of the order of the options on the command line. Order does not save you here, bestie. ๐Ÿ’€

You can also gain more local control over selection of a FPU configuration by using the target("custom-fpu-cfg=name") function attribute or pragma. โœจ

The name fph2 is an abbreviation for Nios II Floating Point Hardware 2 Component. Please note that the custom instructions enabled by -mcustom-fmins=233 and -mcustom-fmaxs=234 are only generated if -ffinite-math-only is specified. The custom instruction enabled by -mcustom-round=248 is only generated if -fno-math-errno is specified. And in contrast to the other configurations, -fsingle-precision-constant is not set. ๐Ÿ™ƒ


These additional -m options are available for the Altera Nios II ELF (bare-metal) target: ๐ŸŽ€

  • -mhal โ€” link with HAL BSP. This suppresses linking with the GCC-provided C runtime startup and termination code, and is typically used in conjunction with -msys-crt0= to specify the location of the alternate startup code provided by the HAL BSP.
  • -msmallc โ€” link with a limited version of the C library, -lsmallc, rather than Newlib.
  • -msys-crt0=startfile โ€” startfile is the file name of the startfile (crt0) to use when linking. This option is only useful in conjunction with -mhal. ๐Ÿฆ‹
  • -msys-lib=systemlib โ€” okay so systemlib is the name of the library that hands you the low-level system calls your C library needs โ€” think read and write type stuff ๐Ÿ’…. You'd typically use this to link against a library that a HAL BSP provides. ๐Ÿ‘‘

๐Ÿฆ‹ Nvidia PTX Options ๐Ÿฆ‹

These ones are defined for Nvidia PTX, bestie:

  • -m64 โ€” lowkey ignored, but it's preserved for backward compatibility. Only the 64-bit ABI is supported, periodt.
  • -march=architecture-string โ€” generate code for the PTX ISA target architecture you name (like 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 was configured โ€” peep --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 โ€” literally just an alias of -march=. iykyk.
  • -march-map=architecture-string โ€” picks the closest available -march= value that isn't more capable than what you asked for. For instance, for -march-map=sm_50 it selects -march=sm_35, and for -march-map=sm_53 it selects -march=sm_53. ๐ŸŽ€
  • -mptx=version-string โ€” generate code for the PTX ISA version you name (like 7.0). The valid version strings include 3.1, 6.0, 6.3, and 7.0. Default PTX ISA version is 6.0, unless a higher version is required for the PTX ISA target architecture you specified via -march=.

This option sets the values of the preprocessor macros __PTX_ISA_VERSION_MAJOR__ and __PTX_ISA_VERSION_MINOR__; for instance, for 3.1 those macros have the values 3 and 1 respectively. ๐Ÿซถ

  • -mmainkernel โ€” link in code for a __main kernel. This is for stand-alone execution instead of offloading execution.
  • -moptimize โ€” apply partitioned execution optimizations. This is the default whenever any level of optimization is selected.
  • -msoft-stack โ€” generate code that does not use .local memory directly for stack storage. Instead, a per-warp stack pointer is maintained explicitly. This enables variable-length stack allocation (with variable-length arrays or alloca), and when global memory is used for the underlying storage, it makes it possible to access automatic variables from other threads, or with atomic instructions. This code generation variant is used for OpenMP offloading, but the option is exposed on its own for the purpose of testing the compiler; to generate code suitable for linking into programs using OpenMP offloading, use -mgomp instead. ๐Ÿ‘€
  • -muniform-simt โ€” switches to a code generation variant that lets you execute all the 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 the 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. The shared memory array int __nvptx_uni[] stores all-zeros or all-ones bitmasks for each warp, indicating the 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. main character energy fr fr ๐Ÿ’ซ
  • -mgomp โ€” generate code for use in OpenMP offloading: enables the -msoft-stack and -muniform-simt options, and selects the corresponding multilib variant. ate. ๐Ÿ”ฅ

๐ŸŒธ OpenRISC Options ๐ŸŒธ

These options are defined for OpenRISC:

  • -mboard=name โ€” configure a board-specific runtime. This gets passed to the linker for newlib board library linking. The default is or1ksim. ๐ŸŽ€
  • -mnewlib โ€” this option is ignored; it's for compatibility purposes only. It used to select linker and preprocessor options for use with newlib.
  • -msoft-div, -mhard-div โ€” select software or hardware divide (l.div, l.divu) instructions. The default is hardware divide.
  • -msoft-mul, -mhard-mul โ€” select software or hardware multiply (l.mul, l.muli) instructions. The default is hardware multiply.
  • -msoft-float, -mhard-float โ€” select software or hardware for floating point operations. The default is software.
  • -mdouble-float โ€” when -mhard-float is selected, this 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, this 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 gets 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 get generated to store the immediate to a register first.
  • -mshftimm โ€” enable generation of shift with immediate (l.srai, l.srli, l.slli) instructions. By default extra instructions get generated to store the immediate to a register first.
  • -mcmodel=small โ€” generate OpenRISC code for the small model: the GOT is limited to 64k. This is the default model.
  • -mcmodel=large โ€” generate OpenRISC code for the large model: the GOT may grow up to 4G in size. ๐Ÿ˜ญ

๐Ÿ’œ PDP-11 Options ๐Ÿ’œ

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... yeah, that's all she wrote here. (not me staring at a whole entire empty section ๐Ÿ’€)


๐Ÿ“ 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. โš ๏ธ Beware: the compiler could still generate code with static initializers and constructors. It is up to the programmer to ensure that the source program will not use those features.
  • -mmcu=mcu โ€” specify the PRU MCU variant to use. Check Newlib for the exact list of supported MCUs.
  • -mno-relax โ€” make GCC pass the --no-relax command-line option to the linker instead of the --relax option.
  • -mloop โ€” allow (or do not allow) GCC to use the LOOP instruction.
  • -mabi=variant โ€” specify the ABI variant to output code for. -mabi=ti selects the unmodified TI ABI while -mabi=gnu selects a GNU variant that copes more naturally with certain GCC assumptions. These are the differences:
    • Function Pointer Size โ€” TI ABI specifies that function (code) pointers are 16-bit, whereas GNU supports only 32-bit data and code pointers.
    • Optional Return Value Pointer โ€” function return values larger than 64 bits are passed by using a hidden pointer as the first argument of the function. TI ABI, though, mandates that the pointer can be NULL in case the caller is not using the returned value. GNU always passes and expects a valid return value pointer.

The current -mabi=ti implementation simply raises a compile error when any of the above code constructs is detected. As a consequence the standard C library cannot be built and it is omitted when linking with -mabi=ti.

Relaxation is a GNU feature and for safety reasons is disabled when using -mabi=ti. The TI toolchain does not emit relocations for QBBx instructions, so the GNU linker cannot adjust them when shortening adjacent LDI32 pseudo instructions. ๐Ÿ˜ค


๐ŸŒˆ 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 contains two parts: the size of integer types and the registers used for floating-point types. For example -march=rv64ifd -mabi=lp64d means that long and pointers are 64-bit (implicitly defining int to be 32-bit), and that floating-point values up to 64 bits wide are passed in F registers. Contrast this with -march=rv64ifd -mabi=lp64f, which still allows the compiler to generate code that uses the F and D extensions but only allows floating-point values up to 32 bits long to be passed in registers; or -march=rv64ifd -mabi=lp64, in which no floating-point arguments will be passed in registers. ๐Ÿ’–

The default for this argument is system dependent, so if you want a specific calling convention, bestie, specify one explicitly. The valid calling conventions are ilp32, ilp32f, ilp32d, lp64, lp64f, and lp64d. Some calling conventions are literally 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. ๐Ÿซถ

  • -mfdiv, -mno-fdiv โ€” Do or donโ€™t use hardware floating-point divide and square root instructions. This requires the F or D extensions for floating-point registers. The default is to use them if the specified architecture has these instructions. ๐Ÿ”ฅ
  • -mdiv, -mno-div โ€” Do or donโ€™t use hardware instructions for integer division. This requires the M extension. The default is to use them if the specified architecture has these instructions.
  • -misa-spec=ISA-spec-string โ€” Specify the version of the RISC-V Unprivileged (formerly User-Level) ISA specification to produce code conforming to. The possibilities for ISA-spec-string are:
    • 2.2 โ€” Produce code conforming to version 2.2.
    • 20190608 โ€” Produce code conforming to version 20190608.
    • 20191213 โ€” Produce code conforming to version 20191213.

The default is -misa-spec=20191213 unless GCC has been configured with --with-isa-spec= specifying a different default version.

  • -march=ISA-string โ€” Generate code for given RISC-V ISA (e.g. rv64im). ISA strings must be lower-case. Examples include rv64i, rv32g, rv32e, and rv32imaf.

When -march= is not specified, use the setting from -mcpu.

If both -march and -mcpu= are not specified, the default for this argument is system dependent, users who want a specific architecture extensions should specify one explicitly.

  • -mcpu=processor-string โ€” Use architecture of and optimize the output for the given processor, specified by particular CPU name. Permissible values for this option are: sifive-e20, sifive-e21, sifive-e24, sifive-e31, sifive-e34, sifive-e76, sifive-s21, sifive-s51, sifive-s54, sifive-s76, sifive-u54, and sifive-u74. ๐Ÿ’…
  • -mtune=processor-string โ€” Optimize the output for the given processor, specified by microarchitecture or particular CPU name. Permissible values for this option are: rocket, sifive-3-series, sifive-5-series, sifive-7-series, thead-c906, size, and all valid options for -mcpu=.

When -mtune= is not specified, use the setting from -mcpu, the default is rocket if both are not specified.

The size choice is not intended for use by end-users. This is used when -Os is specified. It overrides the instruction cost info provided by -mtune=, but does not override the pipeline info. This helps reduce code size while still giving good performance.

  • -mpreferred-stack-boundary=num โ€” Attempt to keep the stack boundary aligned to a 2 raised to num byte boundary. If -mpreferred-stack-boundary is not specified, the default is 4 (16 bytes or 128-bits).
Warning: If you use this switch, then you must build all modules with the same value, including any libraries. This includes the system libraries and startup modules. ๐Ÿ˜ญ
  • -msmall-data-limit=n โ€” Put global and static data smaller than n bytes into a special section (on some targets).
  • -msave-restore, -mno-save-restore โ€” Do or donโ€™t use smaller but slower prologue and epilogue code that uses library function calls. The default is to use fast inline prologues and epilogues.
  • -minline-atomics, -mno-inline-atomics โ€” Do or donโ€™t use smaller but slower subword atomic emulation code that uses libatomic function calls. 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 be compressed. Currently targets 32-bit integer load/stores only.
  • -mstrict-align, -mno-strict-align โ€” Do not or do generate unaligned memory accesses. The default is set depending on whether the processor we are optimizing for supports fast unaligned access or not.
  • -mcmodel=medlow โ€” Generate code for the medium-low code model. The program and its statically defined symbols must lie within a single 2 GiB address range and must lie between absolute addresses -2 GiB and +2 GiB. Programs can be statically or dynamically linked. This is the default code model.
  • -mcmodel=medany โ€” Generate code for the medium-any code model. The program and its statically defined symbols must be within any single 2 GiB address range. Programs can be statically or dynamically linked.
Heads up: The code generated by the medium-any code model is position-independent, but is not guaranteed to function correctly when linked into position-independent executables or libraries.
  • -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. (Yes, that second spelling is exactly how the manual has it.)
  • -mrelax, -mno-relax โ€” Take advantage of linker relaxations to reduce the number of instructions required to materialize symbol addresses. The default is to take advantage of linker relaxations.
  • -mriscv-attribute, -mno-riscv-attribute โ€” Emit (do not emit) RISC-V attribute to record extra information into ELF objects. This feature requires at least binutils 2.32.
  • -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 canary at guard. Supported locations are global for a global canary or tls for per-thread canary in the TLS block.

With the latter choice the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which register to use as base register for reading the canary, and from what offset from that base register. There is no default register or offset as this is entirely for use within the Linux kernel.

๐ŸŒธ 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. This is the default. The g13 value is for the hardware multiply/divide peripheral found on the RL78/G13 (S2 core) targets. The g14 value selects the use of the multiplication and division instructions supported by the RL78/G14 (S3 core) parts. The value rl78 is an alias for g14 and the value mg10 is an alias for none.

In addition a C preprocessor macro is defined, based upon the setting of this option. Possible values are: __RL78_MUL_NONE__, __RL78_MUL_G13__ or __RL78_MUL_G14__.

  • -mcpu=g10, -mcpu=g13, -mcpu=g14, -mcpu=rl78 โ€” Specifies the RL78 core to target. The default is the G14 core, also known as an S3 core or just RL78. The G13 or S2 core does not have multiply or divide instructions, instead it uses a hardware peripheral for these operations. The G10 or S1 core does not have register banks, so it uses a different calling convention.

If this option is set it also selects the type of hardware multiply support to use, unless this is overridden by an explicit -mmul=none option on the command line. Thus specifying -mcpu=g13 enables the use of the G13 hardware multiply peripheral and specifying -mcpu=g10 disables the use of hardware multiplications altogether.

Note, although the RL78/G14 core is the default target, specifying -mcpu=g14 or -mcpu=rl78 on the command line does change the behavior of the toolchain since it also enables G14 hardware multiply support. If these options are not specified on the command line then software multiplication routines will be used even though the code targets the RL78 core. This is for backwards compatibility with older toolchains which did not have hardware multiply and divide support.

In addition a C preprocessor macro is defined, based upon the setting of this option. Possible values are: __RL78_G10__, __RL78_G13__ or __RL78_G14__.

  • -mg10, -mg13, -mg14, -mrl78 โ€” These are aliases for the corresponding -mcpu= option. They are provided for backwards compatibility.
  • -mallregs โ€” Allow the compiler to use all of the available registers. By default registers r24..r31 are reserved for use in interrupt handlers. With this option enabled these registers can be used in ordinary functions as well.
  • -m64bit-doubles, -m32bit-doubles โ€” Make the double data type be 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. The default is -m32bit-doubles. ๐ŸŽ€
  • -msave-mduc-in-interrupts, -mno-save-mduc-in-interrupts โ€” tells the compiler that interrupt handler functions should keep the MDUC registers safe ๐Ÿ’พ. This is only actually needed if normal code might touch the MDUC registers โ€” like, say, because it's doing multiplication and division ops ๐Ÿ™ˆ. The default is to ignore the MDUC registers, because that makes interrupt handlers faster (and we love a speedy handler, no cap โœจ). You also have to pass the target option -mg13 for this to work at all, since the feature only exists on the G13 target (S2 core). And heads up: the MDUC registers only get saved if the interrupt handler actually does a multiplication or division operation, or if it calls another function. Yeah, it's giving "conditional queen" ๐Ÿ’….

๐ŸŒธ IBM RS/6000 and PowerPC Options ๐ŸŒธ

These -m options are defined for the IBM RS/6000 and PowerPC, bestie ๐Ÿซถ:

  • -mpowerpc-gpopt, -mno-powerpc-gpopt, -mpowerpc-gfxopt, -mno-powerpc-gfxopt, -mpowerpc64, -mno-powerpc64, -mmfcrf, -mno-mfcrf, -mpopcntb, -mno-popcntb, -mpopcntd, -mno-popcntd, -mfprnd, -mno-fprnd, -mcmpb, -mno-cmpb, -mhard-dfp, -mno-hard-dfp โ€” you use these options to specify which instructions are available on the processor you're using ๐Ÿ’–. The default value of these options is determined when configuring GCC. Specifying -mcpu=cpu_type overrides the specification of these options. And real talk: we recommend you use the -mcpu=cpu_type option rather than the ones listed above, iykyk ๐Ÿ‘‘

Specifying -mpowerpc-gpopt lets GCC use the optional PowerPC architecture instructions in the General Purpose group, including floating-point square root ๐Ÿ“. Specifying -mpowerpc-gfxopt lets GCC use the optional PowerPC architecture instructions in the Graphics group, including floating-point select โœจ.

The -mmfcrf option allows GCC to generate the move from condition register field instruction implemented on the POWER4 processor and other processors that support the PowerPC V2.01 architecture ๐ŸŒˆ. The -mpopcntb option allows GCC to generate the popcount and double-precision FP reciprocal estimate instruction implemented on the POWER5 processor and other processors that support the PowerPC V2.02 architecture ๐Ÿ’ซ. The -mpopcntd option allows GCC to generate the popcount instruction implemented on the POWER7 processor and other processors that support the PowerPC V2.06 architecture ๐Ÿ”ฅ. The -mfprnd option allows GCC to generate the FP round to integer instructions implemented on the POWER5+ processor and other processors that support the PowerPC V2.03 architecture ๐ŸŒธ. The -mcmpb option allows GCC to generate the compare bytes instruction implemented on the POWER6 processor and other processors that support the PowerPC V2.05 architecture ๐ŸŽ€. The -mhard-dfp option allows GCC to generate the decimal floating-point instructions implemented on some POWER processors ๐Ÿ’œ.

The -mpowerpc64 option allows GCC to generate the additional 64-bit instructions that are found in the full PowerPC64 architecture, and to treat GPRs as 64-bit, doubleword quantities ๐Ÿ‘‘. GCC defaults to -mno-powerpc64.

  • -mcpu=cpu_type โ€” sets the 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 ๐ŸŒˆ. That's a lot of CPUs, and honestly? Slay, we love a comprehensive list ๐Ÿ’….

-mcpu=powerpc, -mcpu=powerpc64, and -mcpu=powerpc64le specify pure 32-bit PowerPC (either endian), 64-bit big endian PowerPC, and 64-bit little endian PowerPC architecture machine types, with an appropriate, generic processor model assumed for scheduling purposes ๐ŸŽ€.

Specifying native as cpu type detects and selects the architecture option that corresponds to the host processor of the system performing the compilation ๐Ÿ’–. Heads up though: -mcpu=native has no effect if GCC does not recognize the processor ๐Ÿ˜ญ.

The other options specify a specific processor. Code generated under those options runs best on that processor, and may not run at all on others โš ๏ธ โ€” so don't be out here assuming portability, bestie.

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. So if you wish to set an individual option to a particular value, you may specify it after the -mcpu option, like -mcpu=970 -mno-altivec โœจ.

On AIX, the -maltivec and -mpowerpc64 options are not enabled or disabled by the -mcpu option at present, because AIX does not have full support for these options ๐Ÿ™ˆ. You may still enable or disable them individually if you're sure it'll work in your environment โ€” your call, main character ๐Ÿซถ.

  • -mtune=cpu_type โ€” 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 ๐ŸŽ€.
  • -mcmodel=small โ€” generate PowerPC64 code for the small model: the TOC is limited to 64k ๐Ÿฃ.
  • -mcmodel=medium โ€” generate PowerPC64 code for the medium model: the TOC and other static data may be up to a total of 4G in size ๐ŸŒธ. This is the default for 64-bit Linux, bestie ๐Ÿ‘‘
  • -mcmodel=large โ€” generate PowerPC64 code for the large model: the TOC may be up to 4G in size. Other data and code is only limited by the 64-bit address space ๐ŸŒŒ โ€” absolute unit energy.
  • -maltivec, -mno-altivec โ€” generate code that uses (does not use) AltiVec instructions, and also enable the use of built-in functions that allow more direct access to the AltiVec instruction set ๐Ÿ’œ. You may also need to set -mabi=altivec to adjust the current ABI with AltiVec ABI enhancements ๐Ÿ› ๏ธ.

When -maltivec is used, the element order for AltiVec intrinsics such as vec_splat, vec_extract, and vec_insert match array element order corresponding to the endianness of the target ๐ŸŒˆ. That is, element zero identifies the leftmost element in a vector register when targeting a big-endian platform, and identifies the rightmost element in a vector register when targeting a little-endian platform ๐Ÿ‘€. Left vs right, it matters, okay??

  • -mvrsave, -mno-vrsave โ€” generate VRSAVE instructions when generating AltiVec code ๐Ÿ’พ.
  • -msecure-plt โ€” generate code that allows ld and ld.so to build executables and shared libraries with non-executable .plt and .got sections ๐Ÿ”’. This is a PowerPC 32-bit SYSV ABI option โœจ.
  • -mbss-plt โ€” generate code that uses a BSS .plt section that ld.so fills in, and requires .plt and .got sections that are both writable and executable ๐Ÿ˜ฌ. This is a PowerPC 32-bit SYSV ABI option.
Okay so that second one is giving "writable and executable at the same time," which is lowkey the vibe security people have nightmares about ๐Ÿ’€. Just so you know what you're signing up for, bestie.
  • -msplit-patch-nops โ€” when adding NOPs for a patchable area via the -fpatchable-function-entry option, emit the "before" NOPs in front of the global entry point and the "after" NOPs after the local entry point ๐ŸŽฏ. This makes the sequence of NOPs not consecutive when a global entry point is generated. Without this option the NOPs are emitted directly before and after the local entry point, making them consecutive but moving global and local entry point further apart ๐Ÿ‘€. If only a single entry point is generated, this option has no effect โ€” it literally does nothing, no thoughts head empty ๐ŸŒธ.
  • -misel, -mno-isel โ€” this switch enables or disables the generation of ISEL instructions โšก.
  • -mvsx, -mno-vsx โ€” generate code that uses (does not use) vector/scalar (VSX) instructions, and also enable the use of built-in functions that allow more direct access to the VSX instruction set ๐Ÿฆ‹.
  • -mcrypto, -mno-crypto โ€” enable the use (disable) of the built-in functions that allow direct access to the cryptographic instructions that were added in version 2.07 of the PowerPC ISA ๐Ÿ”.
  • -mhtm, -mno-htm โ€” enable (disable) the use of the built-in functions that allow direct access to the Hardware Transactional Memory (HTM) instructions that were added in version 2.07 of the PowerPC ISA ๐Ÿง .
  • -mpower8-fusion, -mno-power8-fusion โ€” generate code that keeps (does not keeps) some integer operations adjacent so that the instructions can be fused together on power8 and later processors ๐Ÿ”ฅ. (Yes, the manpage literally says "does not keeps" โ€” we're keeping it, character for character, because that's iconic in its own way ๐Ÿ˜ญ.)
  • -mpower8-vector, -mno-power8-vector โ€” generate code that uses (does not use) the vector and scalar instructions that were added in version 2.07 of the PowerPC ISA ๐ŸŒˆ. Also enable the use of built-in functions that allow more direct access to the vector instructions โœจ.
  • -mquad-memory, -mno-quad-memory โ€” generate code that uses (does not use) the non-atomic quad word memory instructions ๐Ÿ’ซ. The -mquad-memory option requires use of 64-bit mode โš ๏ธ โ€” no 32-bit shenanigans allowed.
  • -mquad-memory-atomic, -mno-quad-memory-atomic โ€” generate code that uses (does not use) the atomic quad word memory instructions โš›๏ธ. The -mquad-memory-atomic option requires use of 64-bit mode too ๐Ÿ‘‘
  • -mfloat128, -mno-float128 โ€” enable/disable the __float128 keyword for IEEE 128-bit floating point, and use either software emulation for IEEE 128-bit floating point or hardware instructions ๐Ÿงฎ.

The VSX instruction set (-mvsx) must be enabled to use the IEEE 128-bit floating point support ๐Ÿ’œ. And the IEEE 128-bit floating point is only supported on Linux ๐Ÿง.

The default for -mfloat128 is enabled on PowerPC Linux systems using the VSX instruction set, and disabled on other systems ๐ŸŽ€.

If you use the ISA 3.0 instruction set (-mpower9-vector or -mcpu=power9) on a 64-bit system, the IEEE 128-bit floating point support will also enable the generation of ISA 3.0 IEEE 128-bit floating point instructions โšก. Otherwise, if you do not specify to generate ISA 3.0 instructions, or you are targeting a 32-bit big endian system, IEEE 128-bit floating point will be done with software emulation ๐Ÿข โ€” slower vibes, but it still works, bestie ๐Ÿซถ.

  • -mfloat128-hardware, -mno-float128-hardware โ€” turns on/off using ISA 3.0 hardware instructions to support the __float128 data type โœจ. The default for -mfloat128-hardware is enabled on PowerPC Linux systems using the ISA 3.0 instruction set, and disabled on other systems ๐Ÿ’–.
  • -m32, -m64 โ€” generate code for 32-bit or 64-bit environments of Darwin and SVR4 targets (including GNU/Linux) ๐ŸŒˆ. The 32-bit environment sets int, long and pointer to 32 bits and generates code that runs on any PowerPC variant. The 64-bit environment sets int to 32 bits and long and pointer to 64 bits, and generates code for PowerPC64, as for -mpowerpc64.
  • -mfull-toc, -mno-fp-in-toc, -mno-sum-in-toc, -mminimal-toc โ€” these modify generation of the TOC (Table Of Contents), which is created for every executable file ๐Ÿ‘‘. The -mfull-toc option is selected by default. In that case, GCC allocates at least one TOC entry for each unique non-automatic variable reference in your program. GCC also places floating-point constants in the TOC. However, only 16,384 entries are available in the TOC ๐Ÿ˜ญ.

If you receive a linker error message that saying you have overflowed the available TOC space, you can reduce the amount of TOC space used with the -mno-fp-in-toc and -mno-sum-in-toc options. -mno-fp-in-toc prevents GCC from putting floating-point constants in the TOC and -mno-sum-in-toc forces GCC to generate code to calculate the sum of an address and a constant at run time instead of putting that sum into the TOC. You may specify one or both of these options. Each causes GCC to produce very slightly slower and larger code at the expense of conserving TOC space ๐Ÿ’….

If you still run out of space in the TOC even when you specify both of these options, specify -mminimal-toc instead. This option causes GCC to make only one TOC entry for every file. When you specify this option, GCC produces code that is slower and larger but which uses extremely little TOC space. You may wish to use this option only on files that contain less frequently-executed code ๐Ÿซถ.

  • -maix64, -maix32 โ€” enable 64-bit AIX ABI and calling convention: 64-bit pointers, 64-bit "long" type, and the infrastructure needed to support them ๐Ÿ”ฅ. Specifying -maix64 implies -mpowerpc64, while -maix32 disables the 64-bit ABI and implies -mno-powerpc64. GCC defaults to -maix32.
  • -mxl-compat, -mno-xl-compat โ€” produce code that conforms more closely to IBM XL compiler semantics when using AIX-compatible ABI ๐ŸŒธ. Pass floating-point arguments to prototyped functions beyond the register save area (RSA) on the stack in addition to argument FPRs. Do not assume that most significant double in 128-bit long double value is properly rounded when comparing values and converting to double. Use XL symbol names for long double support routines.

The AIX calling convention was extended but not initially documented to handle an obscure K&R C case of calling a function that takes the address of its arguments with fewer arguments than declared. IBM XL compilers access floating-point arguments that do not fit in the RSA from the stack when a subroutine is compiled without optimization. Because always storing floating-point arguments on the stack is inefficient and rarely needed, this option is not enabled by default and only is necessary when calling subroutines compiled by IBM XL compilers without optimization ๐Ÿ’œ.

  • -mpe โ€” support IBM RS/6000 SP Parallel Environment (PE) ๐Ÿฆ‹. Link an application written to use message passing with special startup code to enable the application to run. The system must have PE installed in the standard location (/usr/lpp/ppe.poe/), or the specs file must be overridden with the -specs= option to specify the appropriate directory location. The Parallel Environment does not support threads, so the -mpe option and the -pthread option are incompatible ๐Ÿ’€.
  • -malign-natural, -malign-power โ€” on AIX, 32-bit Darwin, and 64-bit PowerPC GNU/Linux, the option -malign-natural overrides the ABI-defined alignment of larger types, such as floating-point doubles, on their natural size-based boundary โœจ. The option -malign-power instructs GCC to follow the ABI-specified alignment rules. GCC defaults to the standard alignment defined in the ABI.

On 64-bit Darwin, natural alignment is the default, and -malign-power is not supported ๐Ÿ™ˆ.

  • -msoft-float, -mhard-float โ€” generate code that does not use (uses) the floating-point register set ๐ŸŽ€. Software floating-point emulation is provided if you use the -msoft-float option, and pass the option to GCC when linking.
  • -mmultiple, -mno-multiple โ€” generate code that uses (does not use) the load multiple word instructions and the store multiple word instructions ๐Ÿ’…. These instructions are generated by default on POWER systems, and not generated on PowerPC systems. Do not use -mmultiple on little-endian PowerPC systems, since those instructions do not work when the processor is in little-endian mode. The exceptions are PPC740 and PPC750 which permit these instructions in little-endian mode.
  • -mupdate, -mno-update โ€” generate code that uses (does not use) the load or store instructions that update the base register to the address of the calculated memory location ๐Ÿ”ฅ. These instructions are generated by default. If you use -mno-update, there is a small window between the time that 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 ๐Ÿ˜ญ.
  • -mavoid-indexed-addresses, -mno-avoid-indexed-addresses โ€” generate code that tries to avoid (not avoid) the use of indexed load or store instructions ๐ŸŒŸ. These instructions can incur a performance penalty on Power6 processors in certain situations, such as when stepping through large arrays that cross a 16M boundary. This option is enabled by default when targeting Power6 and disabled otherwise.
  • -mfused-madd, -mno-fused-madd โ€” generate code that uses (does not use) the floating-point multiply and accumulate instructions ๐Ÿ’–. These 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.
  • -mmulhw, -mno-mulhw โ€” generate code that uses (does not use) the half-word multiply and multiply-accumulate instructions on the IBM 405, 440, 464 and 476 processors ๐Ÿฆ‹. These instructions are generated by default when targeting those processors.
  • -mdlmzb, -mno-dlmzb โ€” generate code that uses (does not use) the string-search dlmzb instruction on the IBM 405, 440, 464 and 476 processors ๐ŸŒธ. This instruction is generated by default when targeting those processors.
  • -mno-bit-align, -mbit-align โ€” on System V.4 and embedded PowerPC systems do not (do) force structures and unions that contain bit-fields to be aligned to the base type of the bit-field ๐Ÿ’œ.

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.

  • -mno-strict-align, -mstrict-align โ€” on System V.4 and embedded PowerPC systems do not (do) assume that unaligned memory references are handled by the system โœจ.
  • -mrelocatable, -mno-relocatable โ€” generate code that allows (does not allow) a static executable to be relocated to a different address at run time ๐Ÿ”ฅ. A simple embedded PowerPC system loader should relocate the entire contents of .got2 and 4-byte locations listed in the .fixup section, a table of 32-bit addresses generated by this option. For this to work, all objects linked together must be compiled with -mrelocatable or -mrelocatable-lib. -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.
  • -mno-toc, -mtoc โ€” on System V.4 and embedded PowerPC systems do not (do) assume that register 2 contains a pointer to a global area pointing to the addresses used in the program ๐Ÿ’….
  • -mlittle, -mlittle-endian โ€” on System V.4 and embedded PowerPC systems compile code for the processor in little-endian mode ๐ŸŒˆ. The -mlittle-endian option is the same as -mlittle.
  • -mbig, -mbig-endian โ€” on System V.4 and embedded PowerPC systems compile code for the processor in big-endian mode ๐ŸŒŸ. The -mbig-endian option is the same as -mbig.
  • -mdynamic-no-pic โ€” on Darwin and Mac OS X systems, compile code so that it is not relocatable, but that its external references are relocatable ๐Ÿ’–. The resulting code is suitable for applications, but not shared libraries.
  • -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.
  • -mprioritize-restricted-insns=priority โ€” this option controls the priority that is assigned to dispatch-slot restricted instructions during the second scheduling pass ๐Ÿ”ฅ. The argument priority takes the value 0, 1, or 2 to assign no, highest, or second-highest (respectively) priority to dispatch-slot restricted instructions.
  • -msched-costly-dep=dependence_type โ€” this option controls which dependences are considered costly by the target during instruction scheduling ๐Ÿ’œ. The argument dependence_type takes one of the following values:
    • no โ€” no dependence is costly.
    • all โ€” all dependences are costly.
    • true_store_to_load โ€” a true dependence from store to load is costly.
    • store_to_load โ€” any dependence from store to load is costly.
  • number โ€” any dependence whose latency is greater than or equal to number counts as costly. that's the whole vibe check ๐Ÿ’…
  • -minsert-sched-nops=scheme โ€” controls which NOP insertion scheme gets used during the second scheduling pass, bestie. scheme takes one of these:
    • no โ€” don't insert NOPs. none. zero. bye ๐Ÿ™ˆ
    • pad โ€” pad with NOPs any dispatch group that has vacant issue slots, following the scheduler's grouping. filling the empty seats fr fr ๐Ÿซถ
    • regroup_exact โ€” insert NOPs to force costly dependent insns into separate groups, and insert exactly as many NOPs as needed to force an insn into a new group, per the estimated processor grouping.
    • number โ€” insert NOPs to force costly dependent insns into separate groups, inserting number NOPs to force an insn into a new group. you pick the count, you own the count โœจ
  • -mcall-sysv โ€” on System V.4 and embedded PowerPC systems, compile code using calling conventions that adhere to the March 1995 draft of the System V Application Binary Interface, PowerPC processor supplement. this is the default unless you configured GCC using powerpc-*-eabiaix. vintage behavior, iconic honestly ๐ŸŽ€
  • -mcall-sysv-eabi, -mcall-eabi โ€” specify both -mcall-sysv and -meabi options. two-for-one deal ๐Ÿ’–
  • -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. we love a Linux moment ๐ŸŒˆ
  • -mcall-freebsd โ€” on System V.4 and embedded PowerPC systems, compile code for the FreeBSD operating system.
  • -mcall-netbsd โ€” on System V.4 and embedded PowerPC systems, compile code for the NetBSD operating system.
  • -mcall-openbsd โ€” on System V.4 and embedded PowerPC systems, compile code for the OpenBSD operating system.
  • -mtraceback=traceback_type โ€” select the type of traceback table. valid values for traceback_type are full, part, and no. three choices, no notes ๐Ÿฆ‹
  • -maix-struct-return โ€” return all structures in memory (as specified by the AIX ABI). all of them. in memory. periodt.
  • -msvr4-struct-return โ€” return structures smaller than 8 bytes in registers (as specified by the SVR4 ABI). tiny structs get the register treatment โœจ

  • -mabi=abi-type โ€” extend the current ABI with a particular extension, or remove such extension. valid values are: altivec, no-altivec, ibmlongdouble, ieeelongdouble, elfv1, elfv2, and for AIX: vec-extabi, vec-default. that's the roster, memorize it ๐Ÿ’…
  • -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 ๐Ÿ˜ญ and if you change the long double type from IEEE extended-precision, the compiler will issue a warning unless you use the -Wno-psabi option. requires -mlong-double-128 to be enabled. so many hoops but okay ๐Ÿ‘‘
  • -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 ๐Ÿ’€ and 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. mirror image, same drama ๐Ÿชž
  • -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. spectacular!! we love a warning that has main character energy ๐Ÿ”ฅ
  • -mabi=elfv2 โ€” change the current ABI to use the ELFv2 ABI. this is the default ABI for little-endian PowerPC 64-bit Linux. overriding the default ABI requires special system support and is likely to fail in spectacular ways. same chaos, different endianness ๐Ÿ™ˆ
  • -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. bit 6 of CR really said "it's giving bookkeeping" ๐Ÿ˜ญ
  • -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. slay ๐Ÿซถ
  • -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. yellowknife is such a name ngl ๐Ÿ’›
  • -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. two data areas vs one, choose your fighter โญ
  • -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. package deal ๐Ÿ’–
  • -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. it reads the room and adapts, lowkey iconic ๐ŸŒธ
  • -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. back to basics bestie ๐ŸŽ€
  • -mreadonly-in-sdata โ€” put read-only objects in the .sdata section as well. this is the default. yes, read-only, yes, still in there, yes, it's fine ๐Ÿ’…
  • -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. respect the floor ๐Ÿงš
  • -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. zero means no inline, not even the loop version, no cap ๐Ÿ™ˆ
  • -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. looping era ๐ŸŒช๏ธ
  • -mstring-compare-inline-limit=num โ€” compare at most num string bytes with inline code. if the difference or end of string is not found at the end of the inline compare a call to strcmp or strncmp will take care of the rest of the comparison. the default is 64 bytes. the handoff is so clean โœจ
  • -G num โ€” on embedded PowerPC systems, put global and static items less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS section. by default, num is 8. the -G num switch is also passed to the linker. all modules should be compiled with the same -G num value. consistency is the moment, don't mix values ๐Ÿ”ฅ
  • -mregnames, -mno-regnames โ€” on System V.4 and embedded PowerPC systems, do (do not) emit register names in the assembly language output using symbolic forms.
  • -mlongcall, -mno-longcall โ€” by default assume that all calls are far away so that a longer and more expensive calling sequence is required. this is required for calls farther than 32 megabytes (33,554,432 bytes) from the current location. a short call is generated if the compiler knows the call cannot be that far away. this setting can be overridden by the shortcall function attribute, or by #pragma longcall(0). broad assumption, extra cost, iconic honestly ๐Ÿ’ธ

some linkers are capable of detecting out-of-range calls and generating glue code on the fly. on these systems, long calls are unnecessary and generate slower code. as of this writing, the AIX linker can do this, as can the GNU linker for PowerPC/64. it is planned to add this feature to the GNU linker for 32-bit PowerPC systems as well. future feature loadingโ€ฆ โณ

Okay so picking up right here: on PowerPC64 ELFv2 and 32-bit PowerPC systems with newer GNU linkers, GCC can generate long calls using an inline PLT call sequence (see -mpltseq). PowerPC with -mbss-plt and PowerPC64 ELFv1 (big-endian) do not support inline PLT calls.

On Darwin/PPC systems, #pragma longcall generates jbsr callee, L42, plus a branch island (glue code). The two target addresses represent the callee and the branch island. The Darwin/PPC linker prefers the first address and generates a bl callee if the PPC bl instruction reaches the callee directly; otherwise, the linker generates bl L42 to call the branch island. The branch island is appended to the body of the calling function; it computes the full 32-bit address of the callee and jumps to it.

On Mach-O (Darwin) systems, this option tells the compiler to emit the glue for every direct call, and the Darwin linker decides whether to use or discard it.

In the future, GCC may ignore all longcall specifications when the linker is known to generate glue.

  • -mpltseq, -mno-pltseq โ€” Implement (or do not implement) -fno-plt and long calls using an inline PLT call sequence that supports lazy linking and long calls to functions in dlopen'd shared libraries. Inline PLT calls are only supported on PowerPC64 ELFv2 and 32-bit PowerPC systems with newer GNU linkers, and are enabled by default if the support is detected when configuring GCC, and, in the case of 32-bit PowerPC, if GCC is configured with --enable-secureplt. -mpltseq code and -mbss-plt 32-bit PowerPC relocatable objects may not be linked together.
  • -mtls-markers, -mno-tls-markers โ€” Mark (do not mark) calls to __tls_get_addr with a relocation specifying the function argument. The relocation allows the linker to reliably associate function call with argument setup instructions for TLS optimization, which in turn allows GCC to better schedule the sequence.
  • -mrecip, -mno-recip โ€” This option enables use of the reciprocal estimate and reciprocal square root estimate instructions with additional Newton-Raphson steps to increase precision instead of doing a divide or square root and divide for floating-point arguments. You should use the -ffast-math option when using -mrecip (or at least -funsafe-math-optimizations, -ffinite-math-only, -freciprocal-math and -fno-trapping-math). Note that while the throughput of the sequence is generally higher than the throughput of the non-reciprocal instruction, the precision of the sequence can be decreased by up to 2 ulp (i.e. the inverse of 1.0 equals 0.99999994) for reciprocal square roots.
  • -mrecip=opt โ€” This option controls which reciprocal estimate instructions may be used. opt is a comma-separated list of options, which may be preceded by a ! to invert the option:
    • all โ€” Enable all estimate instructions.
    • default โ€” Enable the default instructions, equivalent to -mrecip.
    • none โ€” Disable all estimate instructions, equivalent to -mno-recip.
    • div โ€” Enable the reciprocal approximation instructions for both single and double precision.
    • divf โ€” Enable the single-precision reciprocal approximation instructions.
    • divd โ€” Enable the double-precision reciprocal approximation instructions.
    • rsqrt โ€” Enable the reciprocal square root approximation instructions for both single and double precision.
    • rsqrtf โ€” Enable the single-precision reciprocal square root approximation instructions.
    • rsqrtd โ€” Enable the double-precision reciprocal square root approximation instructions.

So, for example, -mrecip=all,!rsqrtd enables all of the reciprocal estimate instructions, except for the FRSQRTE, XSRSQRTEDP, and XVRSQRTEDP instructions which handle the double-precision reciprocal square root calculations.

  • -mrecip-precision, -mno-recip-precision โ€” Assume (do not assume) that the reciprocal estimate instructions provide higher-precision estimates than is mandated by the PowerPC ABI. Selecting -mcpu=power6, -mcpu=power7 or -mcpu=power8 automatically selects -mrecip-precision. The double-precision square root estimate instructions are not generated by default on low-precision machines, since they do not provide an estimate that converges after three steps.
  • -mveclibabi=type โ€” Specifies the ABI type to use for vectorizing intrinsics using an external library. The only type supported at present is mass, which specifies to use IBM's Mathematical Acceleration Subsystem (MASS) libraries for vectorizing intrinsics using external libraries. GCC currently emits calls to acosd2, acosf4, acoshd2, acoshf4, asind2, asinf4, asinhd2, asinhf4, atan2d2, atan2f4, atand2, atanf4, atanhd2, atanhf4, cbrtd2, cbrtf4, cosd2, cosf4, coshd2, coshf4, erfcd2, erfcf4, erfd2, erff4, exp2d2, exp2f4, expd2, expf4, expm1d2, expm1f4, hypotd2, hypotf4, lgammad2, lgammaf4, log10d2, log10f4, log1pd2, log1pf4, log2d2, log2f4, logd2, logf4, powd2, powf4, sind2, sinf4, sinhd2, sinhf4, sqrtd2, sqrtf4, tand2, tanf4, tanhd2, and tanhf4 when generating code for power7. Both -ftree-vectorize and -funsafe-math-optimizations must also be enabled. The MASS libraries must be specified at link time.
  • -mfriz, -mno-friz โ€” Generate (do not generate) the friz instruction when the -funsafe-math-optimizations option is used to optimize rounding of floating-point values to 64-bit integer and back to floating point. The friz instruction does not return the same value if the floating-point number is too large to fit in an integer.
  • -mpointers-to-nested-functions, -mno-pointers-to-nested-functions โ€” Generate (do not generate) code to load up the static chain register (r11) when calling through a pointer on AIX and 64-bit Linux systems where a function pointer points to a 3-word descriptor giving the function address, TOC value to be loaded in register r2, and static chain value to be loaded in register r11. The -mpointers-to-nested-functions is on by default. You cannot call through pointers to nested functions or pointers to functions compiled in other languages that use the static chain if you use -mno-pointers-to-nested-functions.
  • -msave-toc-indirect, -mno-save-toc-indirect โ€” Generate (do not generate) code to save the TOC value in the reserved stack location in the function prologue if the function calls through a pointer on AIX and 64-bit Linux systems. If the TOC value is not saved in the prologue, it is saved just before the call through the pointer. The -mno-save-toc-indirect option is the default.
  • -mcompat-align-parm, -mno-compat-align-parm โ€” Generate (do not generate) code to pass structure parameters with a maximum alignment of 64 bits, for compatibility with older versions of GCC.

Older versions of GCC (prior to 4.9.0) incorrectly did not align a structure parameter on a 128-bit boundary when that structure contained a member requiring 128-bit alignment. This is corrected in more recent versions of GCC. This option may be used to generate code that is compatible with functions compiled with older versions of GCC.

The -mno-compat-align-parm option is the default.

  • -mstack-protector-guard=guard, -mstack-protector-guard-reg=reg, -mstack-protector-guard-offset=offset, -mstack-protector-guard-symbol=symbol โ€” Generate stack protection code using canary at guard. Supported locations are global for global canary or tls for per-thread canary in the TLS block (the default with GNU libc version 2.4 or later).

With the latter choice the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which register to use as base register for reading the canary, and from what offset from that base register. The default for those is as specified in the relevant ABI. -mstack-protector-guard-symbol=symbol overrides the offset with a symbol reference to a canary in the TLS block.

  • -mpcrel, -mno-pcrel โ€” Generate (do not generate) pc-relative addressing. The -mpcrel option requires that the medium code model (-mcmodel=medium) and prefixed addressing (-mprefixed) options are enabled.
  • -mprefixed, -mno-prefixed โ€” Generate (do not generate) addressing modes using prefixed load and store instructions. The -mprefixed option requires that the option -mcpu=power10 (or later) is enabled.
  • -mmma, -mno-mma โ€” Generate (do not generate) the MMA instructions. The -mma option requires that the option -mcpu=power10 (or later) is enabled.
  • -mrop-protect, -mno-rop-protect โ€” Generate (do not generate) ROP protection instructions when the target processor supports them. Currently this option disables the shrink-wrap optimization (-fshrink-wrap).
  • -mprivileged, -mno-privileged โ€” Generate (do not generate) code that will run in privileged state.
  • -mblock-ops-unaligned-vsx, -mno-block-ops-unaligned-vsx โ€” Generate (do not generate) unaligned vsx loads and stores for inline expansion of memcpy and memmove.
  • --param rs6000-vect-unroll-limit= โ€” The vectorizer will check with target 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.

๐ŸŒธ RX Options ๐ŸŒธ

These command-line options are defined for RX targets:

  • -m64bit-doubles, -m32bit-doubles โ€” Make the double data type be 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. The default is -m32bit-doubles. Note RX floating-point hardware only works on 32-bit values, which is why the default is -m32bit-doubles.
  • -fpu, -nofpu โ€” Enables (-fpu) or disables (-nofpu) the use of RX floating-point hardware. The default is enabled for the RX600 series and disabled for the RX200 series.

Floating-point instructions are only generated for 32-bit floating-point values, however, so the FPU hardware is not used for doubles if the -m64bit-doubles option is used.

๐Ÿ’– heads up bestie: if the -fpu option is on, then -funsafe-math-optimizations gets switched on automatically too. Why? Because the RX FPU instructions are literally unsafe themselves. No cap. ๐Ÿ™ˆ
  • -mcpu=name โ€” picks which type of RX CPU you're targeting. rn there are three supported: the generic RX600 and RX200 series hardware, plus the specific RX610 CPU. Default is RX600.

The only difference between RX600 and RX610 is that RX610 doesn't support the MVTIPL instruction. That's it, that's the whole tea. ๐Ÿต

The RX200 series has no hardware floating-point unit, so -nofpu is enabled by default when you pick this type.

  • -mbig-endian-data, -mlittle-endian-data โ€” stores data (but not code!! just data) in big-endian format. Default is -mlittle-endian-data, i.e. data goes in little-endian format. ๐ŸŽ€
  • -msmall-data-limit=N โ€” sets the max size in bytes of global and static variables that can go into the small data area. Using the small data area can give you smaller and faster code, but the area's size is limited and it's on you, the programmer, to make sure it doesn't overflow. Also, when the small data area is used, one of RX's registers (usually r13) gets reserved to point at this area, so the compiler can't use it anymore. That could mean slower and/or bigger code if variables end up pushed onto the stack instead of chilling in that register. ๐Ÿ˜ญ

Note: common variables (the ones that haven't been initialized) and constants don't go into the small data area, because they get assigned to other sections in the output executable.

Default value is zero, which disables this whole feature. Note: it's not enabled by default with higher optimization levels (-O2 etc) because reserving a register can be potentially detrimental. It's up to the programmer to experiment and discover whether this feature actually benefits their program. See the -mpid option's description for how the actual register holding the small data area pointer gets chosen. ๐Ÿ”

  • -msim, -mno-sim โ€” use the simulator runtime. Default is to use the libgloss board-specific runtime.
  • -mas100-syntax, -mno-as100-syntax โ€” when generating assembler output, use a syntax compatible with Renesas's AS100 assembler. The GAS assembler can handle this syntax too, but it has some restrictions, so it's not generated by default. ๐Ÿ’…
  • -mmax-constant-size=N โ€” sets the maximum size, in bytes, of a constant that can be used as an operand in an RX instruction. Even though the RX instruction set does allow constants up to 4 bytes long in instructions, a longer value means a longer instruction. So sometimes it's beneficial to restrict the size of constants used in instructions โ€” constants that are too big get placed into a constant pool instead and referenced via register indirection.

The value N can be between 0 and 4. A value of 0 (the default) or 4 means constants of any size are allowed. โœจ

  • -mrelax โ€” enables linker relaxation. Linker relaxation is where the linker tries to shrink your program by finding shorter versions of various instructions. Disabled by default. ๐Ÿฆ‹
  • -mint-register=N โ€” specifies how many registers to reserve for fast interrupt handler functions. N can be between 0 and 4. A value of 1 means register r13 is reserved for the exclusive use of fast interrupt handlers. A value of 2 reserves r13 and r12. A value of 3 reserves r13, r12 and r11, and a value of 4 reserves r13 through r10. A value of 0, the default, reserves nothing. ๐Ÿ’ซ
  • -msave-acc-in-interrupts โ€” says interrupt handler functions should preserve the accumulator register. This is only necessary if normal code might use the accumulator register โ€” for example because it does 64-bit multiplications. Default is to ignore the accumulator, since that makes the interrupt handlers faster. ๐Ÿ”ฅ
  • -mpid, -mno-pid โ€” enables generation of position independent data. When it's on, any access to constant data happens via an offset from a base address held in a register. That lets the location of constant data be figured out at run time without needing the executable to be relocated โ€” a big win for embedded apps with tight memory constraints. Data that can be modified is not affected by this option. ๐Ÿ‘‘

Note: this feature reserves a register, usually r13, for the constant data base address. That can make code slower and/or bigger, especially in complicated functions.

The actual register chosen to hold the constant data base address depends on whether -msmall-data-limit and/or the -mint-register command-line options are enabled. Starting with register r13 and going downwards, registers get allocated first to satisfy -mint-register, then -mpid, and finally -msmall-data-limit. So it's totally 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 off. You can restore the default with the -mno-pid command-line option.

  • -mno-warn-multiple-fast-interrupts, -mwarn-multiple-fast-interrupts โ€” stops GCC from throwing a warning if it finds more than one fast interrupt handler while compiling a file. Default is to warn for each extra fast interrupt handler it finds, because RX only supports one such interrupt. ๐Ÿ’€
  • -mallow-string-insns, -mno-allow-string-insns โ€” enables or disables 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 you're accessing an I/O register. (See section 12.2.7 of the RX62N Group User's Manual for more info.) ๐Ÿ™ˆ

Default is to allow these instructions, but GCC can't reliably detect every circumstance where a string instruction might be used to access an I/O register, so their use can't be disabled automatically. Instead it relies on the programmer to use -mno-allow-string-insns if their program touches I/O space.

When the instructions are enabled, GCC defines the C preprocessor symbol __RX_ALLOW_STRING_INSNS__; otherwise it defines __RX_DISALLOW_STRING_INSNS__. ๐ŸŽ€

  • -mjsr, -mno-jsr โ€” use only (or not only) JSR instructions to access functions. You can use this when code size exceeds the range of BSR instructions. Note that -mno-jsr does not mean "don't use JSR" โ€” it means any type of branch may be used. ๐ŸŒˆ
โš ๏ธ Note: the generic GCC command-line option -ffixed-reg has special significance to the RX port when it's used with the interrupt function attribute. That attribute marks a function meant to process fast interrupts. GCC makes sure it only uses registers r10, r11, r12 and/or r13 โ€” and only provided that the normal use of the corresponding registers has 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, these are giving mainframe main character energy. ๐Ÿ‘‘

  • -mhard-float, -msoft-float โ€” use (or don't use) the hardware floating-point instructions and registers for floating-point operations. When -msoft-float is specified, functions in libgcc.a are used to do the 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 (or don't 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 do the decimal-floating-point operations. When -mhard-dfp is specified, the compiler generates decimal-floating-point hardware instructions. This is the default for -march=z9-ec or higher. ๐Ÿ’…
  • -mlong-double-64, -mlong-double-128 โ€” these switches control the size of the long double type. A size of 64 bits makes long double equivalent to double. This is the default. ๐ŸŽ€
  • -mbackchain, -mno-backchain โ€” store (or don't store) the address of the caller's frame as a backchain pointer into the callee's stack frame. A backchain may be needed so you can debug with tools that don't 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 goes 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 using the backchain for debugging usually requires the whole binary be built with -mbackchain. Note that the combination of -mbackchain, -mpacked-stack and -mhard-float is not supported. To 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) the packed stack layout. When -mno-packed-stack is specified, the compiler uses all fields of the 96/160 byte register save area only for their default purpose; unused fields still take up stack space. When -mpacked-stack is specified, register save slots are densely packed at the top of the register save area; unused space gets reused for other purposes, letting you use the available stack space more efficiently. 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. ๐Ÿฆ‹

Okay so, continuing the S/390 and zSeries saga โ€” as long as the stack frame backchain isn't being used, code generated with -mpacked-stack is call-compatible with code generated with -mno-packed-stack. ๐Ÿซถ But heads up: 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 โ€” and that code is not call-compatible with code compiled with -mpacked-stack. Also, 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 that uses 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 doesn't 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. Note that -mesa is not possible with -m64. When generating code compliant to the GNU/Linux for S/390 ABI, the default is -mesa. When generating code compliant to the GNU/Linux for zSeries ABI, the default is -mzarch.
  • -mhtm, -mno-htm โ€” the -mhtm option enables a set of builtins making use of instructions available with the transactional execution facility introduced with the IBM zEnterprise EC12 machine generation S/390 System z Built-in Functions. -mhtm is enabled by default when using -march=zEC12.
  • -mvx, -mno-vx โ€” when -mvx is specified, generate code using the instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option changes the ABI for some vector type values with regard to alignment and calling conventions. In case vector type values are being used in an ABI-relevant context, a GAS .gnu_attribute command will be added to mark the resulting binary with the ABI used. -mvx is enabled by default when using -march=z13.
  • -mzvector, -mno-zvector โ€” the -mzvector option enables vector language extensions and builtins using instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option adds support for vector to be used as a keyword to define vector type variables and arguments. vector is only available when GNU extensions are enabled. It will not be expanded when requesting strict standard compliance, e.g. with -std=c99. In addition to the GCC low-level builtins, -mzvector enables a set of builtins added for compatibility with AltiVec-style implementations like Power and Cell. In order to make use of these builtins, the header file vecintrin.h needs to be included. -mzvector is disabled by default.
  • -mmvcle, -mno-mvcle โ€” generate (or do not generate) code using the "mvcle" instruction to perform block moves. When -mno-mvcle is specified, use a "mvc" loop instead. This is the default unless optimizing for size.
  • -mdebug, -mno-debug โ€” print (or do not print) additional debug information when compiling. The default is to not print debug information.
  • *-march=cpu-type* โ€” generate code that runs on cpu-type, which is the name of a system representing a certain processor type. Possible values for cpu-type are z900/arch5, z990/arch6, z9-109, z9-ec/arch7, z10/arch8, z196/arch9, zEC12, z13/arch11, z14/arch12, z15/arch13, z16/arch14, and native.

The default is -march=z900.

Specifying native as cpu type can be used to select the best architecture option for the host processor. -march=native has no effect if GCC does not recognize the processor.

  • *-mtune=cpu-type* โ€” tune to cpu-type everything applicable about the generated code, except for the ABI and the set of available instructions. The list of cpu-type values is the same as for -march. The default is the value used for -march.
  • -mtpf-trace, -mno-tpf-trace โ€” generate code that adds (does not add) in TPF OS specific branches to trace routines in the operating system. This option is off by default, even when compiling for the TPF OS.
  • -mtpf-trace-skip, -mno-tpf-trace-skip โ€” generate code that changes (does not change) the default branch targets enabled by -mtpf-trace to point to specialized trace routines providing the ability of selectively skipping function trace entries for the TPF OS. This option is off by default, even when compiling for the TPF OS and specifying -mtpf-trace.
  • -mfused-madd, -mno-fused-madd โ€” generate code that uses (does not use) the floating-point multiply and accumulate instructions. These instructions are generated by default if hardware floating point is used.
  • *-mwarn-framesize=framesize* โ€” emit a warning if the current function exceeds the given frame size. Because this is a compile-time check, it doesn't need to be a real problem when the program runs. It's intended to identify functions that most probably cause a stack overflow. It's useful in an environment with limited stack size, e.g. the linux kernel.
  • -mwarn-dynamicstack โ€” emit a warning if the function calls "alloca" or uses dynamically-sized arrays. This is generally a bad idea with a limited stack size.
  • *-mstack-guard=stack-guard*, -mstack-size=stack-size โ€” if these options are provided, the S/390 back end emits additional instructions in the function prologue that trigger a trap if the stack size is stack-guard bytes above the stack-size (remember that the stack on S/390 grows downward ๐Ÿ™ƒ). If the stack-guard option is omitted, the smallest power of 2 larger than the frame size of the compiled function is chosen. These options are intended to help debug 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 function 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, bestie โ€” there's a lot of them, so buckle up ๐Ÿ’…

  • -m1 โ€” generate code for the SH1.
  • -m2 โ€” generate code for the SH2.
  • -m2e โ€” generate code for the SH2e.
  • -m2a-nofpu โ€” generate code for the SH2a without FPU, or for a SH2a-FPU in such a way that the floating-point unit is not used.
  • -m2a-single-only โ€” generate code for the SH2a-FPU, in such a way that no double-precision floating-point operations are used.
  • -m2a-single โ€” generate code for the SH2a-FPU assuming the floating-point unit is in single-precision mode by default.
  • -m2a โ€” generate code for the SH2a-FPU assuming the floating-point unit is in double-precision mode by default.
  • -m3 โ€” generate code for the SH3.
  • -m3e โ€” generate code for the SH3e.
  • -m4-nofpu โ€” generate code for the SH4 without a floating-point unit.
  • -m4-single-only โ€” generate code for the SH4 with a floating-point unit that only supports single-precision arithmetic.
  • -m4-single โ€” generate code for the SH4 assuming the floating-point unit is in single-precision mode by default.
  • -m4 โ€” generate code for the SH4.
  • -m4-100 โ€” generate code for SH4-100.
  • -m4-100-nofpu โ€” generate code for SH4-100 in such a way that the floating-point unit is not used.
  • -m4-100-single โ€” generate code for SH4-100 assuming the floating-point unit is in single-precision mode by default.
  • -m4-100-single-only โ€” generate code for SH4-100 in such a way that no double-precision floating-point operations are used.
  • -m4-200 โ€” generate code for SH4-200.
  • -m4-200-nofpu โ€” generate code for SH4-200 in such a way that the floating-point unit is not used.
  • -m4-200-single โ€” generate code for SH4-200 assuming the floating-point unit is in single-precision mode by default.
  • -m4-200-single-only โ€” generate code for SH4-200 in such a way that no double-precision floating-point operations are used.
  • -m4-300 โ€” generate code for SH4-300.
  • -m4-300-nofpu โ€” generate code for SH4-300 in such a way that the floating-point unit is not used.
  • -m4-300-single โ€” generate code for SH4-300 in such a way that no double-precision floating-point operations are used.
  • -m4-300-single-only โ€” generate code for SH4-300 in such a way that no double-precision floating-point operations are used.
  • -m4-340 โ€” generate code for SH4-340 (no MMU, no FPU).
  • -m4-500 โ€” generate code for SH4-500 (no FPU). Passes -isa=sh4-nofpu to the assembler.
  • -m4a-nofpu โ€” generate code for the SH4al-dsp, or for a SH4a in such a way that the floating-point unit is not used.
  • -m4a-single-only โ€” generate code for the SH4a, in such a way that no double-precision floating-point operations are used.
  • -m4a-single โ€” generate code for the SH4a assuming the floating-point unit is in single-precision mode by default.
  • -m4a โ€” generate code for the SH4a.
  • -m4al โ€” lowkey the same as -m4a-nofpu, except it sneaks -dsp through to the assembler for you. And nope, GCC isn't out here generating any DSP instructions at the moment, bestie, it's just passing the flag along. ๐Ÿ’…
  • -mb โ€” compile your code for the processor in big-endian mode. big endian rights โœจ
  • -ml โ€” compile your code for the processor in little-endian mode. tiny endian energy ๐ŸŽ€
  • -mdalign โ€” align doubles at 64-bit boundaries. โš ๏ธ heads up though: this literally changes the calling conventions, so some functions from the standard C library will not work unless you recompile it first with -mdalign. not a drill, recompile your libc first fr fr ๐Ÿ˜ญ
  • -mrelax โ€” shorten some address references at link time when it's possible; it does this by using the linker option -relax. cuter links, same vibes ๐Ÿฆ‹
  • -mbigtable โ€” use 32-bit offsets in switch tables. the default is 16-bit offsets, so this is you choosing the bigger ~~purse~~ table.
  • -mbitops โ€” enable the use of bit manipulation instructions on SH2A. bit-flipping era ๐Ÿ”ฅ
  • -mfmovd โ€” enable the use of the instruction fmovd. and please go check -mdalign for the alignment constraints, because alignment drama is real. ๐Ÿ‘€
  • -mrenesas โ€” comply with the calling conventions defined by Renesas. respect the house rules ๐Ÿ’…
  • -mno-renesas โ€” comply with the calling conventions defined for GCC before the Renesas conventions were even a thing. this option is the default for all targets of the SH toolchain, so it's giving main character energy by being the standard. ๐Ÿ‘‘
  • -mnomacsave โ€” mark the MAC register as call-clobbered, even if -mrenesas is given. MAC said "don't save me" and we're respecting it. ๐Ÿ™ˆ
  • -mieee, -mno-ieee โ€” control the IEEE compliance of floating-point comparisons, which affects how we handle the cases where the result of a comparison is unordered. by default -mieee is implicitly enabled. ๐Ÿ’– but if -ffinite-math-only is enabled, then -mno-ieee is implicitly set, which gives you faster floating-point greater-equal and less-equal comparisons. and both of those implicit settings can be overridden by just specifying either -mieee or -mno-ieee yourself. you're in charge, bestie. โœจ
  • -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 doesn't allow icbi and -musermode is not in effect, then the inlined code manipulates the instruction cache address array directly with an associative write. and that's a whole situation, because it not only requires privileged mode at run time, it also fails if the cache line had been mapped via the TLB and has become unmapped. ๐Ÿ˜ญ the TLB said "we're done here." ๐Ÿ’€
  • -misize โ€” dump instruction size and location in the assembly code. little receipts for every instruction, iykyk ๐Ÿงพ
  • -mpadstruct โ€” okay so this option is deprecated. it pads structures to multiple of 4 bytes, which is incompatible with the SH ABI. deprecated means move on, bestie, it's not coming back. ๐Ÿšฉ
  • -matomic-model=model โ€” sets the model of atomic operations and additional parameters as a comma separated list. for the details on the atomic built-in functions, go 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. these generated atomic sequences require additional support from the interrupt/exception handling code of the system, and they're 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 they're only suitable for single-core systems. when using this model, the gbr-offset= parameter has to be specified as well. no skipping it. ๐Ÿซถ
    • 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 it's 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 it's 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. rules are rules ๐ŸŽ€
    • 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. no blending, no mixing, one model only. periodt. ๐Ÿ’…
  • -mtas โ€” generate the tas.b opcode for __atomic_test_and_set. โš ๏ธ but notice: 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. and on multi-core SH4A processors the tas.b instruction must be used with caution since it can result in data corruption for certain cache configurations. data corruption is not the vibe, be careful out there ๐Ÿ˜ญ๐Ÿ’€
  • -mprefergot โ€” when generating position-independent code, emit function calls using the Global Offset Table instead of the Procedure Linkage Table. GOT > PLT for this one specific situation, and that's that. ๐Ÿฆ‹
  • -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*. and if the target is SH1* or SH2*, -musermode has no effect, since there is no user mode. there's just nothing to switch to, bestie. ๐Ÿซ 
  • -multcost=number โ€” set the cost to assume for a multiply insn. one number, one multiply, one cost. โญ
  • -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. no library, just vibes and instructions. ๐Ÿ”ฅ

  • -maccumulate-outgoing-args โ€” reserve space once for outgoing arguments in the function prologue rather than around each call. generally beneficial for performance and size. it's also needed for unwinding to avoid changing the stack frame around conditional code. efficiency icon ๐Ÿ‘‘
  • -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. so rename all you want, the register contract stays. ๐Ÿ’…
  • -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. hands off those registers, allocator. โœ‹
  • -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. pick a number, any number (but pick it deliberately) โญ
  • -mzdcbranch, -mno-zdcbranch โ€” assume (do not assume) that zero displacement conditional branch instructions bt and bf are fast. if -mzdcbranch is specified, the compiler prefers zero displacement branch code sequences. this is enabled by default when generating code for SH4 and SH4A, and it can be explicitly disabled by specifying -mno-zdcbranch. ๐Ÿฆ‹
  • -mcbranch-force-delay-slot โ€” force the usage of delay slots for conditional branches, which stuffs the delay slot with a nop if a suitable instruction cannot be found. by default this option is disabled. it can be enabled to work around hardware bugs as found in the original SH7055. bugs are not the moment, but the workaround is ๐Ÿ˜ญ
  • -mfused-madd, -mno-fused-madd โ€” generate code that uses (does not use) the floating-point multiply and accumulate instructions. these instructions are generated by default if hardware floating point is used. ๐Ÿ“ข and here's the plot twist: the machine-dependent -mfused-madd option is now mapped to the machine-independent -ffp-contract=fast option, and -mno-fused-madd is mapped to -ffp-contract=off. the old flags are still hanging around like a loyal bestie ๐Ÿซถ
  • -mfsca, -mno-fsca โ€” lets you green-light (or hard no) the compiler emitting the "fsca" instruction for sine and cosine approximations โœจ heads up tho: -mfsca only works with -funsafe-math-optimizations, they're a package deal. It's on by default when you're generating code for SH4A. And -mno-fsca kills the sine/cosine approximations even if -funsafe-math-optimizations is literally right there in effect ๐Ÿซถ
  • -mfsrra, -mno-fsrra โ€” same vibe but for the "fsrra" instruction, aka reciprocal square root approximations ๐Ÿ’… the catch: -mfsrra has to be used in combination with -funsafe-math-optimizations and -ffinite-math-only. Enabled by default when generating code for SH4A. -mno-fsrra disables reciprocal square root approximations even if -funsafe-math-optimizations and -ffinite-math-only are both in effect, no cap.
  • -mpretend-cmove โ€” prefers zero-displacement conditional branches for conditional move instruction patterns ๐Ÿฆ‹ and yeah, this can result in faster code on the SH4 processor. slay.
  • -mfdpic โ€” generate code using the FDPIC ABI ๐Ÿ‘‘

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

-mimpure-text suppresses the "relocations remain against allocatable but non-writable sections" linker error message. However, the necessary relocations trigger copy-on-write, and the shared object is not actually shared across processes ๐Ÿ˜ญ instead of using -mimpure-text, you should compile all source code with -fpic or -fPIC. fr fr, listen to the manpage on this one.

These switches are supported in addition to the above on Solaris 2:

  • -pthreads โ€” this is a synonym for -pthread ๐Ÿ’–

โญ SPARC Options โญ

These -m options are supported on the SPARC:

  • -mno-app-regs, -mapp-regs โ€” specify -mapp-regs to generate output using the global registers 2 through 4, which the SPARC SVR4 ABI reserves for applications ๐Ÿ‘€ like the global register 1, each global register 2 through 4 is then treated as an allocable register that is clobbered by function calls. This is the default.

To be fully SVR4 ABI-compliant at the cost of some performance loss, specify -mno-app-regs. You should compile libraries and system software with this option ๐Ÿซก

  • -mflat, -mno-flat โ€” with -mflat, the compiler does not generate save/restore instructions and uses a "flat" or single register window model ๐ŸŒˆ this model is compatible with the regular register window model. The local registers and the input registers (0--5) are still treated as "call-saved" registers and are saved on the stack as needed.

With -mno-flat (the default), the compiler generates save/restore instructions (except for leaf functions). This is the normal operating mode ๐Ÿ’…

  • -mfpu, -mhard-float โ€” generate output containing floating-point instructions. This is the default โœจ
  • -mno-fpu, -msoft-float โ€” generate output containing library calls for floating point.
โš ๏ธ Warning: the requisite libraries are not available for all SPARC targets. Normally the facilities of the machine's usual C compiler are used, but this cannot be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation. The embedded targets sparc-*-aout and sparclite-*-* do provide software floating-point support.

-msoft-float changes the calling convention in the output file; therefore, it is only useful if you compile all of a program with this option ๐Ÿ˜ญ in particular, you need to compile libgcc.a, the library that comes with GCC, with -msoft-float in order for this to work. all of it. no half-measures.

  • -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. makes sense, honestly.

  • -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. you've been warned, 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 ๐Ÿ’€ vintage behavior unlocked, 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 ๐Ÿ’–

  • 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 generates code for the V9 variant of the SPARC architecture. This adds 64-bit integer and floating-point move instructions, 3 additional floating-point condition code registers and conditional move instructions ๐Ÿ‘‘ with -mcpu=ultrasparc, the compiler additionally optimizes it for the Sun UltraSPARC I/II/IIi chips. With -mcpu=ultrasparc3, the compiler additionally optimizes it for the Sun UltraSPARC III/III+/IIIi/IIIi+/IV/IV+ chips. With -mcpu=niagara, the compiler additionally optimizes it for Sun UltraSPARC T1 chips. With -mcpu=niagara2, the compiler additionally optimizes it for Sun UltraSPARC T2 chips. With -mcpu=niagara3, the compiler additionally optimizes it for Sun UltraSPARC T3 chips. With -mcpu=niagara4, the compiler additionally optimizes it for Sun UltraSPARC T4 chips. With -mcpu=niagara7, the compiler additionally optimizes it for Oracle SPARC M7 chips. With -mcpu=m8, the compiler additionally optimizes it for Oracle M8 chips ๐ŸŒŸ

  • -mtune=cpu_type โ€” okay so this one tunes how instructions get scheduled for cpu_type, but it does not touch the instruction set or register set like -mcpu=cpu_type does. Same value list as -mcpu=cpu_type, but ngl only the ones that pick an actual CPU implementation are useful, and those are: cypress, supersparc, hypersparc, leon, leon3, leon3v7, leon5, f930, f934, sparclite86x, tsc701, ultrasparc, ultrasparc3, niagara, niagara2, niagara3, niagara4, niagara7 and m8. With native Solaris and GNU/Linux toolchains you can also use native. ๐Ÿ’…
  • -mv8plus, -mno-v8plus โ€” with -mv8plus, GCC spits out code for the SPARC-V8+ ABI. The glow-up vs. the V8 ABI? Global and out registers are considered 64 bits wide. Default-on for Solaris in 32-bit mode for all SPARC-V9 processors, periodt. โœจ
  • -mvis, -mno-vis โ€” -mvis lets GCC generate code that takes advantage of the UltraSPARC Visual Instruction Set extensions. Default is -mno-vis (soz, off by default bestie).
  • -mvis2, -mno-vis2 โ€” -mvis2 = version 2.0 of the UltraSPARC Visual Instruction Set extensions, slay. Default is -mvis2 when you're targeting a cpu that supports these instructions, like UltraSPARC-III and later. Setting -mvis2 also sets -mvis. ๐Ÿซถ
  • -mvis3, -mno-vis3 โ€” -mvis3 = version 3.0 of the UltraSPARC Visual Instruction Set extensions. Default is -mvis3 when the cpu supports them, like niagara-3 and later. Setting -mvis3 also sets -mvis2 and -mvis. ๐Ÿ”ฅ
  • -mvis4, -mno-vis4 โ€” -mvis4 = version 4.0 of the UltraSPARC Visual Instruction Set extensions. Default is -mvis4 when the cpu supports them, like niagara-7 and later. Setting -mvis4 also sets -mvis3, -mvis2 and -mvis. ๐Ÿ‘‘
  • -mvis4b, -mno-vis4b โ€” -mvis4b = version 4.0 of the UltraSPARC Visual Instruction Set extensions plus the extra VIS instructions introduced in the Oracle SPARC Architecture 2017. Default is -mvis4b when the cpu supports them, like m8 and later. Setting -mvis4b also sets -mvis4, -mvis3, -mvis2 and -mvis. ๐ŸŒˆ
  • -mcbcond, -mno-cbcond โ€” with -mcbcond, GCC generates code that takes advantage of the UltraSPARC Compare-and-Branch-on-Condition instructions. Default is -mcbcond when targeting a CPU that supports them, like 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 them, like 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 architecture versions V8 or V9 with FPU โ€” but not -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 it, like 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 it, like 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). ๐ŸŽ€
  • -mfix-ut699 โ€” turns on the documented workarounds for the floating-point errata and the data cache nullify errata of the UT699 processor.
  • -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. ๐Ÿฆ‹

So these -m options are supported in addition to all the ones above on SPARC-V9 processors in 64-bit environments, iykyk:

  • -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. ๐Ÿ’€
  • -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. ๐Ÿ“–

  • -mstack-bias, -mno-stack-bias โ€” with -mstack-bias, GCC assumes 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, bestie:

  • -G โ€” create a shared object. It is recommended that -symbolic or -shared be used instead (so like, lowkey deprecated vibes).
  • -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, no cap:

  • -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. ๐ŸŽ€
  • -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. (yes, it's giving copy-paste energy, but that's literally what the docs say ๐Ÿ’€)
  • -mv850e2v3 โ€” specify that the target processor is the V850E2V3. The preprocessor constant __v850e2v3__ is defined if this option is used.
  • -mv850e2 โ€” specify that the target processor is the V850E2. The preprocessor constant __v850e2__ is defined if this option is used.
  • -mv850e1 โ€” specify that the target processor is the V850E1. The preprocessor constants __v850e1__ and __v850e__ are defined if this option is used. ๐Ÿ’œ
  • -mv850es โ€” specify that the target processor is the V850ES. This is an alias for the -mv850e1 option.
  • -mv850e โ€” specify that the target processor is the V850E. The preprocessor constant __v850e__ is defined if this option is used. ๐ŸŒธ
Heads up bestie: if neither -mv850 nor -mv850e nor -mv850e1 nor -mv850e2 nor -mv850e2v3 nor -mv850e3v5 are defined, then a default target processor is chosen and the relevant __v850*__ preprocessor constant is defined. And the preprocessor constants __v850 and __v851__ are always defined, regardless of which processor variant is the target. ๐ŸŽ€
  • -mdisable-callt, -mno-disable-callt โ€” this option suppresses generation of the CALLT instruction for the v850e, v850e1, v850e2, v850e2v3 and v850e3v5 flavors of the v850 architecture. ๐Ÿ’…

This one's on by default when the RH850 ABI is in use (peep -mrh850-abi), and off by default when the GCC ABI is in use. And if CALLT instructions are being generated, the C preprocessor symbol __V850_CALLT__ gets defined. ๐Ÿ’…

  • -mrelax, -mno-relax โ€” passes on (or doesn't pass on) the -mrelax command-line option to the assembler.
  • -mlong-jumps, -mno-long-jumps โ€” disables (or re-enables) generation of PC-relative jump instructions.
  • -msoft-float, -mhard-float โ€” disables (or re-enables) generation of hardware floating point instructions. Only significant when the target architecture is V850E2V3 or higher. If hardware floating point instructions are being generated then the C preprocessor symbol __FPU_OK__ is defined, otherwise __NO_FPU__ is defined. ๐Ÿซถ
  • -mloop โ€” enables the use of the e3v5 LOOP instruction. Not enabled by default when the e3v5 architecture is selected, because its use is still experimental. ๐Ÿ™ˆ
  • -mrh850-abi, -mghs โ€” enables support for the RH850 version of the V850 ABI. This is the default. With this version of the ABI, these 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, these 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 โ€” generates code suitable for big switch tables. Only use this if the assembler/linker complain about out of range branches within a switch table. ๐Ÿ’€
  • -mapp-regs โ€” this one makes r2 and r5 get used in the code the compiler generates. This setting is the default.
  • -mno-app-regs โ€” this one makes r2 and r5 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 that does 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 that does file I/O and is destined to run on the simulator should be linked with this option. This causes libraries libc.a and libsim.a to be linked.
  • -mfpu, -mhard-float โ€” generate code containing floating-point instructions. This is the default.
  • -mno-fpu, -msoft-float โ€” generate code containing library calls for floating-point.
Bestie, listen: -msoft-float changes the calling convention in the output file. So it's only useful if you compile all of a program with this option. In particular, you need to compile libgcc.a (the library that comes with GCC) with -msoft-float for this to work. No cap. ๐Ÿšจ
  • *-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. 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 -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 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. That last 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're 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. Buckle up, bestie, there's a lot of them. ๐Ÿ’…

  • -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 โ€” 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 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 โ€” when used with -march, the Pentium Pro instruction set is used, so the code runs on all i686 family chips. When used with -mtune, it has the same meaning as generic.
  • pentium2 โ€” Intel Pentium II CPU, based on Pentium Pro core with MMX and FXSR instruction set support.
  • pentium3, pentium3m โ€” Intel Pentium III CPU, based on Pentium Pro core with MMX, FXSR and SSE instruction set support.
  • pentium-m โ€” Intel Pentium M; low-power version of Intel Pentium III CPU with MMX, SSE, SSE2 and FXSR instruction set support. Used by Centrino notebooks. ๐ŸŽ€
  • pentium4, pentium4m โ€” Intel Pentium 4 CPU with MMX, SSE, SSE2 and FXSR instruction set support.
  • prescott โ€” improved version of Intel Pentium 4 CPU with MMX, SSE, SSE2, SSE3 and FXSR instruction set support.

๐ŸŽ€ nocona

Improved version of Intel Pentium 4 CPU with 64-bit extensions, and the instruction set support is: MMX, SSE, SSE2, SSE3, FXSR. Vintage, but she still serves ๐Ÿ’…

๐ŸŒธ core2

Intel Core 2 CPU, 64-bit extensions, bringing MMX, SSE, SSE2, SSE3, SSSE3, CX16, SAHF, FXSR instruction set support. The CPU that raised a whole generation of nerds, honestly ๐Ÿซถ

๐Ÿฆ‹ nehalem, corei7

Both names, same girl โœจ Intel Nehalem CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF and FXSR instruction set support. That's MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR โ€” iconic.

๐Ÿ’œ westmere

Intel Westmere CPU with 64-bit extensions and MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL instruction set support. She said "add PCLMUL" and honestly? slay.

๐ŸŒˆ sandybridge, corei7-avx

Two aliases, one vibe ๐Ÿ’– Intel Sandy Bridge CPU with 64-bit extensions and MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL instruction set support. AVX walked in and everything changed, periodt.

โญ 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 โ€” so: MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C. Bestie she is stacked ๐Ÿงš

๐Ÿ”ฅ haswell, core-avx2

Intel Haswell CPU with 64-bit extensions, and the full support list is 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. AVX2 debut, we were all gagged ๐Ÿ˜ญ

๐Ÿ‘‘ 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, PREFETCHW instruction set support. Yes, MOVBE shows up twice in there โ€” that's what the list says, don't come for me ๐Ÿ™ˆ

๐Ÿ’ซ 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, SGX instruction set support. Main character energy, lowkey the default for a whole era โญ

๐Ÿฆ‹ skylake-avx512

Intel Skylake Server CPU with 64-bit extensions, and the list just keeps going bestie: MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD instruction set support. The AVX-512 era begins ๐Ÿ’€โœจ

๐ŸŒธ 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, AVX512VNNI instruction set support. Basically Skylake-AVX512 but with AVX512VNNI, and we love an upgrade ๐Ÿ’…

๐ŸŽ€ cannonlake

Intel Cannon Lake Server CPU with 64-bit extensions, supporting 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. New friends: PKU, AVX512VBMI, AVX512IFMA, SHA ๐Ÿซถ

๐ŸŒˆ cooperlake

Intel Cooper Lake CPU with 64-bit extensions and 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, AVX512BF16 instruction set support. AVX512BF16 said hi ๐Ÿ”ฅ

๐Ÿงš icelake-client

Intel Ice Lake Client CPU with 64-bit extensions, supporting 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. That list is a whole personality and I respect it ๐Ÿ˜ญ

๐ŸŒธ 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, CLWB. Server edition, extra toppings, no notes ๐Ÿ‘‘

๐Ÿ’œ tigerlake

Intel Tiger Lake CPU with 64-bit extensions and 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, KEYLOCKER instruction set support. Yes AVX512VP2INTERSECT is a real name, I didn't make it up ๐Ÿ’€

โญ 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, AVX512VPOPCNTDQ instruction set support. Note she's the desktop one, no SGX here ๐Ÿซถ

๐Ÿ“ alderlake, raptorlake, meteorlake

Three names, one CPU family ๐Ÿ’– Intel Alder Lake/Raptor Lake/Meteor Lake CPU with 64-bit extensions and 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, AVX-VNNI instruction set support. Hybrid era, ate and left no crumbs.

๐ŸŒˆ sapphirerapids, emeraldrapids

Both aliases, same giant flex โœจ Intel Sapphire Rapids/Emerald Rapids CPU with 64-bit extensions, supporting 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 has entered the chat ๐Ÿ‘‘

๐Ÿงš 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, PREFETCHI instruction set support. AMX-FP16 and PREFETCHI are the new girls ๐Ÿ’…

๐Ÿฆ‹ graniterapids-d

Intel Granite Rapids D CPU with 64-bit extensions, and yes there's one more at the end: 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, AMX-COMPLEX instruction set support. AMX-COMPLEX really said "and one more thing" ๐Ÿ˜ญ

๐ŸŽ€ bonnell, atom

Intel Bonnell CPU with 64-bit extensions, keeping it cute and small with MOVBE, MMX, SSE, SSE2, SSE3, SSSE3 instruction set support. Netbook legend, lowkey iconic ๐Ÿ“

๐ŸŒธ silvermont, slm

Intel Silvermont CPU with 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND instruction set support. Tiny chip, big try ๐Ÿซถ

โญ 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, FSGSBASE instruction set support. Look at her go, she's got XSAVE now ๐Ÿ’œ

๐Ÿ’œ goldmont-plus

Intel Goldmont Plus CPU with 64-bit extensions, supporting 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. The "plus" is PTWRITE, RDPID and SGX, and she earned them โœจ

๐Ÿ”ฅ tremont

Intel Tremont CPU with 64-bit extensions: MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT, FSGSBASE, PTWRITE, RDPID, SGX, CLWB, GFNI-SSE, MOVDIRI, MOVDIR64B, CLDEMOTE, WAITPKG instruction set support. The low-power one with the longest list, honestly rude of her ๐Ÿ’€

  • sierraforest โ€” Intel Sierra Forest CPU, and she's got 64-bit extensions plus an entire buffet of instruction set support: 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. like. that's the whole list bestie, no crumbs left ๐Ÿ’…
  • grandridge โ€” Intel Grand Ridge CPU, 64-bit extensions, and honestly the exact same flex as above: 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. twin energy fr ๐Ÿซถ
  • knl โ€” Intel Knights Landing CPU. 64-bit extensions and: 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 MOVBE shows up twice in the list, don't @ me, that's literally what it says ๐Ÿ˜ญ)
  • knm โ€” Intel Knights Mill CPU. 64-bit extensions plus: 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. she's got extras โœจ
  • k6 โ€” AMD K6 CPU, MMX instruction set support. vintage but cute ๐ŸŽ€
  • k6-2, k6-3 โ€” improved versions of the AMD K6 CPU with MMX and 3DNow! instruction set support. glow-up szn ๐ŸŒธ
  • athlon, athlon-tbird โ€” AMD Athlon CPU, rocking MMX, 3dNOW!, enhanced 3DNow! and SSE prefetch instructions support.
  • athlon-4, athlon-xp, athlon-mp โ€” improved AMD Athlon CPU with MMX, 3DNow!, enhanced 3DNow! and the full SSE instruction set support. the way she ate ๐Ÿ’…
  • k8, opteron, athlon64, athlon-fx โ€” processors built on the AMD K8 core with x86-64 instruction set support, and that includes the AMD Opteron, Athlon 64, and Athlon 64 FX processors. (bestie, this supersets MMX, SSE, SSE2, 3DNow!, enhanced 3DNow! and 64-bit instruction set extensions.) ๐Ÿ‘‘
  • k8-sse3, opteron-sse3, athlon64-sse3 โ€” improved versions of AMD K8 cores, now with SSE3 instruction set support. upgrade era ๐Ÿฆ‹
  • 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.) the AVX512 arc, iconic ๐Ÿ”ฅ
  • 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.) newest gen, main character energy ๐Ÿ‘‘
  • 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 one 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. (note: "includes" this time, not "supersets" โ€” read the room ๐Ÿ’€)
  • 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.)
ok the "no scheduling is implemented for this chip" note is lowkey doing a lot of heavy lifting in this VIA section โ€” it's a real caveat, not a vibe, so don't expect fancy instruction scheduling for any of these ๐Ÿฅฒ
  • 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.) two cores, zero scheduling, we love consistency ๐ŸŒˆ
  • 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 โ€” ZHAOXIN lujiazui CPU with x86-64, 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. While the CPUs do support AVX and F16C, these aren't enabled by -march=lujiazui for performance reasons. ๐Ÿ‘€ (yes bestie, they exist and they're deliberately gated โ€” that's the note, don't come for me)
  • geode โ€” AMD Geode embedded processor with MMX and 3DNow! instruction set support. tiny legend ๐Ÿ“
  • -mtune=cpu-type โ€” tunes literally everything applicable about the generated code to cpu-type, except the ABI and the set of available instructions ๐Ÿ’…. So like, picking a specific cpu-type schedules things appropriately for that particular chip, but the compiler does not generate any code that can't run on the default machine type unless you also use a -march=cpu-type option. Example bestie: if GCC is configured for i686-pc-linux-gnu then -mtune=pentium4 generates code that is tuned for Pentium 4 but still runs on i686 machines โœจ.

The choices for cpu-type are the same as for -march. In addition, -mtune supports 2 extra choices for cpu-type:

  • generic โ€” produce code optimized for the most common IA32/AMD64/EM64T processors ๐ŸŒธ. If you know the CPU on which your code will run, then you should use the corresponding -mtune or -march option instead of -mtune=generic. But, if you do not know exactly what CPU users of your application will have, then you should use this option ๐Ÿซถ.

As new processors are deployed in the marketplace, the behavior of this option will change. Therefore, if you upgrade to a newer version of GCC, code generation controlled by this option will change to reflect the processors that are most common at the time that version of GCC is released ๐Ÿ‘‘.

There is no -march=generic option because -march indicates the instruction set the compiler can use, and there is no generic instruction set applicable to all processors. In contrast, -mtune indicates the processor (or, in this case, collection of processors) for which the code is optimized ๐Ÿ’–.

  • intel โ€” produce code optimized for the most current Intel processors, which are Haswell and Silvermont for this version of GCC ๐Ÿ”ฅ. If you know the CPU on which your code will run, then you should use the corresponding -mtune or -march option instead of -mtune=intel. But, if you want your application performs better on both Haswell and Silvermont, then you should use this option โœจ.

As new Intel processors are deployed in the marketplace, the behavior of this option will change. Therefore, if you upgrade to a newer version of GCC, code generation controlled by this option will change to reflect the most current Intel processors at the time that version of GCC is released ๐ŸŒˆ.

There is no -march=intel option because -march indicates the instruction set the compiler can use, and there is no common instruction set applicable to all processors. In contrast, -mtune indicates the processor (or, in this case, collection of processors) for which the code is optimized ๐ŸŽ€.

  • -mcpu=cpu-type โ€” a deprecated synonym for -mtune ๐Ÿ’€. Like, it still works but it's giving "old news", yk? Use -mtune instead, bestie ๐Ÿ™ˆ.
  • -mfpmath=unit โ€” generate floating-point arithmetic for selected unit unit ๐Ÿ’…. The choices for unit are:
    • 387 โ€” use the standard 387 floating-point coprocessor present on the majority of chips and emulated otherwise ๐Ÿงš. Code compiled with this option runs almost everywhere. The temporary results are computed in 80-bit precision instead of the precision specified by the type, resulting in slightly different results compared to most of other chips. See -ffloat-store for more detailed description โญ.

This is the default choice for non-Darwin x86-32 targets ๐Ÿ“.

  • sse โ€” use scalar floating-point instructions present in the SSE instruction set ๐ŸŒธ. This instruction set is supported by Pentium III and newer chips, and in the AMD line by Athlon-4, Athlon XP and Athlon MP chips. The earlier version of the SSE instruction set supports only single-precision arithmetic, thus the double and extended-precision arithmetic are still done using 387. A later version, present only in Pentium 4 and AMD x86-64 chips, supports double-precision arithmetic too ๐Ÿ‘‘.

For the x86-32 compiler, you must use -march=cpu-type, -msse or -msse2 switches to enable SSE extensions and make this option effective. For the x86-64 compiler, these extensions are enabled by default ๐Ÿซถ.

The resulting code should be considerably faster in the majority of cases and avoid the numerical instability problems of 387 code, but may break some existing code that expects temporaries to be 80 bits ๐Ÿ˜ญ. (Yeah, that's the tradeoff, bestie.)

This is the default choice for the x86-64 compiler, Darwin x86-32 targets, and the default choice for x86-32 targets with the SSE2 instruction set when -ffast-math is enabled โœจ.

  • sse,387 / sse+387 / both โ€” attempt to utilize both instruction sets at once ๐Ÿ”ฅ. This effectively doubles the amount of available registers, and on chips with separate execution units for 387 and SSE the execution resources too. Use this option with care, as it is still experimental, because the GCC register allocator does not model separate functional units well, resulting in unstable performance ๐Ÿ’€. No cap, it's giving "handle with care" energy.
  • -masm=dialect โ€” output assembly instructions using selected dialect ๐ŸŽ€. Also affects which dialect is used for basic asm and extended asm. Supported choices (in dialect order) are att or intel. The default is att. Darwin does not support intel ๐ŸŒธ.
  • -mieee-fp / -mno-ieee-fp โ€” control whether or not the compiler uses IEEE floating-point comparisons ๐Ÿ’…. These correctly handle the case where the result of a comparison is unordered โœจ.
  • -m80387 / -mhard-float โ€” generate output containing 80387 instructions for floating point ๐Ÿงฎโœจ.
  • -mno-80387 / -msoft-float โ€” generate output containing library calls for floating point ๐Ÿซถ.
Warning: the requisite libraries are not part of GCC ๐Ÿ˜ญ. Normally the facilities of the machine's usual C compiler are used, but this cannot be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation ๐Ÿ’€. On machines where a function returns floating-point results in the 80387 register stack, some floating-point opcodes may be emitted even if -msoft-float is used ๐ŸŒธ.
  • -mno-fp-ret-in-387 โ€” do not use the FPU registers for return values of functions ๐Ÿ™ˆ.

The usual calling convention has functions return values of types float and double in an FPU register, even if there is no FPU. The idea is that the operating system should emulate an FPU ๐Ÿงš.

The option -mno-fp-ret-in-387 causes such values to be returned in ordinary CPU registers instead ๐Ÿ’….

  • -mno-fancy-math-387 โ€” some 387 emulators do not support the sin, cos and sqrt instructions for the 387 ๐Ÿ˜ญ. Specify this option to avoid generating those instructions โญ. This option is overridden when -march indicates that the target CPU always has an FPU and so the instruction does not need emulation. These instructions are not generated unless you also use the -funsafe-math-optimizations switch ๐Ÿ”ฅ.
  • -malign-double / -mno-align-double โ€” control whether GCC aligns double, long double, and long long variables on a two-word boundary or a one-word boundary ๐Ÿ’…. Aligning double variables on a two-word boundary produces code that runs somewhat faster on a Pentium at the expense of more memory ๐Ÿ“.

On x86-64, -malign-double is enabled by default โœจ.

Warning: if you use the -malign-double switch, structures containing the above types are aligned differently than the published application binary interface specifications for the x86-32 and are not binary compatible with structures in code compiled without that switch ๐Ÿ’€.
  • -m96bit-long-double / -m128bit-long-double โ€” these switches control the size of long double type ๐ŸŽ€. The x86-32 application binary interface specifies the size to be 96 bits, so -m96bit-long-double is the default in 32-bit mode.

Modern architectures (Pentium and newer) prefer long double to be aligned to an 8- or 16-byte boundary ๐ŸŒธ. In arrays or structures conforming to the ABI, this is not possible. So specifying -m128bit-long-double aligns long double to a 16-byte boundary by padding the long double with an additional 32-bit zero โœจ.

In the x86-64 compiler, -m128bit-long-double is the default choice as its ABI specifies that long double is aligned on 16-byte boundary ๐Ÿ‘‘.

Notice that neither of these options enable any extra precision over the x87 standard of 80 bits for a long double ๐Ÿ™ˆ.

Warning: if you override the default value for your target ABI, this changes the size of structures and arrays containing long double variables, as well as modifying the function calling convention for functions taking long double. Hence they are not binary-compatible with code compiled without that switch ๐Ÿ’€.
  • -mlong-double-64 / -mlong-double-80 / -mlong-double-128 โ€” these switches control the size of long double type ๐ŸŒˆ. A size of 64 bits makes the long double type equivalent to the double type. This is the default for 32-bit Bionic C library ๐Ÿ“. A size of 128 bits makes the long double type equivalent to the __float128 type. This is the default for 64-bit Bionic C library โœจ.
Warning: if you override the default value for your target ABI, this changes the size of structures and arrays containing long double variables, as well as modifying the function calling convention for functions taking long double. Hence they are not binary-compatible with code compiled without that switch ๐Ÿ’€.
  • -malign-data=type โ€” control how GCC aligns variables ๐Ÿ’…. Supported values for type are compat uses increased alignment value compatible uses GCC 4.8 and earlier, abi uses alignment value as specified by the psABI, and cacheline uses increased alignment value to match the cache line size ๐ŸŒธ. compat is the default โญ.
  • -mlarge-data-threshold=threshold โ€” when -mcmodel=medium is specified, data objects larger than threshold are placed in the large data section ๐Ÿ”ฅ. This value must be the same across all objects linked into the binary, and defaults to 65535 ๐ŸŽ€.
  • -mrtd โ€” use a different function-calling convention, in which functions that take a fixed number of arguments return with the ret num instruction, which pops their arguments while returning ๐Ÿ‘‘. This saves one instruction in the caller since there is no need to pop the arguments there โœจ. Iconic little optimization, ngl.

  • "stdcall" โ€” slaps the stdcall calling sequence onto one specific function (function attribute energy). And if you're feeling rebellious, you can override -mrtd by hitting it with the "cdecl" attribute instead.
โš ๏ธ Warning: this calling convention does not vibe with the one normally used on Unix, so you literally cannot use it if you need to call libraries compiled with the Unix compiler. Like, at all. No cap.

Also โ€” and this is important, bestie โ€” you must provide function prototypes for all functions that take a variable number of arguments (yes, that includes "printf"), otherwise GCC generates straight-up incorrect code for calls to those functions. ๐Ÿ’€

And on top of that? You get seriously incorrect code if you call a function with too many arguments. (Normally extra arguments are harmlessly ignored, so yeah, this is the one case where it bites.)

  • -mregparm=num โ€” controls how many registers get used to pass integer arguments. Default is zero registers passed, and you can push it to at most 3 registers. Want to control this for one specific function instead? Use the "regparm" function attribute.
โš ๏ธ Warning: if you use this switch and num is nonzero, then every single module has to be built with the same value โ€” libraries included. That means system libraries and startup modules too, no exceptions. ๐Ÿซถ
  • -msseregparm โ€” uses SSE register passing conventions for float and double arguments and return values. Fine-tune it per-function with the "sseregparm" function attribute.
โš ๏ธ Warning: same deal โ€” use this switch and all modules must be built with the same value, libraries and all. System libraries and startup modules included. ๐Ÿ’…
  • -mvect8-ret-in-mem โ€” returns 8-byte vectors in memory instead of in MMX registers. This is the default on VxWorks so it matches the ABI of the Sun Studio compilers up to version 12. Only reach for this option if you genuinely need to stay compatible with existing code produced by those previous compiler versions or older versions of GCC. Legacy-compat obligations only, iykyk.
  • -mpc32, -mpc64, -mpc80 โ€” sets 80387 floating-point precision to 32, 64 or 80 bits respectively. The details, because they matter:
    • -mpc32 rounds the significands of floating-point operation results to 24 bits (single precision).
    • -mpc64 rounds them to 53 bits (double precision).
    • -mpc80 rounds them to 64 bits (extended double precision) โ€” and that's the default.

When you use this option, floating-point operations in higher precisions are not available to the programmer unless you set the FPU control word explicitly. โœจ

Setting rounding to less than the default 80 bits can speed some programs up by 2% or more ๐Ÿ”ฅ โ€” but heads up: some mathematical libraries assume that extended-precision (80-bit) floating-point operations are enabled by default. Routines in those libraries could suffer significant loss of accuracy when this option sets precision below extended precision, typically through the so-called "catastrophic cancellation". So yeah, know what you're doing.

  • -mdaz-ftz โ€” the flush-to-zero (FTZ) and denormals-are-zero (DAZ) flags in the MXCSR register control floating-point calculations. SSE and AVX instructions, including scalar and vector instructions, can benefit from enabling the FTZ and DAZ flags when -mdaz-ftz is specified. Don't set the FTZ/DAZ flags when -mno-daz-ftz or -shared is specified โ€” oh, and -mdaz-ftz will set FTZ/DAZ flags even with -shared. Yeah, we said both. That's the whole bit. ๐Ÿ˜ญ
  • -mstackrealign โ€” realigns the stack at entry. On the x86, -mstackrealign generates an alternate prologue and epilogue that realigns the run-time stack whenever it's necessary. This is how you mix legacy code that keeps 4-byte stack alignment together with modern code that keeps 16-byte stack alignment for SSE compatibility. Also peep the "force_align_arg_pointer" attribute โ€” that one works per-function. ๐Ÿงš
  • -mpreferred-stack-boundary=num โ€” tries 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, a.k.a. 128 bits).
โš ๏ธ Warning: when generating code for the x86-64 architecture with SSE extensions disabled, you can use -mpreferred-stack-boundary=3 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 only meant for controlled environments where stack space is an important limitation. This option leads to wrong code when functions compiled with 16 byte stack alignment (like functions from a standard library) are called with a misaligned stack โ€” and in that case, SSE instructions may lead to misaligned memory access traps. Also, variable arguments are handled incorrectly for 16 byte aligned objects (including x87 long double and __int128), which gives you wrong results. You must build all modules with -mpreferred-stack-boundary=3, libraries included โ€” system libraries and startup modules too. ๐ŸŽ€
  • -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 make sure these values are properly aligned on the stack, the stack boundary has to be at least as aligned as anything stored on the stack requires. And every function must be generated so 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. Recommendation: libraries that use callbacks should always just use the default setting. ๐Ÿ‘‘

This extra alignment does eat extra stack space and generally increases code size. Code that's sensitive to stack space usage โ€” embedded systems and operating system kernels, we're looking at you โ€” may want to reduce the preferred alignment to -mpreferred-stack-boundary=2.

  • Here's the big one, the extended-instruction-set buffet ๐Ÿ“ โ€” each of these switches enables use of instructions in the corresponding set:
-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

So what do these actually turn on? 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 matching -mno- option to turn the instruction use back off. โœจ

These extensions are also available as built-in functions โ€” see x86 Built-in Functions for the full rundown of which functions these switches enable and disable.

Want SSE/SSE2 instructions generated automatically from floating-point code (instead of 387 instructions)? That's -mfpmath=sse, bestie.

Fun fact: GCC depresses SSEx instructions when -mavx is used. Instead it generates new AVX instructions, or AVX equivalence for all SSEx instructions, whenever they're needed. ๐Ÿ’…

These options let GCC use these extended instructions in generated code even without -mfpmath=sse. Applications that do run-time CPU detection have to compile separate files for each supported architecture, using the appropriate flags โ€” and in particular, the file containing the CPU detection code should be compiled without these options. Important detail, don't skip it. ๐ŸŒธ

  • -mdump-tune-features โ€” tells GCC to dump the names of the x86 performance tuning features and their default settings. Those names are exactly what you plug into -mtune-ctrl=feature-list. ๐Ÿฆ‹
  • -mtune-ctrl=feature-list โ€” fine-grain control over x86 code generation features. feature-list is a comma separated list of feature names (see also -mdump-tune-features). When specified, the feature is turned on if it isn't preceded with ^; if it is preceded by ^, it's turned off.
โš ๏ธ Heads up: -mtune-ctrl=feature-list is intended to be used by GCC developers. Using it may lead you into code paths that aren't covered by testing, and it can potentially result in compiler ICEs or runtime errors. You've been warned. ๐Ÿ˜ญ
  • -mno-default โ€” instructs GCC to turn off all tunable features. See also -mtune-ctrl=feature-list and -mdump-tune-features. ๐ŸŽ€
  • -mcld โ€” tells GCC to drop a cld instruction into the prologue of any function that uses string instructions ๐Ÿงต String instructions check the DF flag to pick autoincrement vs. autodecrement mode, and the ABI says DF is cleared on function entry โ€” but some operating systems are out here violating that spec and not clearing DF in their exception dispatchers ๐Ÿ˜ค so the exception handler can get invoked with DF set, and then your string instructions go in the wrong direction. This option can be on by default for 32-bit x86 targets if GCC was configured with --enable-cld. In that case you can suppress the cld instructions with -mno-cld.
  • -mvzeroupper โ€” makes GCC emit a vzeroupper instruction before control flow transfers out of the function, which minimizes the AVX-to-SSE transition penalty ๐Ÿ’จ and also removes unnecessary zeroupper intrinsics.
  • -mprefer-avx128 โ€” tells the auto-vectorizer to use 128-bit AVX instructions instead of 256-bit ones ๐ŸŽฏ
  • *-mprefer-vector-width=opt* โ€” tells GCC to use opt-bit vector width in instructions instead of whatever the default is on the selected platform. The values are:
    • none โ€” no extra limitations applied to GCC beyond the ones defined by the selected platform.
    • 128 โ€” prefer 128-bit vector width for instructions.
    • 256 โ€” prefer 256-bit vector width for instructions.
    • 512 โ€” prefer 512-bit vector width for instructions.
  • *-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.
  • -mcx16 โ€” lets GCC generate CMPXCHG16B instructions in 64-bit code so compare-and-exchange operations work on 16-byte-aligned 128-bit objects ๐Ÿ”’ which is super useful for atomically updating data structures bigger than one machine word. The compiler uses this instruction to implement __sync Builtins. But bestie, heads up: for __atomic Builtins operating on 128-bit integers, a library call is always used.
  • -msahf โ€” enables generation of SAHF instructions in 64-bit code. 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 are load and store instructions, respectively, for certain status flags. In 64-bit mode, the SAHF instruction 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 ๐Ÿ”„
  • -mshstk โ€” the -mshstk option enables shadow stack built-in functions from x86 Control-flow Enforcement Technology (CET) ๐Ÿ›ก๏ธ
  • -mcrc32 โ€” enables the built-in functions __builtin_ia32_crc32qi, __builtin_ia32_crc32hi, __builtin_ia32_crc32si and __builtin_ia32_crc32di to generate the crc32 machine instruction.
  • -mmwait โ€” enables the built-in functions __builtin_ia32_monitor and __builtin_ia32_mwait to 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 up precision, instead of DIVSS and SQRTSS (and their vectorized variants) for single-precision floating-point arguments โœจ These instructions are only generated when -funsafe-math-optimizations is enabled together with -ffinite-math-only and -fno-trapping-math. Note that while the throughput of the sequence is higher than the throughput of the non-reciprocal instruction, the precision of the sequence can go down by up to 2 ulp (i.e. the inverse of 1.0 equals 0.99999994).

Note that GCC already implements 1.0f/sqrtf(x) in terms of RSQRTSS (or RSQRTPS) with -ffast-math (or the option combo above), and doesn't need -mrecip.

Also note that GCC emits the above sequence with an additional Newton-Raphson step for vectorized single-float division and vectorized sqrtf(x) already with -ffast-math (or the option combo above), and doesn't need -mrecip.

  • *-mrecip=opt* โ€” controls which reciprocal estimate instructions may be used ๐ŸŽ›๏ธ opt is a comma-separated list of options, and any of them may be preceded by a ! to invert it:
    • all โ€” enable all estimate instructions.
    • default โ€” enable the default instructions, equivalent to -mrecip.
    • none โ€” disable all estimate instructions, equivalent to -mno-recip.
    • div โ€” enable the approximation for scalar division.
    • vec-div โ€” enable the approximation for vectorized division.
    • sqrt โ€” enable the approximation for scalar square root.
    • vec-sqrt โ€” enable the approximation for vectorized square root.

So, for example, -mrecip=all,!sqrt enables all of the reciprocal approximations except for square root ๐Ÿ’…

  • -mveclibabi=type โ€” specifies the ABI type to use for vectorizing intrinsics using an external library. Supported values for type are svml for the Intel short vector math library and acml for the AMD math core library. To use this option, **both -ftree-vectorize and -funsafe-math-optimizations have to be enabled, and an SVML- or ACML-ABI-compatible library must be specified at link time ๐Ÿ”—

GCC currently emits calls to vmldExp2, vmldLn2, vmldLog102, vmldPow2, vmldTanh2, vmldTan2, vmldAtan2, vmldAtanh2, vmldCbrt2, vmldSinh2, vmldSin2, vmldAsinh2, vmldAsin2, vmldCosh2, vmldCos2, vmldAcosh2, vmldAcos2, vmlsExp4, vmlsLn4, vmlsLog104, vmlsPow4, vmlsTanh4, vmlsTan4, vmlsAtan4, vmlsAtanh4, vmlsCbrt4, vmlsSinh4, vmlsSin4, vmlsAsinh4, vmlsAsin4, vmlsCosh4, vmlsCos4, vmlsAcosh4 and vmlsAcos4 for the corresponding function type when -mveclibabi=svml is used, and __vrd2_sin, __vrd2_cos, __vrd2_exp, __vrd2_log, __vrd2_log2, __vrd2_log10, __vrs4_sinf, __vrs4_cosf, __vrs4_expf, __vrs4_logf, __vrs4_log2f, __vrs4_log10f and __vrs4_powf for the corresponding function type when -mveclibabi=acml is used.

  • *-mabi=name* โ€” generates 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 the Microsoft ABI when targeting Microsoft Windows, and the SysV ABI on all other systems ๐Ÿ–ฅ๏ธ You can control this behavior for specific functions using the function attributes ms_abi and sysv_abi.
  • -mforce-indirect-call โ€” forces all calls to functions to be indirect. This is useful when using Intel Processor Trace, where it generates more precise timing information for function calls โฑ๏ธ
  • -mmanual-endbr โ€” inserts the ENDBR instruction at function entry only via the cf_check function attribute. Useful with the -fcf-protection=branch option to control ENDBR insertion at the function entry ๐Ÿ”
  • -mcet-switch โ€” by default, CET instrumentation is turned off on switch statements that use a jump table, and indirect branch track is disabled. Since jump tables live 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 makes the jump targets 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 do those saves and restores, reducing function size at the cost of a few extra instructions.
  • *-mtls-dialect=type* โ€” generates code to access thread-local storage using the gnu or gnu2 conventions. gnu is the conservative default; gnu2 is more efficient, but it may add compile- and run-time requirements that can't be satisfied on all systems โš ๏ธ
  • -mpush-args, -mno-push-args โ€” use PUSH operations to store outgoing parameters. This method is shorter and usually just as fast as the method using SUB/MOV operations, and it's enabled by default. In some cases disabling it may improve performance, thanks to 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 isn't equal to 2. The drawback? A notable increase in code size ๐Ÿ˜ฌ This switch implies -mno-push-args.
  • -mthreads โ€” supports thread-safe exception handling on MinGW ๐Ÿงต Programs that rely on thread-safe exception handling must compile and link all code with the -mthreads option. When compiling, -mthreads defines -D_MT; when linking, it links in a special thread helper library -lmingwthrd which cleans up per-thread exception-handling data.
  • -mms-bitfields, -mno-ms-bitfields โ€” enable/disable bit-field layout compatible with the native Microsoft Windows compiler.

If packed is used on a structure, or if bit-fields are used, it may be that the Microsoft ABI lays out the structure differently than GCC normally does ๐Ÿ‘€ Particularly when moving packed data between functions compiled with GCC and the native Microsoft compiler (either via a function call or as data in a file), it may be necessary to access either format.

This option is enabled by default for Microsoft Windows targets. You can also control it locally with variable or type attributes โ€” peep x86 Variable Attributes and x86 Type Attributes for the deets. ๐Ÿซถ

The Microsoft structure layout algorithm is honestly pretty simple, except for the bit-field packing part (that's where things get spicy). The padding and alignment of struct members, and whether a bit-field is allowed to straddle a storage-unit boundary, are determined by these rules:

  1. Structure members are stored sequentially in the order in which they are declared: the first member gets the lowest memory address and the last member gets the highest. ๐Ÿ’…
  2. Every data object has an alignment requirement. For all data except structures, unions, and arrays, that alignment requirement is either the size of the object or the current packing size (specified with either the "aligned" attribute or the "pack" pragma) โ€” whichever is less. For structures, unions, and arrays, the alignment requirement is the largest alignment requirement of its members. Every object is allocated an offset so that:
offset % alignment_requirement == 0
  1. Adjacent bit-fields 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 common alignment requirements of the bit-fields. โœจ

Now, MSVC interprets zero-length bit-fields like this:

  1. If a zero-length bit-field is inserted between two bit-fields that are normally coalesced, the bit-fields are not coalesced. ๐Ÿ˜ค

For example:

struct
 {
   unsigned long bf_1 : 12;
   unsigned long : 0;
   unsigned long bf_2 : 12;
 } t1;

The size of "t1" is 8 bytes with the zero-length bit-field. If the zero-length bit-field were removed, "t1"'s size would be 4 bytes.

  1. If a zero-length bit-field is inserted after a bit-field, "foo", and the alignment of the zero-length bit-field is greater than the member that follows it, "bar", then "bar" is aligned as the type of the zero-length bit-field. ๐Ÿ‘‘

For example:

struct
 {
   char foo : 4;
   short : 0;
   char bar;
 } t2;

struct
 {
   char foo : 4;
   short : 0;
   double bar;
 } t3;

For "t2", "bar" is placed at offset 2, rather than offset 1. Accordingly, the size of "t2" is 4. For "t3", the zero-length bit-field does not affect the alignment of "bar" or, as a result, the size of the structure.

Taking this into account, it is important to note the following:

  1. If a zero-length bit-field follows a normal bit-field, the type of the zero-length bit-field may affect the alignment of the structure as a whole. For example, "t2" has a size of 4 bytes, since the zero-length bit-field follows a normal bit-field, and is of type short.
  2. Even if a zero-length bit-field is not followed by a normal bit-field, it may still affect the alignment of the structure:
struct
 {
   char foo : 6;
   long : 0;
 } t4;

Here, "t4" takes up 4 bytes.

  1. Zero-length bit-fields following non-bit-field members are ignored:
struct
 {
   char foo;
   long : 0;
   char bar;
 } t5;

Here, "t5" takes up 2 bytes.


  • -mno-align-stringops โ€” do not align the destination of inlined string operations. This switch reduces code size and improves performance in case the destination is already aligned โ€” but GCC doesn't know about it, so it's just out here guessing. ๐Ÿ˜ญ
  • -minline-all-stringops โ€” by default GCC inlines string operations only when the destination is known to be aligned to at least a 4-byte boundary. This option enables more inlining and increases code size, but may improve performance of code that depends on fast "memcpy" and "memset" for short lengths. It also enables inline expansion of "strlen" for all pointer alignments. ๐Ÿ”ฅ
  • -minline-stringops-dynamically โ€” for string operations of unknown size, use run-time checks with inline code for small blocks and a library call for large blocks. Bestie does a vibe check at runtime, iconic behavior honestly.
  • -mstringop-strategy=alg โ€” override the internal decision heuristic for the particular algorithm to use for inlining string operations. The allowed values for alg are:
    • rep_byte
    • rep_4byte
    • rep_8byte

Expand using i386 "rep" prefix of the specified size.

  • byte_loop
  • loop
  • unrolled_loop

Expand into an inline loop.

  • libcall

Always use a library call.

  • -mmemcpy-strategy=strategy โ€” override the internal decision heuristic to decide if "__builtin_memcpy" should be inlined and what inline algorithm to use when the expected size of the copy operation is known. strategy is a comma-separated list of alg:max_size:dest_align triplets. alg is specified in -mstringop-strategy, max_size specifies the max byte size with which inline algorithm alg is allowed. For the last triplet, the max_size must be -1. The max_size of the triplets in the list must be specified in increasing order. The minimal byte size for alg is 0 for the first triplet and "max_size + 1" of the preceding range. ๐Ÿ“
  • -mmemset-strategy=strategy โ€” the option is similar to -mmemcpy-strategy= except that it is to control "__builtin_memset" expansion.
  • -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. The option -fomit-leaf-frame-pointer removes the frame pointer for leaf functions, which might make debugging harder. ๐Ÿ™ˆ
  • -mtls-direct-seg-refs, -mno-tls-direct-seg-refs โ€” controls whether TLS variables may be accessed with offsets from the TLS segment register (%gs for 32-bit, %fs for 64-bit), or whether the thread base pointer must be added. Whether or not this is valid depends on the operating system, and whether it maps the segment to cover the entire TLS area.

For systems that use the GNU C Library, the default is on.

  • -msse2avx, -mno-sse2avx โ€” specify that the assembler should encode SSE instructions with VEX prefix. The option -mavx turns this on by default. โœจ
  • -mfentry, -mno-fentry โ€” if profiling is active (-pg), put the profiling counter call before the prologue. Note: on x86 architectures the attribute "ms_hook_prologue" isn't possible at the moment for -mfentry and -pg. ๐Ÿ’€
  • -mrecord-mcount, -mno-record-mcount โ€” if profiling is active (-pg), generate a __mcount_loc section that contains pointers to each profiling call. This is useful for automatically patching and out calls.
  • -mnop-mcount, -mno-nop-mcount โ€” if profiling is active (-pg), generate the calls to the profiling functions as NOPs. This is useful when they should be patched in later dynamically. This is likely only useful together with -mrecord-mcount. ๐Ÿงš
  • -minstrument-return=type โ€” instrument function exit in -pg -mfentry instrumented functions with a call to the specified function. This only instruments true returns ending with ret, but not sibling calls ending with jump. Valid *type*s are none to not instrument, call to generate a call to __return__, or nop5 to generate a 5 byte nop.
  • -mrecord-return, -mno-record-return โ€” generate a __return_loc section pointing to all return instrumentation code.
  • -mfentry-name=name โ€” set name of __fentry__ symbol called at function entry for -pg -mfentry functions.
  • -mfentry-section=name โ€” set name of section to record -mrecord-mcount calls (default __mcount_loc).
  • -mskip-rax-setup, -mno-skip-rax-setup โ€” when generating code for the x86-64 architecture with SSE extensions disabled, -mskip-rax-setup can be used to skip setting up RAX register when there are no variable arguments passed in vector registers.
Warning: since the RAX register is used to avoid unnecessarily saving vector registers on the stack when passing variable arguments, the impacts of this option are that callees may waste some stack space, misbehave, or jump to a random location. ๐Ÿ˜ญ GCC 4.4 or newer don't have those issues, regardless of the RAX register value.
  • -m8bit-idiv, -mno-8bit-idiv โ€” on some processors, like Intel Atom, 8-bit unsigned integer divide is much faster than 32-bit/64-bit integer divide. This option generates a run-time check. If both dividend and divisor are within range of 0 to 255, 8-bit unsigned integer divide is used instead of 32-bit/64-bit integer divide. โšก
  • -mavx256-split-unaligned-load, -mavx256-split-unaligned-store โ€” split 32-byte AVX unaligned load and store.
  • -mstack-protector-guard=guard, -mstack-protector-guard-reg=reg, -mstack-protector-guard-offset=offset โ€” generate stack protection code using canary at guard. Supported locations are global for global canary or tls for per-thread canary in the TLS block (the default). This option has effect only when -fstack-protector or -fstack-protector-all is specified. ๐Ÿ›ก๏ธ

With the latter choice the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which segment register (%fs or %gs) to use as base register for reading the canary, and from what offset from that base register. The default for those is as specified in the relevant ABI.

  • -mgeneral-regs-only โ€” generate code that uses only the general-purpose registers. This prevents the compiler from using floating-point, vector, mask and bound registers. No fancy registers for you, only the basics. ๐Ÿ’…
  • -mrelax-cmpxchg-loop โ€” okay so when GCC has to spit out a compare-and-swap loop for __sync Builtins and __atomic Builtins and there's no native instruction to do it in one go, this flag makes it optimize for the highly contended case ๐Ÿ’… it issues an atomic load before the CMPXCHG instruction, and uses the PAUSE instruction to save CPU power when restarting the loop. very "be polite to the other threads" of it, we love to see it ๐Ÿซถ
  • -mindirect-branch=choice โ€” converts indirect calls and jumps according to choice. here's the menu, bestie:
    • the default is keep, which keeps indirect call and jump unmodified (iconic "if it ain't broke" energy โœจ)
    • 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. literally cannot be reached, it's giving lost in the address space ๐Ÿ˜ญ
note that -mindirect-branch=thunk-extern is compatible with -fcf-protection=branch since the external thunk can be made to enable control-flow check. slay, they coexist ๐Ÿ’–
  • -mfunction-return=choice โ€” same deal but for function returns, converted according to choice:
    • the default is keep, which keeps function return unmodified
    • thunk converts function return to call and return thunk
    • thunk-inline converts function return to inlined call and return thunk
    • thunk-extern converts function return to external call and return thunk provided in a separate object file

you can control this behavior for a specific function by using the function attribute function_return ๐ŸŒธ

note that -mindirect-return=thunk-extern is compatible with -fcf-protection=branch since the external thunk can be made to enable control-flow check.
note that -mcmodel=large is incompatible with -mfunction-return=thunk and -mfunction-return=thunk-extern since the thunk function may not be reachable in the large code model. same problem as above, the thunk is just too far away ๐Ÿฅฒ
  • -mindirect-branch-register โ€” forces indirect call and jump via register. simple as that, no notes ๐Ÿ’…
  • -mharden-sls=choice โ€” generates code to mitigate against straight line speculation (SLS) with choice. the options:
    • 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 โญ

  • -mindirect-branch-cs-prefix โ€” adds a CS prefix to call and jmp to indirect thunk with branch target in r8-r15 registers so that the call and jmp instruction length is 6 bytes to allow them to be replaced with lfence; call *%r8-r15 or lfence; jmp *%r8-r15 at run-time. tiny byte-level glow-up, we respect it ๐Ÿงš

these -m switches are supported in addition to the above on x86-64 processors in 64-bit environments.

  • -m32, -m64, -mx32, -m16, -miamcu โ€” generate code for a 16-bit, 32-bit or 64-bit environment. the full tea โ˜•:
    • -m32 sets int, long, and pointer types to 32 bits, and generates code that runs in 32-bit mode.
    • -m64 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. (Darwin main character behaviour, honestly ๐Ÿ“)
    • -mx32 sets int, long, and pointer types to 32 bits, and generates code for the x86-64 architecture.
    • -m16 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.
    • -miamcu generates code which conforms to Intel MCU psABI. it requires the -m32 option to be turned on. no -m32, no deal ๐Ÿ”ฅ
  • -mno-red-zone โ€” do not use a so-called "red zone" for x86-64 code. ok so 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. ๐Ÿšซ very "not in my house" of the compiler
  • -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 ๐Ÿ’–
  • -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. yes has to, it's mandatory bestie ๐Ÿ‘‘
  • -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. it's giving "there are levels to this" ๐ŸŒˆ
  • -mcmodel=large โ€” generate code for the large model. this model makes no assumptions about addresses and sizes of sections. zero assumptions, pure chaos, we love a free spirit ๐Ÿฆ‹
  • -maddress-mode=long โ€” generate code for long address mode. this is only supported for 64-bit and x32 environments. it is the default address mode for 64-bit environments โญ
  • -maddress-mode=short โ€” generate code for short address mode. this is only supported for 32-bit and x32 environments. it is the default address mode for 32-bit and x32 environments ๐ŸŽ€
  • -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. a little note-to-self baked into the binary ๐Ÿซถ
  • -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 a real one, do not ignore the warning, it will not be cute
  • -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. the way that GCC respects your boundaries ๐Ÿ˜Œ๐Ÿ’œ
  • -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. so many bits, so much metadata โœจ

๐ŸชŸ x86 Windows Options

these additional options are available for Microsoft Windows targets:

  • -mconsole โ€” specifies that a console application is to be generated, by instructing the linker to set the PE header subsystem type 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. "pretend you didn't see it" energy ๐Ÿ™ˆ
  • -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. yes bestie, we're going Unicode ๐ŸŒˆ
  • -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 only, no commitment ๐Ÿ’€
  • -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, as there the User32 API, which is used to set executable privileges, isn't available. no User32, no problem ๐ŸŒธ
  • -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. shoutout to the old runtimes ๐Ÿซก
  • -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 option, and honestly? clean, minimal, iconic ๐ŸŽ€

๐ŸŒช๏ธ Xtensa Options

these options are supported for Xtensa targets:

  • -mconst16, -mno-const16 โ€” enable or disable use of CONST16 instructions for loading constant values. the CONST16 instruction is currently not a standard option from Tensilica. when enabled, CONST16 instructions are always used in place of the standard L32R instructions. the use of CONST16 is enabled by default only if the L32R instruction is not available. always in place of, not sometimes, always โ€” worth knowing fr fr ๐Ÿ”ฅ
  • -mfused-madd, -mno-fused-madd โ€” turns fused multiply/add and multiply/subtract instructions on or off for the floating-point option. ๐Ÿ’… Heads up: this does nothing if the floating-point option isn't also enabled, so don't come crying to me. Disabling fused multiply/add and multiply/subtract instructions forces the compiler to use separate instructions for the multiply and the add/subtract. That's lowkey desirable in some cases where you need strictly IEEE 754-compliant results: the fused multiply add/subtract instructions don't round the intermediate result, so you get results with more bits of precision than the IEEE standard specifies. ๐Ÿ˜ญ Disabling them also guarantees your program's output isn't sensitive to the compiler's ability to combine multiply and add/subtract operations. no cap.
  • -mserialize-volatile, -mno-serialize-volatile โ€” when this is enabled, GCC inserts MEMW instructions before volatile memory references to guarantee sequential consistency. โœจ The default is -mserialize-volatile. Use -mno-serialize-volatile to omit the MEMW instructions. that's it, that's the whole vibe.
  • -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. ๐Ÿงš kernel girlies stay winning.
  • -mtext-section-literals, -mno-text-section-literals โ€” these control the treatment of literal pools. ๐ŸŽ€ The default is -mno-text-section-literals, which places literals in a separate section in the output file. This lets the literal pool live in a data RAM/ROM, and it also lets the linker combine literal pools from separate object files to remove redundant literals and improve code size. With -mtext-section-literals, the literals are interspersed in the text section so they stay 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 โ€” also about literal pool treatment, bestie, don't get them twisted. The default is -mno-auto-litpools, which places literals in a separate section in the output file unless -mtext-section-literals is used. With -mauto-litpools the literals are interspersed in the text section by the assembler. The compiler does not produce explicit .literal directives and loads literals into registers with MOVI instructions instead of L32R, so the assembler can do relaxation and place literals as necessary. This option lets the assembler 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 tells the assembler to automatically align instructions to reduce branch penalties, at the expense of some code density. The assembler tries to widen density instructions to align branch targets and the instructions following call instructions. ๐Ÿฆ‹ If there aren't enough preceding safe density instructions to align a target, no widening happens โ€” no forcing, no drama. The default is -mtarget-align. These options do not affect the treatment of auto-aligned instructions like LOOP, which the assembler always aligns, either by widening density instructions or by inserting NOP instructions. ๐Ÿ’€
  • -mlongcalls, -mno-longcalls โ€” when enabled, GCC tells the assembler to translate direct calls into indirect calls, unless it can determine that the target of a direct call is in the range allowed by the call instruction. This translation typically happens for calls to functions in other source files. Specifically, the assembler translates a direct CALL instruction into an L32R followed by a CALLX instruction. ๐ŸŒˆ The default is -mno-longcalls. Use this in programs where the call target can potentially be out of range. Lowkey important detail: 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. ๐Ÿ‘€ Also note 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 and 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 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. โฑ๏ธ When optimizing for speed, this affects whether a constant gets loaded from the literal pool using L32R or synthesized from a small one with a couple of arithmetic instructions. The default value is 0. iykyk.

๐Ÿฆ‹ zSeries Options ๐Ÿฆ‹

These are listed under

๐ŸŒธ ENVIRONMENT ๐ŸŒธ

Okay bestie, this section is all about the env vars that lowkey run the whole show behind the scenes. Some of them work by handing GCC directories or prefixes to go dig around in when it's hunting for files. Others are vibes-only: they configure how the compilation environment behaves.

Heads up: you can also just tell GCC where to look with options like -B, -I and -L. Those win over the environment variables, and the environment variables in turn win over whatever GCC's configuration says. Priority chain, periodt.

๐Ÿ’… LANG, LC_CTYPE, LC_MESSAGES, LC_ALL

These four control how GCC uses localization info, which is the whole reason it can roll with different national conventions. GCC peeks at the LC_CTYPE and LC_MESSAGES locale categories if it was configured to do so. You can set those categories to literally any value your install supports. A classic value is en_GB.UTF-8 โ€” English, United Kingdom, encoded in UTF-8. Slay.

  • LC_CTYPE โ€” this one specifies character classification. GCC uses it to figure out the character boundaries in a string, which you genuinely need for some multibyte encodings that contain quote and escape characters that would otherwise get read as "string ends here" or "escape time." ๐Ÿ˜ญ
  • LC_MESSAGES โ€” this one picks the language for diagnostic messages. (Yes, your errors can be multilingual. Iconic.)
  • LC_ALL โ€” if it's set, it overrides both LC_CTYPE and LC_MESSAGES. If it's not set, those two default to the value of LANG. And if none of these are set at all? GCC defaults to traditional C English behavior. Very "we tried nothing and we're all out of ideas," but make it valid.

๐Ÿซถ TMPDIR

If TMPDIR is set, it names the directory used for temporary files. GCC needs temp files to hold the output of one compilation stage while it feeds it into the next stage โ€” like, the preprocessor's output becomes the input to the compiler proper. Pipeline realness. โœจ

๐ŸŽ€ GCC_COMPARE_DEBUG

Setting GCC_COMPARE_DEBUG is nearly equivalent to passing -fcompare-debug to the compiler driver. Go read that option's docs for the deets โ€” she's got lore.

๐Ÿ’œ GCC_EXEC_PREFIX

If GCC_EXEC_PREFIX is set, it gives a prefix to stick onto the names of the subprograms the compiler executes. Note: no slash gets added when the prefix is combined with a subprogram name โ€” but you're absolutely free to specify a prefix that already ends in a slash if that's your vibe.

If GCC_EXEC_PREFIX isn't set, GCC tries to work out a sensible prefix from the pathname it was invoked with. And if it can't find the subprogram using your specified prefix, it goes looking in the usual places instead. Fallback queen. ๐Ÿ’…

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" from when you ran the configure script.

Other prefixes given with -B take precedence over this one.

This prefix is also used for finding files like crt0.o that get used for linking. And plot twist โ€” it's used in a genuinely unusual way when finding the directories to search for header files. For each of the standard directories whose name normally begins with /usr/local/lib/gcc (more precisely, with the value of GCC_INCLUDE_DIR), GCC tries swapping that beginning for the specified prefix to produce 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 that prefix value gets replaced by GCC_EXEC_PREFIX when looking for header files. Messy? Yes. Documented? Also yes. ๐Ÿ˜ญ

๐Ÿฆ‹ COMPILER_PATH

The value of COMPILER_PATH is a colon-separated list of directories, much like PATH. GCC tries those directories when searching for subprograms โ€” but only if it couldn't find them using GCC_EXEC_PREFIX. Backup plan energy.

๐ŸŒˆ LIBRARY_PATH

The value of LIBRARY_PATH is also a colon-separated list of directories, much like PATH. When GCC is configured as a native compiler, it tries those directories when searching for special linker files, if it can't find them via GCC_EXEC_PREFIX. Linking with GCC also uses these directories when searching for ordinary libraries for the -l option โ€” but directories given with -L come first. No cutting the line, bestie.

๐Ÿ“ LANG (yes, again โ€” she does double duty)

This variable passes locale info to the compiler. One way that info gets used: determining the character set for parsing character literals, string literals and comments in C and C++. When the compiler is configured to allow multibyte characters, these LANG values are recognized:

  • C-JIS โ€” recognize JIS characters.
  • C-SJIS โ€” recognize SJIS characters.
  • C-EUCJP โ€” recognize EUCJP characters.

If LANG isn't defined, or it has some other value, then the compiler uses "mblen" and "mbtowc" as defined by the default locale to recognize and translate multibyte characters. Default behavior, we love her.

โญ GCC_EXTRA_DIAGNOSTIC_OUTPUT

If GCC_EXTRA_DIAGNOSTIC_OUTPUT is set to one of the values below, then extra text gets emitted to stderr whenever fix-it hints are emitted. But watch out: -fdiagnostics-parseable-fixits and -fno-diagnostics-parseable-fixits take precedence over this environment variable. Options stay winning. ๐Ÿ‘‘

  • fixits-v1 โ€” emit parseable fix-it hints, equivalent to -fdiagnostics-parseable-fixits. In particular, columns are expressed as a count of bytes, starting at byte 1 for the initial column.
  • fixits-v2 โ€” same as fixits-v1, but columns are expressed as display columns, as per -fdiagnostics-column-unit=display.

Some additional environment variables affect the behavior of the preprocessor. Yes, there's more. Buckle up. ๐Ÿงš

๐Ÿ’– CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH, OBJC_INCLUDE_PATH

Each variable's value is a list of directories separated by a special character, much like PATH, where the preprocessor goes looking for header files. That special character, "PATH_SEPARATOR", is target-dependent and decided at GCC build time. For Microsoft Windows-based targets it's a semicolon, and for almost literally every other target it's a colon.

  • CPATH โ€” a list of directories searched as if given with -I, but after any paths from -I options on the command line. This one is used no matter which language is being preprocessed.
  • The remaining three apply only when preprocessing the particular language they name. Each specifies a list of directories searched as if given with -isystem, but after any paths from -isystem options on the command line.

In all of these variables, an empty element tells the compiler to search its current working directory. Empty elements can show up at the beginning or the end of a path. For instance, if CPATH is ":/special/include", that hits exactly the same as -I. -I/special/include. Sneaky but valid. ๐Ÿ™ˆ

๐ŸŒธ DEPENDENCIES_OUTPUT

If this variable 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. Not invited to the party.

The value of DEPENDENCIES_OUTPUT can be just a file name โ€” in which case the Make rules get written to that file, with the target name guessed from the source file name. Or the value can be in the form file target, in which case the rules get written to file using target as the target name.

In other words, this env var is equivalent to combining the options -MM and -MF, plus an optional -MT switch if you're feeling extra. ๐Ÿ’…

๐ŸŽ€ SUNPRO_DEPENDENCIES

Same as DEPENDENCIES_OUTPUT (see above), except system header files are not ignored, so it implies -M rather than -MM. However, the dependence on the main input file is omitted. Different flavor, same family.

๐Ÿ”ฅ SOURCE_DATE_EPOCH

If this variable is 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. Reproducible builds girlies, this one's for you. โœจ

The value of SOURCE_DATE_EPOCH must be a UNIX timestamp, defined as the number of seconds (leap seconds excluded) since 01 Jan 1970 00:00:00, represented in ASCII. Identical to the output of date +%s on GNU/Linux and other systems that support the %s extension in the date command.

The value should be a known timestamp, like the last modification time of the source or the package, and it should be set by the build process. Don't just make one up, bestie. ๐Ÿ˜ญ


๐Ÿ’€ BUGS ๐Ÿ’€

For instructions on how to report bugs, go look at <https://bugs.opensuse.org/>. They're waiting for your findings.


๐Ÿงš FOOTNOTES ๐Ÿงš

  1. On some systems, gcc -shared needs to build supplementary stub code for constructors to actually 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 supplying them when they aren't necessary is innocuous (harmless, no drama). Also, -shared suppresses the addition of startup code that alters the floating-point environment, as done with -ffast-math, -Ofast or -funsafe-math-optimizations on some targets. Noted, logged, memorized. ๐Ÿ‘‘

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


๐Ÿ’œ AUTHOR ๐Ÿ’œ

See the Info entry for gcc, or <https://gcc.gnu.org/onlinedocs/gcc/Contributors.html>, for the contributors to GCC. Every single one of them. Main characters, all of them.


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 the whole page, bestie โ€” we made it to the end of all 122 parts! ๐ŸŽ‰ This one's gcc-13, dated 2026-09-10, and honestly she ate. Go forth and compile something iconic. ๐Ÿ’…โœจ