GCC(1) GNU GCC(1)

gcc - GNU project C and C++ compiler

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.

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

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

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

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

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

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

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

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

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

-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
-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
-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-immediate-escalation -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 -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-elaborated-enum-base -Wno-exceptions -Wextra-semi -Wno-global-module -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-template-id-cdtor -Wno-terminate -Wno-vexing-parse -Wvirtual-inheritance -Wno-virtual-move-assign -Wvolatile -Wzero-as-null-pointer-constant
-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
-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-json-formatting -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] -fdiagnostics-text-art-charset=[none|ascii|unicode|emoji]
-fsyntax-only -fmax-errors=n -Wpedantic -pedantic-errors -fpermissive -w -Wextra -Wall -Wabi=n -Waddress -Wno-address-of-packed-member -Waggregate-return -Walloc-size -Walloc-size-larger-than=byte-size -Walloc-zero -Walloca -Walloca-larger-than=byte-size -Wno-aggressive-loop-optimizations -Warith-conversion -Warray-bounds -Warray-bounds=n -Warray-compare -Warray-parameter -Warray-parameter=n -Wno-attributes -Wattribute-alias=n -Wno-attribute-alias -Wno-attribute-warning -Wbidi-chars=[none|unpaired|any|ucn] -Wbool-compare -Wbool-operation -Wno-builtin-declaration-mismatch -Wno-builtin-macro-redefined -Wc90-c99-compat -Wc99-c11-compat -Wc11-c23-compat -Wc++-compat -Wc++11-compat -Wc++14-compat -Wc++17-compat -Wc++20-compat -Wno-c++11-extensions -Wno-c++14-extensions -Wno-c++17-extensions -Wno-c++20-extensions -Wno-c++23-extensions -Wcalloc-transposed-args -Wcast-align -Wcast-align=strict -Wcast-function-type -Wcast-qual -Wchar-subscripts -Wclobbered -Wcomment -Wcompare-distinct-pointer-types -Wno-complain-wrong-lang -Wconversion -Wno-coverage-mismatch -Wno-cpp -Wdangling-else -Wdangling-pointer -Wdangling-pointer=n -Wdate-time -Wno-deprecated -Wno-deprecated-declarations -Wno-designated-init -Wdisabled-optimization -Wno-discarded-array-qualifiers -Wno-discarded-qualifiers -Wno-div-by-zero -Wdouble-promotion -Wduplicated-branches -Wduplicated-cond -Wempty-body -Wno-endif-labels -Wenum-compare -Wenum-conversion -Wenum-int-mismatch -Werror -Werror=* -Wexpansion-to-defined -Wfatal-errors -Wflex-array-member-not-at-end -Wfloat-conversion -Wfloat-equal -Wformat -Wformat=2 -Wno-format-contains-nul -Wno-format-extra-args -Wformat-nonliteral -Wformat-overflow=n -Wformat-security -Wformat-signedness -Wformat-truncation=n -Wformat-y2k -Wframe-address -Wframe-larger-than=byte-size -Wno-free-nonheap-object -Wno-if-not-aligned -Wno-ignored-attributes -Wignored-qualifiers -Wno-incompatible-pointer-types -Whardened -Wimplicit -Wimplicit-fallthrough -Wimplicit-fallthrough=n -Wno-implicit-function-declaration -Wno-implicit-int -Winfinite-recursion -Winit-self -Winline -Wno-int-conversion -Wint-in-bool-context -Wno-int-to-pointer-cast -Wno-invalid-memory-model -Winvalid-pch -Winvalid-utf8 -Wno-unicode -Wjump-misses-init -Wlarger-than=byte-size -Wlogical-not-parentheses -Wlogical-op -Wlong-long -Wno-lto-type-mismatch -Wmain -Wmaybe-uninitialized -Wmemset-elt-size -Wmemset-transposed-args -Wmisleading-indentation -Wmissing-attributes -Wmissing-braces -Wmissing-field-initializers -Wmissing-format-attribute -Wmissing-include-dirs -Wmissing-noreturn -Wno-missing-profile -Wno-multichar -Wmultistatement-macros -Wnonnull -Wnonnull-compare -Wnormalized=[none|id|nfc|nfkc] -Wnull-dereference -Wno-odr -Wopenacc-parallelism -Wopenmp -Wopenmp-simd -Wno-overflow -Woverlength-strings -Wno-override-init-side-effects -Wpacked -Wno-packed-bitfield-compat -Wpacked-not-aligned -Wpadded -Wparentheses -Wno-pedantic-ms-format -Wpointer-arith -Wno-pointer-compare -Wno-pointer-to-int-cast -Wno-pragmas -Wno-prio-ctor-dtor -Wredundant-decls -Wrestrict -Wno-return-local-addr -Wreturn-type -Wno-scalar-storage-order -Wsequence-point -Wshadow -Wshadow=global -Wshadow=local -Wshadow=compatible-local -Wno-shadow-ivar -Wno-shift-count-negative -Wno-shift-count-overflow -Wshift-negative-value -Wno-shift-overflow -Wshift-overflow=n -Wsign-compare -Wsign-conversion -Wno-sizeof-array-argument -Wsizeof-array-div -Wsizeof-pointer-div -Wsizeof-pointer-memaccess -Wstack-protector -Wstack-usage=byte-size -Wstrict-aliasing -Wstrict-aliasing=n -Wstrict-overflow -Wstrict-overflow=n -Wstring-compare -Wno-stringop-overflow -Wno-stringop-overread -Wno-stringop-truncation -Wstrict-flex-arrays -Wsuggest-attribute=[pure|const|noreturn|format|malloc] -Wswitch -Wno-switch-bool -Wswitch-default -Wswitch-enum -Wno-switch-outside-range -Wno-switch-unreachable -Wsync-nand -Wsystem-headers -Wtautological-compare -Wtrampolines -Wtrigraphs -Wtrivial-auto-var-init -Wno-tsan -Wtype-limits -Wundef -Wuninitialized -Wunknown-pragmas -Wunsuffixed-float-constants -Wunused -Wunused-but-set-parameter -Wunused-but-set-variable -Wunused-const-variable -Wunused-const-variable=n -Wunused-function -Wunused-label -Wunused-local-typedefs -Wunused-macros -Wunused-parameter -Wno-unused-result -Wunused-value -Wunused-variable -Wuse-after-free -Wuse-after-free=n -Wuseless-cast -Wno-varargs -Wvariadic-macros -Wvector-operation-performance -Wvla -Wvla-larger-than=byte-size -Wno-vla-larger-than -Wvolatile-register-var -Wwrite-strings -Wno-xor-used-as-pow -Wzero-length-bounds
-fanalyzer -fanalyzer-call-summaries -fanalyzer-checker=name -fno-analyzer-feasibility -fanalyzer-fine-grained -fanalyzer-show-events-in-system-headers -fno-analyzer-state-merge -fno-analyzer-state-purge -fno-analyzer-suppress-followups -fanalyzer-transitivity -fno-analyzer-undo-inlining -fanalyzer-verbose-edges -fanalyzer-verbose-state-changes -fanalyzer-verbosity=level -fdump-analyzer -fdump-analyzer-callgraph -fdump-analyzer-exploded-graph -fdump-analyzer-exploded-nodes -fdump-analyzer-exploded-nodes-2 -fdump-analyzer-exploded-nodes-3 -fdump-analyzer-exploded-paths -fdump-analyzer-feasibility -fdump-analyzer-infinite-loop -fdump-analyzer-json -fdump-analyzer-state-purge -fdump-analyzer-stderr -fdump-analyzer-supergraph -fdump-analyzer-untracked -Wno-analyzer-double-fclose -Wno-analyzer-double-free -Wno-analyzer-exposure-through-output-file -Wno-analyzer-exposure-through-uninit-copy -Wno-analyzer-fd-access-mode-mismatch -Wno-analyzer-fd-double-close -Wno-analyzer-fd-leak -Wno-analyzer-fd-phase-mismatch -Wno-analyzer-fd-type-mismatch -Wno-analyzer-fd-use-after-close -Wno-analyzer-fd-use-without-check -Wno-analyzer-file-leak -Wno-analyzer-free-of-non-heap -Wno-analyzer-imprecise-fp-arithmetic -Wno-analyzer-infinite-loop -Wno-analyzer-infinite-recursion -Wno-analyzer-jump-through-null -Wno-analyzer-malloc-leak -Wno-analyzer-mismatching-deallocation -Wno-analyzer-null-argument -Wno-analyzer-null-dereference -Wno-analyzer-out-of-bounds -Wno-analyzer-overlapping-buffers -Wno-analyzer-possible-null-argument -Wno-analyzer-possible-null-dereference -Wno-analyzer-putenv-of-auto-var -Wno-analyzer-shift-count-negative -Wno-analyzer-shift-count-overflow -Wno-analyzer-stale-setjmp-buffer -Wno-analyzer-tainted-allocation-size -Wno-analyzer-tainted-assertion -Wno-analyzer-tainted-array-index -Wno-analyzer-tainted-divisor -Wno-analyzer-tainted-offset -Wno-analyzer-tainted-size -Wanalyzer-symbol-too-complex -Wanalyzer-too-complex -Wno-analyzer-undefined-behavior-strtok -Wno-analyzer-unsafe-call-within-signal-handler -Wno-analyzer-use-after-free -Wno-analyzer-use-of-pointer-in-stale-stack-frame -Wno-analyzer-use-of-uninitialized-value -Wno-analyzer-va-arg-type-mismatch -Wno-analyzer-va-list-exhausted -Wno-analyzer-va-list-leak -Wno-analyzer-va-list-use-after-va-end -Wno-analyzer-write-to-const -Wno-analyzer-write-to-string-literal
-Wbad-function-cast -Wmissing-declarations -Wmissing-parameter-type -Wdeclaration-missing-parameter-type -Wmissing-prototypes -Wmissing-variable-declarations -Wnested-externs -Wold-style-declaration -Wold-style-definition -Wstrict-prototypes -Wtraditional -Wtraditional-conversion -Wdeclaration-after-statement -Wpointer-sign
-g -glevel -gdwarf -gdwarf-version -gbtf -gctf -gctflevel -ggdb -grecord-gcc-switches -gno-record-gcc-switches -gstrict-dwarf -gno-strict-dwarf -gas-loc-support -gno-as-loc-support -gas-locview-support -gno-as-locview-support -gcodeview -gcolumn-info -gno-column-info -gdwarf32 -gdwarf64 -gstatement-frontiers -gno-statement-frontiers -gvariable-location-views -gno-variable-location-views -ginternal-reset-location-views -gno-internal-reset-location-views -ginline-points -gno-inline-points -gvms -gz[=type] -gsplit-dwarf -gdescribe-dies -gno-describe-dies -fdebug-prefix-map=old=new -fdebug-types-section -fno-eliminate-unused-debug-types -femit-struct-debug-baseonly -femit-struct-debug-reduced -femit-struct-debug-detailed[=spec-list] -fno-eliminate-unused-debug-symbols -femit-class-debug-always -fno-merge-debug-strings -fno-dwarf2-cfi-asm -fvar-tracking -fvar-tracking-assignments
-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 -ffold-mem-offsets -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-stringops[=fn] -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
-p -pg -fprofile-arcs --coverage -ftest-coverage -fcondition-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 -fhardened -fharden-control-flow-redundancy -fhardcfr-skip-leaf -fhardcfr-check-exceptions -fhardcfr-check-returning-calls -fhardcfr-check-noreturn-calls=[always|no-xthrow|nothrow|never] -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 -fstrub=disable -fstrub=strict -fstrub=relaxed -fstrub=all -fstrub=at-calls -fstrub=internal -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 -fpatchable-function-entry=N[,M]
-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
-Wa,option -Xassembler option
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
-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
-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 -ftrampoline-impl=[stack|heap] -ftrapv -fwrapv -fvisibility=[default|internal|hidden|protected] -fstrict-volatile-bitfields -fsync-libcalls
-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]
AArch64 Options -mabi=name -mbig-endian -mlittle-endian -mgeneral-regs-only -mcmodel=tiny -mcmodel=small -mcmodel=large -mstrict-align -mno-strict-align -momit-leaf-frame-pointer -mtls-dialect=desc -mtls-dialect=traditional -mtls-size=size -mfix-cortex-a53-835769 -mfix-cortex-a53-843419 -mlow-precision-recip-sqrt -mlow-precision-sqrt -mlow-precision-div -mpc-relative-literal-loads -msign-return-address=scope -mbranch-protection=none|standard|pac-ret[+leaf +b-key]|bti -mharden-sls=opts -march=name -mcpu=name -mtune=name -moverride=string -mverbose-cost-dump -mstack-protector-guard=guard -mstack-protector-guard-reg=sysreg -mstack-protector-guard-offset=offset -mtrack-speculation -moutline-atomics -mearly-ldp-fusion -mlate-ldp-fusion

Adapteva Epiphany Options -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 -march=gpu -mtune=gpu -mstack-size=bytes

ARC Options -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 -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 -mmcu=mcu -mabsdata -maccumulate-args -mbranch-cost=cost -mfuse-add=level -mcall-prologues -mgas-isr-prologues -mint8 -mflmap -mdouble=bits -mlong-double=bits -mn_flash=size -mno-interrupts -mmain-is-OS_task -mrelax -mrmw -mstrict-X -mtiny-stack -mrodata-in-ram -mfract-convert-truncate -mshort-calls -mskip-bug -nodevicelib -nodevicespecs -Waddr-space-convert -Wmisspelled-isr

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

C6X Options -mbig-endian -mlittle-endian -march=cpu -msim -msdata=sdata-type

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

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

Darwin Options -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 -nodefaultrpaths -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 -mno-fp-regs -msoft-float -mieee -mieee-with-inexact -mieee-conformant -mfp-trap-mode=mode -mfp-rounding-mode=mode -mtrap-precision=mode -mbuild-constants -mcpu=cpu-type -mtune=cpu-type -mbwx -mmax -mfix -mcix -mfloat-vax -mfloat-ieee -mexplicit-relocs -msmall-data -mlarge-data -msmall-text -mlarge-text -mmemory-latency=time

eBPF Options -mbig-endian -mlittle-endian -mframe-limit=bytes -mxbpf -mco-re -mno-co-re -mjmpext -mjmp32 -malu32 -mv3-atomics -mbswap -msdiv -msmov -mcpu=version -masm=dialect -minline-memops-threshold=bytes

FR30 Options -msmall-model -mno-lsim

FT32 Options -msim -mlra -mnodiv -mft32b -mcompress -mnopm

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

GNU/Linux Options -mglibc -muclibc -mmusl -mbionic -mandroid -tno-android-cc -tno-android-ld

H8/300 Options -mrelax -mh -ms -mn -mexr -mno-exr -mint32 -malign-300

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

LM32 Options -mbarrel-shift-enabled -mdivide-enabled -mmultiply-enabled -msign-extend-enabled -muser-enabled

LoongArch Options -march=arch-type -mtune=tune-type -mabi=base-abi-type -mfpu=fpu-type -msimd=simd-type -msoft-float -msingle-float -mdouble-float -mlsx -mno-lsx -mlasx -mno-lasx -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=style -mexplicit-relocs -mno-explicit-relocs -mdirect-extern-access -mno-direct-extern-access -mcmodel=code-model -mrelax -mpass-mrelax-to-as -mrecip -mrecip=opt -mfrecipe -mno-frecipe -mdiv32 -mno-div32 -mlam-bh -mno-lam-bh -mlamcas -mno-lamcas -mld-seq-sa -mno-ld-seq-sa -mtls-dialect=opt

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

M32C Options -mcpu=cpu -msim -memregs=number

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

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

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 -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 -mexplicit-relocs=release -mcheck-zero-division -mno-check-zero-division -mdivide-traps -mdivide-breaks -mload-store-pairs -mno-load-store-pairs -mstrict-align -mno-strict-align -mno-unaligned-access -munaligned-access -mmemcpy -mno-memcpy -mlong-calls -mno-long-calls -mmad -mno-mad -mimadd -mno-imadd -mfused-madd -mno-fused-madd -nocpp -mfix-24k -mno-fix-24k -mfix-r4000 -mno-fix-r4000 -mfix-r4400 -mno-fix-r4400 -mfix-r5900 -mno-fix-r5900 -mfix-r10000 -mno-fix-r10000 -mfix-rm7000 -mno-fix-rm7000 -mfix-vr4120 -mno-fix-vr4120 -mfix-vr4130 -mno-fix-vr4130 -mfix-sb1 -mno-fix-sb1 -mflush-func=func -mno-flush-func -mbranch-cost=num -mbranch-likely -mno-branch-likely -mcompact-branches=policy -mfp-exceptions -mno-fp-exceptions -mvr4130-align -mno-vr4130-align -msynci -mno-synci -mlxc1-sxc1 -mno-lxc1-sxc1 -mmadd4 -mno-madd4 -mrelax-pic-calls -mno-relax-pic-calls -mmcount-ra-address -mframe-header-opt -mno-frame-header-opt

MMIX Options -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 -meb -mel -mmul.x -mno-crt0

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

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

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

Nvidia PTX Options -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.

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

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

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

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

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

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

Solaris 2 Options -mclear-hwcap -mno-clear-hwcap -mimpure-text -mno-impure-text -pthreads

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

System V Options -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 -msmp -non-static -Bstatic -Bdynamic -Xbind-lazy -Xbind-now

x86 Options -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 -mpartial-vector-fp-math -mmove-max=bits -mstore-max=bits -mnoreturn-no-callee-saved-registers -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 -mavxvnniint16 -msm3 -msha512 -msm4 -mapxf -musermsr -mavx10.1 -mavx10.1-256 -mavx10.1-512 -mevex512 -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 -mcrtdll=library -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 -mstrict-align -mno-strict-align

zSeries Options See S/390 and zSeries Options.

Compilation can involve up to four stages: preprocessing, compilation proper, assembly and linking, always in that order. GCC is capable of preprocessing and compiling 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 (those newly compiled, and those specified as input) into an executable file.

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

C source code that must be preprocessed.
C source code that should not be preprocessed.
C++ source code that should not be preprocessed.
Objective-C source code. Note that you must link with the libobjc library to make an Objective-C program work.
Objective-C source code that should not be preprocessed.
Objective-C++ source code. Note that you must link with the libobjc library to make an Objective-C++ program work. Note that .M refers to a literal capital M.
Objective-C++ source code that should not be preprocessed.
C, C++, Objective-C or Objective-C++ header file to be turned into a precompiled header (default), or C, C++ header file to be turned into an Ada spec (via the -fdump-ada-spec switch).
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.
Objective-C++ source code that must be preprocessed.
Objective-C++ source code that should not be preprocessed.
C++ header file to be turned into a precompiled header or Ada spec.
Fixed form Fortran source code that should not be preprocessed.
Fixed form Fortran source code that must be preprocessed (with the traditional preprocessor).
Free form Fortran source code that should not be preprocessed.
Free form Fortran source code that must be preprocessed (with the traditional preprocessor).
Go source code.
D source code.
D interface file.
D documentation code (Ddoc).
Ada source code file that contains a library unit declaration (a declaration of a package, subprogram, or generic, or a generic instantiation), or a library unit renaming declaration (a package, generic, or subprogram renaming declaration). Such files are also called specs.
Ada source code file containing a library unit body (a subprogram or package body). Such files are also called bodies.
Assembler code.
Assembler code that must be preprocessed.
An object file to be fed straight into linking. Any file name with no recognized suffix is treated this way.

You can specify the input language explicitly with the -x option:

Specify explicitly the language for the following input files (rather than letting the compiler choose a default based on the file name suffix). This option applies to all following input files until the next -x option. Possible values for language are:
c  c-header  cpp-output
c++  c++-header  c++-system-header c++-user-header c++-cpp-output
objective-c  objective-c-header  objective-c-cpp-output
objective-c++ objective-c++-header objective-c++-cpp-output
assembler  assembler-with-cpp
ada
d
f77  f77-cpp-input f95  f95-cpp-input
go
Turn off any specification of a language, so that subsequent files are handled according to their file name suffixes (as they are if -x has not been used at all).

If you only want some of the stages of compilation, you can use -x (or filename suffixes) to tell gcc where to start, and one of the options -c, -S, or -E to say where gcc is to stop. Note that some combinations (for example, -x cpp-output -E) instruct gcc to do nothing at all.

-c
Compile or assemble the source files, but do not link. The linking stage simply is not done. The ultimate output is in the form of an object file for each source file.

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

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

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.

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.

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.

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

-v
Print (on standard error output) the commands executed to run the stages of compilation. Also print the version number of the compiler driver program and of the preprocessor and the compiler proper.
-###
Like -v except the commands are not executed and arguments are quoted unless they contain only alphanumeric characters or "./-_". This is useful for shell scripts to capture the driver-generated command lines.
Print (on the standard output) a description of the command-line options understood by gcc. If the -v option is also specified then --help is also passed on to the various processes invoked by gcc, so that they can display the command-line options they accept. If the -Wextra option has also been specified (prior to the --help option), then command-line options that have no documentation associated with them are also displayed.
Print (on the standard output) a description of target-specific command-line options for each tool. For some targets extra target-specific information may also be printed.
Print (on the standard output) a description of the command-line options understood by the compiler that fit into all specified classes and qualifiers. These are the supported classes:
Display all of the optimization options supported by the compiler.
Display all of the options controlling warning messages produced by the compiler.
Display target-specific options. Unlike the --target-help option however, target-specific options of the linker and assembler are not displayed. This is because those tools do not currently support the extended --help= syntax.
Display the values recognized by the --param option.
Display the options supported for language, where language is the name of one of the languages supported in this version of GCC. If an option is supported by all languages, one needs to select common class.
Display the options that are common to all languages.

These are the supported qualifiers:

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

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

--help=target,undocumented

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

--help=warnings,^joined,^undocumented

The argument to --help= should not consist solely of inverted qualifiers.

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

--help=target,optimizers

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

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

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

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

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

-Q -O2 --help=optimizers

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

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

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

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

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

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

However, the use of gcc does not add the C++ library. g++ is a program that calls GCC and automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files unless -x is used. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations. On many systems, g++ is also installed with the name c++.

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

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

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

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

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

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

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

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

Determine the language standard. This option is currently only supported when compiling C or C++.

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

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

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

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

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

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

Don't recognize built-in functions that do not begin with __builtin_ as prefix.

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

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

#define abs(n)          __builtin_abs ((n))
#define strcpy(d, s)    __builtin_strcpy ((d), (s))
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++.
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.
Enable parsing of function definitions marked with "__GIMPLE". This is an experimental feature that allows unit testing of GIMPLE passes.
When the option -fgnu-tm is specified, the compiler generates code for the Linux variant of Intel's current Transactional Memory ABI specification document (Revision 1.1, May 6 2009). This is an experimental feature whose interface may change in future versions of GCC, as the official specification changes. Please note that not all architectures are supported for this feature.

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

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

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

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

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

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

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.
Allow implicit conversions between vectors with differing numbers of elements and/or incompatible element types. This option should not be used for new code.
Accept some non-standard constructs used in Microsoft header files.

In C++ code, this allows member names in structures to be similar to previous types declarations.

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

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

Note that this option is off for all targets except for x86 targets using ms-abi.

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

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='-fno-math-errno -ffinite-math-only' -foffload-options=nvptx-none=-latomic
-foffload-options=amdgcn-amdhsa=-march=gfx906
Enable handling of OpenACC directives #pragma acc in C/C++ and !$acc in free-form Fortran and !$acc, c$acc and *$acc in fixed-form 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.
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.
Enable handling of OpenMP directives #pragma omp, [[omp::directive(...)]], [[omp::sequence(...)]] and [[omp::decl(...)]] in C/C++ and !$omp in Fortran. It additionally enables the conditional compilation sentinel !$ in Fortran. In fixed source form Fortran, the sentinels can also start with c or *. 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.
Enable handling of OpenMP's "simd", "declare simd", "declare reduction", "assume", "ordered", "scan" and "loop" directive, and of combined or composite directives with "simd" as constituent with "#pragma omp", "[[omp::directive(...)]]", "[[omp::sequence(...)]]" and "[[omp::decl(...)]]" in C/C++ and "!$omp" in Fortran. It additionally enables the conditional compilation sentinel !$ in Fortran. In fixed source form Fortran, the sentinels can also start with c or *. Other OpenMP directives are ignored. Unless -fopenmp is additionally specified, the "loop" region binds to the current task region, independent of the specified "bind" clause.
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.

ISO/IEC TS 18661-3 defines new permissible values for "FLT_EVAL_METHOD" that indicate that operations and constants with a semantic type that is an interchange or extended format should be evaluated to the precision and range of that type. These new values are a superset of those permitted under C99/C11, which does not specify the meaning of other positive values of "FLT_EVAL_METHOD". As such, code conforming to C11 may not have been written expecting the possibility of the new values.

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

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

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

The -fdeps-* options are used to extract structured dependency information for a source. This involves determining what resources provided by other source files will be required to compile the source as well as what resources are provided by the source. This information can be used to add required dependencies between compilation rules of dependent sources based on their contents rather than requiring such information be reflected within the build tools as well.

Where to write structured dependency information.
The format to use for structured dependency information. p1689r5 is the only supported format right now. Note that when this argument is specified, the output of -MF is stripped of some information (namely C++ modules) so that it does not use extended makefile syntax not understood by most tools.
Analogous to -MT but for structured dependency information. This indicates the target which will ultimately need any required resources and provide any resources extracted from the source that may be required by other sources.
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++.

These options control whether a bit-field is signed or unsigned, when the declaration does not use either "signed" or "unsigned". By default, such a bit-field is signed, because this is consistent: the basic integer types such as "int" are signed types.
Let the type "char" be signed, like "signed char".

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

Let the type "char" be unsigned, like "unsigned char".

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

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

The type "char" is always a distinct type from each of "signed char" or "unsigned char", even though its behavior is always just like one of those two.

Control 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 value of level controls the level of strictness.

-fstrict-flex-arrays is equivalent to -fstrict-flex-arrays=3, which is the strictest; all trailing arrays of structures are treated as flexible array members.

The negative form -fno-strict-flex-arrays is equivalent to -fstrict-flex-arrays=0, which is the least strict. In this case a trailing array is treated as a flexible array member only when it is declared as a flexible array member per C99 standard onwards.

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

You can control this behavior for a specific trailing array field of a structure by using the variable attribute "strict_flex_array" attribute.

The -fstrict_flex_arrays option interacts with the -Wstrict-flex-arrays option.

Set the default scalar storage order of structures and unions to the specified endianness. The accepted values are big-endian, little-endian and native for the native endianness of the target (the default). This option is not supported for C++.

Warning: the -fsso-struct switch causes GCC to generate code that is not binary compatible with code generated without it if the specified endianness is not the native endianness of the target.

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

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

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

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

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

Use version n of the C++ ABI. The default is version 0.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Version 15, which first appeared in G++ 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 appeard in G++ 13, fixes manglings of lambdas that have additional context.

Version 19, which first appeard in G++ 14, fixes manglings of structured bindings to include ABI tags.

See also -Wabi.

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.

Turn off all access checking. This switch is mainly useful for working around bugs in the access control code.
Enable support for C++17 "new" of types that require more alignment than "void* ::operator new(std::size_t)" provides. A numeric argument such as "-faligned-new=32" can be used to specify how much alignment (in bytes) is provided by that function, but few users will need to override the default of alignof(std::max_align_t).

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

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
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).
Enable support for the C++ Concepts feature for constraining template arguments. With -std=c++20 and above, Concepts are part of the language standard, so -fconcepts defaults to on.

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. The option -fconcepts-ts was deprecated in GCC 14 and may be removed in GCC 15; users are expected to convert their code to C++20 concepts.

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

Control whether any contracts have any semantics at all. Defaults to on.
[N4820] Control whether contracts with level axiom should have the assume semantic. Defaults to on.
[N4820] Specify which level of contracts to generate checks for. Defaults to default.
[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.
[P1332] Specify the concrete semantics for each contract level of a particular contract role.
[P1429] Specify the concrete semantic for a particular contract level.
Control whether to reject adding contracts to a function after its first declaration. Defaults to off.

The possible concrete semantics for 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.
Enable support for the C++ coroutines extension (experimental).
Permit the C++ front end to note all candidates during overload resolution failure, including when a deleted function is selected.
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.

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

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.
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.
Do not enable immediate function escalation whereby certain functions can be promoted to consteval, as specified in P2564R3. For example:
consteval int id(int i) { return i; }

constexpr int f(auto t)
{
  return t + id(t); // id causes f<int> to be promoted to consteval
}

void g(int i)
{
  f (3);
}

compiles in C++20: "f" is an immediate-escalating function (due to the "auto" it is a function template and is declared "constexpr") and id(t) is an immediate-escalating expression, so "f" is promoted to "consteval". Consequently, the call to id(t) is in an immediate context, so doesn't have to produce a constant (that is the mechanism allowing consteval function composition). However, with -fno-immediate-escalation, "f" is not promoted to "consteval", and since the call to consteval function id(t) is not a constant expression, the compiler rejects the code.

This option is turned on by default; it is only effective in C++20 mode or later.

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.
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.
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.
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.
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.
Compile a header file to create an importable header unit.
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.)
Disable lazy module importing and module mapper creation.
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.
Only emit the Compiled Module Interface, inhibiting any object file.
Disable Wpedantic warnings about constructs used in MFC, such as implicit int and getting a pointer to member function via non-standard syntax.
Enable the P0136 adjustment to the semantics of C++11 constructor inheritance. This is part of C++17 but also considered to be a Defect Report against C++11 and C++14. This flag is enabled by default unless -fabi-version=10 or lower is specified.
Enable the P0522 resolution to Core issue 150, template template parameters and default arguments: this allows a template with default template arguments as an argument for a template template parameter with fewer template parameters. This flag is enabled by default for -std=c++17.
Disable built-in declarations of functions that are not mandated by ANSI/ISO C. These include "ffs", "alloca", "_exit", "index", "bzero", "conjf", and other related functions.
Treat a throw() exception specification as if it were a "noexcept" specification to reduce or eliminate the text size overhead relative to a function with no exception specification. If the function has local variables of types with non-trivial destructors, the exception specification actually makes the function smaller because the EH cleanups for those variables can be optimized away. The semantic effect is that an exception thrown out of a function with such an exception specification results in a call to "terminate" rather than "unexpected".
Do not treat the operator name keywords "and", "bitand", "bitor", "compl", "not", "or" and "xor" as synonyms as keywords.
Disable diagnostics that the standard says a compiler does not need to issue. Currently, the only such diagnostic issued by G++ is the one for a name having multiple meanings within a class.
When an error message refers to a specialization of a function template, the compiler normally prints the signature of the template followed by the template arguments and any typedefs or typenames in the signature (e.g. "void f(T) [with T = int]" rather than "void f(int)") so that it's clear which template is involved. 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 make it harder to understand the error message rather than easier, you can use -fno-pretty-templates to disable them.
Disable generation of information about every class with virtual functions for use by the C++ run-time type identification features ("dynamic_cast" and "typeid"). If you don't use those parts of the language, you can save some space by using this flag. Note that exception handling uses the same information, but G++ generates it as needed. The "dynamic_cast" operator can still be used for casts that do not require run-time type information, i.e. casts to "void *" or to unambiguous base classes.

Mixing code compiled with -frtti with that compiled with -fno-rtti may not work. For example, programs may fail to link if a class compiled with -fno-rtti is used as a base for a class compiled with -frtti.

Enable the built-in global declarations
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;

as introduced in C++14. 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. The flag -Wsized-deallocation warns about places that might want to add a definition.

Allow the compiler to optimize using the assumption that a value of enumerated type can only be one of the values of the enumeration (as defined in the C++ standard; basically, a value that can be represented in the minimum number of bits needed to represent all the enumerators). This assumption may not be valid if the program uses a cast to convert an arbitrary integer value to the enumerated type. This option has no effect for an enumeration type with a fixed underlying type.
Evaluate member access, array subscripting, and shift expressions in left-to-right order, and evaluate assignment in right-to-left order, as adopted for C++17. Enabled by default with -std=c++17. -fstrong-eval-order=some enables just the ordering of member access and shift expressions, and is the default without -std=c++17.
Set the maximum number of template instantiation notes for a single warning or error to n. The default value is 10.
Set the maximum instantiation depth for template classes to n. A limit on the template instantiation depth is needed to detect endless recursions during template class instantiation. ANSI/ISO C++ conforming programs must not rely on a maximum depth greater than 17 (changed to 1024 in C++11). The default value is 900, as the compiler can run out of stack space before hitting 1024 in some situations.
Do not emit the extra code to use the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this option to reduce code size slightly in code that doesn't need to be thread-safe.
Register destructors for objects with static storage duration with the "__cxa_atexit" function rather than the "atexit" function. This option is required for fully standards-compliant handling of static destructors, but only works if your C library supports "__cxa_atexit".
Don't use the "__cxa_get_exception_ptr" runtime routine. This causes "std::uncaught_exception" to be incorrect, but is necessary if the runtime routine is not available.
This switch declares that the user does not attempt to compare pointers to inline functions or methods where the addresses of the two functions are taken in different shared objects.

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

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

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

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

This flag attempts to use visibility settings to make GCC's C++ linkage model compatible with that of Microsoft Visual Studio.

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

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

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

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

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

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

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

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

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

This warning is upgraded to an error by -pedantic-errors in C++23 mode or later.

Warn when performing class template argument deduction (CTAD) on a type with no explicitly written deduction guides. This warning will point out cases where CTAD succeeded only because the compiler synthesized the implicit deduction guides, which might not be what the programmer intended. Certain style guides allow CTAD only on types that specifically "opt-in"; i.e., on types that are designed to support CTAD. This warning can be suppressed with the following pattern:
struct allow_ctad_t; // any name works
template <typename T> struct S {
  S(T) { }
};
// Guide with incomplete parameter type will never be considered.
S(allow_ctad_t) -> S<void>;
Warn when a class seems unusable because all the constructors or destructors in that class are private, and it has neither friends nor public static member functions. Also warn if there are no non-private methods, and there's at least one private member function that isn't a constructor or destructor.
Warn 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

The "#pragma" can also surround the class; in that case, the warning will be disabled for all the member functions.

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

The warning does not warn for "std::span"-like classes. We consider classes of the form:

template<typename T>
struct Span {
  T* data_;
  std::size len_;
};

as "std::span"-like; that is, the class is a non-union class that has a pointer data member and a trivial destructor.

The warning can be disabled by using the "gnu::no_dangling" attribute.

This warning is enabled by -Wall.

Warn when "delete" is used to destroy an instance of a class that has virtual functions and non-virtual destructor. It is unsafe to delete an instance of a derived class through a pointer to a base class if the base class does not have a virtual destructor. This warning is enabled by -Wall.
Warn that the implicit declaration of a copy constructor or copy assignment operator is deprecated if the class has a user-provided copy constructor or copy assignment operator, in C++11 and up. This warning is enabled by -Wextra. With -Wdeprecated-copy-dtor, also deprecate if the class has a user-provided destructor.
Disable the warning about the case when the usual arithmetic conversions are applied on operands where one is of enumeration type and the other is of a different enumeration type. This conversion was deprecated in C++20. For example:
enum E1 { e };
enum E2 { f };
int k = f - e;

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

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

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

For C++11 and above, warn if an (invalid) additional enum-base is used in an elaborated-type-specifier. That is, if an enum with given underlying type and no enumerator list is used in a declaration other than just a standalone declaration of the enum. Enabled by default. This warning is upgraded to an error with -pedantic-errors.
Do not warn about uses of "std::initializer_list" that are likely to result in dangling pointers. Since the underlying array for an "initializer_list" is handled like a normal C++ temporary object, it is easy to inadvertently keep a pointer to the array past the end of the array's lifetime. For example:
  • If a function returns a temporary "initializer_list", or a local "initializer_list" variable, the array's lifetime ends at the end of the return statement, so the value returned has a dangling pointer.
  • If a new-expression creates an "initializer_list", the array only lives until the end of the enclosing full-expression, so the "initializer_list" in the heap has a dangling pointer.
  • When an "initializer_list" variable is assigned from a brace-enclosed initializer list, the temporary array created for the right side of the assignment only lives until the end of the full-expression, so at the next statement the "initializer_list" variable has a dangling pointer.
    // li's initial underlying array lives as long as li
    std::initializer_list<int> li = { 1,2,3 };
    // assignment changes li to point to a temporary array
    li = { 4, 5 };
    // now the temporary is gone and li has a dangling pointer
    int i = li.begin()[0] // undefined behavior
    
  • When a list constructor stores the "begin" pointer from the "initializer_list" argument, this doesn't extend the lifetime of the array, so if a class variable is constructed from a temporary "initializer_list", the pointer is left dangling by the end of the variable declaration statement.
Warn 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);
}
Verify all imported macro definitions are valid at the end of compilation. This is not enabled by default, as it requires additional processing to determine. It may be useful when preparing sets of header-units to ensure consistent macros.
Do not warn when a string or character literal is followed by a ud-suffix which does not begin with an underscore. As a conforming extension, GCC treats such suffixes as separate preprocessing tokens in order to maintain backwards compatibility with code that uses formatting macros from "<inttypes.h>". For example:
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>

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

In this case, "PRId64" is treated as a separate preprocessing token.

This option also controls warnings when a user-defined literal operator is declared with a literal suffix identifier that doesn't begin with an underscore. Literal suffix identifiers that don't begin with an underscore are reserved for future standardization.

These warnings are enabled by default.

For C++11 and later standards, narrowing conversions are diagnosed by default, as required by the standard. A narrowing conversion from a constant produces an error, and a narrowing conversion from a non-constant produces a warning, but -Wno-narrowing suppresses the diagnostic. Note that this does not affect the meaning of well-formed code; narrowing conversions are still considered ill-formed in SFINAE contexts.

With -Wnarrowing in C++98, warn when a narrowing conversion prohibited by C++11 occurs within { }, e.g.

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

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

Warn when a noexcept-expression evaluates to false because of a call to a function that does not have a non-throwing exception specification (i.e. throw() or "noexcept") but is known by the compiler to never throw an exception.
Warn if the C++17 feature making "noexcept" part of a function type changes the mangled name of a symbol relative to C++14. Enabled by -Wabi and -Wc++17-compat.

As an example:

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

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

Warn when the destination of a call to a raw memory function such as "memset" or "memcpy" is an object of class type, and when writing into such an object might bypass the class non-trivial or deleted constructor or copy assignment, violate const-correctness or encapsulation, or corrupt virtual table pointers. Modifying the representation of such objects may violate invariants maintained by member functions of the class. For example, the call to "memset" below is undefined because it modifies a non-trivial class object and is, therefore, diagnosed. The safe way to either initialize or clear the storage of objects of such types is by using the appropriate constructor or assignment operator, if one is available.
std::string str = "abc";
memset (&str, 0, sizeof str);

The -Wclass-memaccess option is enabled by -Wall. Explicitly casting the pointer to the class object to "void *" or to a type that can be safely accessed by the raw memory function suppresses the warning.

Warn when a class has virtual functions and an accessible non-virtual destructor itself or in an accessible polymorphic base class, in which case it is possible but unsafe to delete an instance of a derived class through a pointer to the class itself or base class. This warning is automatically enabled if -Weffc++ is specified. The -Wdelete-non-virtual-dtor option (enabled by -Wall) should be preferred because it warns about the unsafe cases without false positives.
Warn on uses of the "register" storage class specifier, except when it is part of the GNU Explicit Register Variables extension. The use of the "register" keyword as storage class specifier has been deprecated in C++11 and removed in C++17. Enabled by default with -std=c++17.
Warn when the order of member initializers given in the code does not match the order in which they must be executed. For instance:
struct A {
  int i;
  int j;
  A(): j (0), i (1) { }
};

The compiler rearranges the member initializers for "i" and "j" to match the declaration order of the members, emitting a warning to that effect. This warning is enabled by -Wall.

This warning warns when a call to "std::move" prevents copy elision. A typical scenario when copy elision can occur is when returning in a function with a class return type, when the expression being returned is the name of a non-volatile automatic object, and is not a function parameter, and has the same type as the function return type.
struct T {
...
};
T fn()
{
  T t;
  ...
  return std::move (t);
}

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

This warning is enabled by -Wall.

This warning warns about redundant calls to "std::move"; that is, when a move operation would have been performed even without the "std::move" call. This happens because the compiler is forced to treat the object as if it were an rvalue in certain situations such as returning a local variable, where copy elision isn't applicable. Consider:
struct T {
...
};
T fn(T t)
{
  ...
  return std::move (t);
}

Here, the "std::move" call is redundant. Because G++ implements Core Issue 1579, another example is:

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

In this example, copy elision isn't applicable because the type of the expression being returned and the function return type differ, yet G++ treats the return value as if it were designated by an rvalue.

This warning is enabled by -Wextra.

This warning warns when a C++ range-based for-loop is creating an unnecessary copy. This can happen when the range declaration is not a reference, but probably should be. For example:
struct S { char arr[128]; };
void fn () {
  S arr[5];
  for (const auto x : arr) { ... }
}

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

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

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

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

This warning is enabled by -Wall.

Warn about redundant class-key and enum-key in references to class types and enumerated types in contexts where the key can be eliminated without causing an ambiguity. For example:
struct foo;
struct foo *p;   // warn that keyword struct can be eliminated

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

struct foo;
void foo ();   // "hides" struct foo
void bar (struct foo&);  // no warning, keyword struct is necessary
Do not warn if a class type has a base or a field whose type uses the anonymous namespace or depends on a type with no linkage. If a type A depends on a type B with no or internal linkage, defining it in multiple translation units would be an ODR violation because the meaning of B is different in each translation unit. If A only appears in a single translation unit, the best way to silence the warning is to give it internal linkage by putting it in an anonymous namespace as well. The compiler doesn't give this warning for types defined in the main .C file, as those are unlikely to have multiple definitions. -Wsubobject-linkage is enabled by default.
Warn about violations of the following style guidelines from Scott Meyers' Effective C++ series of books:
  • Define a copy constructor and an assignment operator for classes with dynamically-allocated memory.
  • Prefer initialization to assignment in constructors.
  • Have "operator=" return a reference to *this.
  • Don't try to return a reference when you must return an object.
  • Distinguish between prefix and postfix forms of increment and decrement operators.
  • Never overload "&&", "||", or ",".

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

When selecting this option, be aware that the standard library headers do not obey all of these guidelines; use grep -v to filter out those warnings.

Disable the warning about the case when an exception handler is shadowed by another handler, which can point out a wrong ordering of exception handlers.
Warn about the use of an uncasted "NULL" as sentinel. When compiling only with GCC this is a valid sentinel, as "NULL" is defined to "__null". Although it is a null pointer constant rather than a null pointer, it is guaranteed to be of the same size as a pointer. But this use is not portable across different compilers.
Disable warnings when non-template friend functions are declared within a template. In very old versions of GCC that predate implementation of the ISO standard, declarations such as friend int foo(int), where the name of the friend is an unqualified-id, could be interpreted as a particular specialization of a template function; the warning exists to diagnose compatibility problems, and is enabled by default.
Warn if an old-style (C-style) cast to a non-void type is used within a C++ program. The new-style casts ("dynamic_cast", "static_cast", "reinterpret_cast", and "const_cast") are less vulnerable to unintended effects and much easier to search for.
Warn when a function declaration hides virtual functions from a base class. For example, in:
struct A {
  virtual void f();
};

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

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

B* b;
b->f();

fails to compile.

In cases where the different signatures are not an accident, the simplest solution is to add 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 the 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. Level 1 is included in -Wall.

Disable the diagnostic for converting a bound pointer to member function to a plain pointer.
Warn when overload resolution chooses a promotion from unsigned or enumerated type to a signed type, over a conversion to an unsigned type of the same size. Previous versions of G++ tried to preserve unsignedness, but the standard mandates the current behavior.
Warn 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.
Warn for mismatches between calls to "operator new" or "operator delete" and the corresponding call to the allocation or deallocation function. This includes invocations of C++ "operator delete" with pointers returned from either mismatched forms of "operator new", or from other functions that allocate objects for which the "operator delete" isn't a suitable deallocator, as well as calls to other deallocation functions with pointers returned from "operator new" for which the deallocation function isn't suitable.

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

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

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

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

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

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

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

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

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

Warn 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.
Warn 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.
Suppress 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.
Warn 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.
Disable the warning about the use of simple-template-id as the declarator-id of a constructor or destructor, which became invalid in C++20 via DR 2237. For example:
template<typename T> struct S {
  S<T>(); // should be S();
  ~S<T>();  // should be ~S();
};

-Wtemplate-id-cdtor is enabled by default with -std=c++20; it is also enabled by -Wc++20-compat.

Disable the warning about a throw-expression that will immediately result in a call to "terminate".
Warn about the most vexing parse syntactic ambiguity. This warns about the cases when a declaration looks like a variable definition, but the C++ language requires it to be interpreted as a function declaration. For instance:
void f(double a) {
  int i();        // extern int i (void);
  int n(int(a));  // extern int n (int);
}

Another example:

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

The warning will suggest options how to deal with such an ambiguity; e.g., it can suggest removing the parentheses or using braces instead.

This warning is enabled by default.

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

Warn when a literal 0 is used as null pointer constant. This can be useful to facilitate the conversion to "nullptr" in C++11.
Warn about a new-expression of a type that requires greater alignment than the alignof(std::max_align_t) but uses an allocation function without an explicit alignment parameter. This option is enabled by -Wall.

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

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

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]();
At this level, in addition to diagnosing all the same constructs as at level 1, a diagnostic is also issued for placement new expressions that construct an object in the last member of structure whose type is an array of a single element and whose size is less than the size of the object being constructed. While the previous example would be diagnosed, the following construct makes use of the flexible member array extension to avoid the warning at level 2.
struct S { int n, a[]; };
S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]);
new (s->a)int [32]();
Warn about catch handlers that do not catch via reference. With -Wcatch-value=1 (or -Wcatch-value for short) warn about polymorphic class types that are caught by value. With -Wcatch-value=2 warn about all class types that are caught by value. With -Wcatch-value=3 warn about all types that are not caught by reference. -Wcatch-value is enabled by -Wall.
Warn for conditionally-supported (C++11 [intro.defs]) constructs.
Do not warn when deleting a pointer to incomplete type, which may cause undefined behavior at runtime. This warning is enabled by default.
Warn about redundant semicolons after in-class function definitions.
Disable the diagnostic for when the global module fragment of a module unit does not consist only of preprocessor directives.
This option controls warnings when a base class is inaccessible in a class derived from it due to ambiguity. The warning is enabled by default. Note that the warning for ambiguous virtual bases is enabled by the -Wextra option.
struct A { int a; };

struct B : A { };

struct C : B, A { };
Suppress warnings about use of C++11 inheriting constructors when the base class inherited from has a C variadic constructor; the warning is on by default because the ellipsis is not inherited.
Suppress warnings from applying the "offsetof" macro to a non-POD type. According to the 2014 ISO C++ standard, applying "offsetof" to a non-standard-layout type is undefined. In existing C++ implementations, however, "offsetof" typically gives meaningful results. This flag is for users who are aware that they are writing nonportable code and who have deliberately chosen to ignore the warning about it.

The restrictions on "offsetof" may be relaxed in a future version of the C++ standard.

Warn about a definition of an unsized deallocation function
void operator delete (void *) noexcept;
void operator delete[] (void *) noexcept;

without a definition of the corresponding sized deallocation function

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

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

Warn about types with virtual methods where code quality would be improved if the type were declared with the C++11 "final" specifier, or, if possible, declared in an anonymous namespace. This allows GCC to more aggressively devirtualize the polymorphic calls. This warning is more effective with link-time optimization, where the information about the class hierarchy graph is more complete.
Warn about virtual methods where code quality would be improved if the method were declared with the C++11 "final" specifier, or, if possible, its type were declared in an anonymous namespace or with the "final" specifier. This warning is more effective with link-time optimization, where the information about the class hierarchy graph is more complete. It is recommended to first consider suggestions of -Wsuggest-final-types and then rebuild with new annotations.
Warn about overriding virtual functions that are not marked with the "override" keyword.
Do not warn for conversions between "NULL" and non-pointer types. -Wconversion-null is enabled by default.

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

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

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

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

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

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

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). On Darwin / macOS platforms, the -fconstant-cfstrings option, if also present, overrides the -fconstant-string-class setting and cause "@"..."" literals to be laid out as constant CoreFoundation strings. Note that -fconstant-cfstrings is an alias for the target-specific -mconstant-cfstrings equivalent.
Generate object code compatible with the standard GNU Objective-C runtime. This is the default for most types of systems.
Generate output compatible with the NeXT runtime. This is the default for NeXT-based systems, including Darwin / macOS. The macro "__NEXT_RUNTIME__" is predefined if (and only if) this option is used.
Assume that all Objective-C message dispatches ("[receiver message:arg]") in this translation unit ensure that the receiver is not "nil". This allows for more efficient entry points in the runtime to be used. This option is only available in conjunction with the NeXT runtime and ABI version 0 or 1.
Use version n of the Objective-C ABI for the selected runtime. This option is currently supported only for the NeXT runtime. In that case, Version 0 is the traditional (32-bit) ABI without support for properties and other Objective-C 2.0 additions. Version 1 is the traditional (32-bit) ABI with support for properties and other Objective-C 2.0 additions. Version 2 is the modern (64-bit) ABI. If nothing is specified, the default is Version 0 on 32-bit target machines, and Version 2 on 64-bit target machines.
For each Objective-C class, check if any of its instance variables is a C++ object with a non-trivial default constructor. If so, synthesize a special "- (id) .cxx_construct" instance method which runs non-trivial default constructors on any such instance variables, in order, and then return "self". Similarly, check if any instance variable is a C++ object with a non-trivial destructor, and if so, synthesize a special "- (void) .cxx_destruct" method which runs all such default destructors, in reverse order.

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

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

Allow fast jumps to the message dispatcher. On Darwin this is accomplished via the comm page.
Enable syntactic support for structured exception handling in Objective-C, similar to what is offered by C++. This option is required to use the Objective-C keywords @try, @throw, @catch, @finally and @synchronized. This option is available with both the GNU runtime and the NeXT runtime (but not available in conjunction with the NeXT runtime on Mac OS X 10.2 and earlier).
Enable garbage collection (GC) in Objective-C and Objective-C++ programs. This option is only available with the NeXT runtime; the GNU runtime has a different garbage collection implementation that does not require special compiler flags.
For the NeXT runtime with version 2 of the ABI, check for a nil receiver in method invocations before doing the actual method call. This is the default and can be disabled using -fno-objc-nilcheck. Class methods and super calls are never checked for nil in this way no matter what this flag is set to. Currently this flag does nothing when the GNU runtime, or an older version of the NeXT runtime ABI, is used.
Conform to the language syntax of Objective-C 1.0, the language recognized by GCC 4.0. This only affects the Objective-C additions to the C/C++ language; it does not affect conformance to C/C++ standards, which is controlled by the separate C/C++ dialect option flags. When this option is used with the Objective-C or Objective-C++ compiler, any Objective-C syntax that is not recognized by GCC 4.0 is rejected. This is useful if you need to make sure that your Objective-C code can be compiled with older versions of GCC.
Emit a special marker instructing ld(1) not to statically link in the resulting object file, and allow dyld(1) to load it in at run time instead. This is used in conjunction with the Fix-and-Continue debugging mode, where the object file in question may be recompiled and dynamically reloaded in the course of program execution, without the need to restart the program itself. Currently, Fix-and-Continue functionality is only available in conjunction with the NeXT runtime on Mac OS X 10.3 and later.
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.
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.
Set the default instance variable visibility to the specified option so that instance variables declared outside the scope of any access modifier directives default to the specified visibility.
Dump interface declarations for all classes seen in the source file to a file named sourcename.decl.
Warn whenever an Objective-C assignment is being intercepted by the garbage collector.
Do not warn if a property for an Objective-C object has no assign semantics specified.
If a class is declared to implement a protocol, a warning is issued for every method in the protocol that is not implemented by the class. The default behavior is to issue a warning for every method not explicitly implemented in the class, even if a method implementation is inherited from the superclass. If you use the -Wno-protocol option, then methods inherited from the superclass are considered to be implemented, and no warning is issued for them.
Warn if a class interface lacks a superclass. Most classes will inherit from "NSObject" (or "Object") for example. When declaring classes intended to be root classes, the warning can be suppressed by marking their interfaces with "__attribute__((objc_root_class))".
Warn if multiple methods of different types for the same selector are found during compilation. The check is performed on the list of methods in the final stage of compilation. Additionally, a check is performed for each selector appearing in a @selector(...) expression, and a corresponding method for that selector has been found during compilation. Because these checks scan the method table only at the end of compilation, these warnings are not produced if the final stage of compilation is not reached, for example because an error is found during compilation, or because the -fsyntax-only option is being used.
Warn if multiple methods with differing argument and/or return types are found for a given selector when attempting to send a message using this selector to a receiver of type "id" or "Class". When this flag is off (which is the default behavior), the compiler omits such warnings if any differences found are confined to types that share the same size and alignment.
Warn if a @selector(...) expression referring to an undeclared selector is found. A selector is considered undeclared if no method with that name has been declared before the @selector(...) expression, either explicitly in an @interface or @protocol declaration, or implicitly in an @implementation section. This option always performs its checks as soon as a @selector(...) expression is found, while -Wselector only performs its checks in the final stage of compilation. This also enforces the coding style convention that methods and selectors must be declared before being used.
Generate C header describing the largest structure that is passed by value, if any.

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

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

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

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 -fdiagnostics-text-art-charset=none 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.
Only meaningful in line-wrapping mode. Instructs the diagnostic messages reporter to emit source location information once; that is, in case the message is too long to fit on a single physical line and has to be wrapped, the source location won't be emitted (as prefix) again, over and over, in subsequent continuation lines. This is the default behavior.
Only meaningful in line-wrapping mode. Instructs the diagnostic messages reporter to emit the same source location information (as prefix) for physical lines that result from the process of breaking a message which is too long to fit on a single line.
Use color in diagnostics. WHEN is never, always, or auto. The default depends on how the compiler has been configured, it can be any of the above WHEN options or also never if GCC_COLORS environment variable isn't present in the environment, and auto otherwise. auto makes GCC use color only when the standard error is a terminal, and when not executing in an emacs shell. The forms -fdiagnostics-color and -fno-diagnostics-color are aliases for -fdiagnostics-color=always and -fdiagnostics-color=never, respectively.

The colors are defined by the environment variable GCC_COLORS. Its value is a colon-separated list of capabilities and Select Graphic Rendition (SGR) substrings. SGR commands are interpreted by the terminal or terminal emulator. (See the section in the documentation of your text terminal for permitted values and their meanings as character attributes.) These substring values are integers in decimal representation and can be concatenated with semicolons. Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors.

The default GCC_COLORS is

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

where 01;31 is bold red, 01;35 is bold magenta, 01;36 is bold cyan, 32 is green, 34 is blue, 01 is bold, and 31 is red. Setting GCC_COLORS to the empty string disables colors. Supported capabilities are as follows.

"error="
SGR substring for error: markers.
"warning="
SGR substring for warning: markers.
"note="
SGR substring for note: markers.
"path="
SGR substring for colorizing paths of control-flow events as printed via -fdiagnostics-path-format=, such as the identifiers of individual events and lines indicating interprocedural calls and returns.
"range1="
SGR substring for first additional range.
"range2="
SGR substring for second additional range.
"locus="
SGR substring for location information, file:line or file:line:column etc.
"quote="
SGR substring for information printed within quotes.
"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.
"valid="
SGR substring for highlighting valid elements within text art diagrams.
"invalid="
SGR substring for highlighting invalid elements within text art diagrams.
Use escape sequences to embed URLs in diagnostics. For example, when -fdiagnostics-show-option emits text showing the command-line option controlling a diagnostic, embed a URL for documentation of that option.

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

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

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

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

At this time GCC 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.

By default, each diagnostic emitted includes text indicating the command-line option that directly controls the diagnostic (if such an option is known to the diagnostic machinery). Specifying the -fno-diagnostics-show-option flag suppresses that behavior.
By default, each diagnostic emitted includes the original source line and a caret ^ indicating the column. This option suppresses this information. The source line is truncated to n characters, if the -fmessage-length=n option is given. When the output is done to the terminal, the width is limited to the width given by the COLUMNS environment variable or, if not set, to the terminal width.
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).

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.
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.
By default, when printing source code (via -fdiagnostics-show-caret), a left margin is printed, showing line numbers. This option suppresses this left margin.
This option controls the minimum width of the left margin printed by -fdiagnostics-show-line-numbers. It defaults to 6.
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.

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

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

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

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

The parts that differ are highlighted with color ("double" and "float" in this case).

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.

Specify how to print paths of control-flow events for diagnostics that have such a path associated with them.

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

none means to not print diagnostic paths.

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

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

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

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

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

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

For example:

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

If this is option is provided then the stack depth will be printed for each run of events within -fdiagnostics-path-format=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.

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

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.

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.
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
Some diagnostics can contain "text art" diagrams: visualizations created from text, intended to be viewed in a monospaced font.

This option selects which characters should be used for printing such diagrams, if any. CHARSET is none, ascii, unicode, or emoji.

The none value suppresses the printing of such diagrams. The ascii value will ensure that such diagrams are pure ASCII ("ASCII art"). The unicode value will allow for conservative use of unicode drawing characters (such as box-drawing characters). The emoji value further adds the possibility of emoji in the output (such as emitting U+26A0 WARNING SIGN followed by U+FE0F VARIATION SELECTOR-16 to select the emoji variant of the character).

The default is emoji, except when the environment variable LANG is set to C, in which case the default is ascii.

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.

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:

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

where the "note" is a child of the "warning".

A diagnostic has a "kind". If this is "warning", then there is an "option" key describing the command-line option controlling the warning.

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

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

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

For example, this error:

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

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

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

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

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

might be printed in JSON form as:

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

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

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

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

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

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

By default, when JSON is emitted for diagnostics (via -fdiagnostics-format=sarif-stderr, -fdiagnostics-format=sarif-file, -fdiagnostics-format=json, -fdiagnostics-format=json-stderr, -fdiagnostics-format=json-file), GCC will add newlines and indentation to visually emphasize the hierarchical structure of the JSON.

Use -fno-diagnostics-json-formatting to suppress this whitespace. It must be passed before the option it is to affect.

This is intended for compatibility with tools that do not expect the output to contain newlines, such as that emitted by older GCC releases.

Warnings are diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error.

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

Check the code for syntax errors, but don't do anything beyond that.
Limits the maximum number of error messages to n, at which point GCC bails out rather than attempting to continue processing the source code. If n is 0 (the default), there is no limit on the number of error messages produced. If -Wfatal-errors is also specified, then -Wfatal-errors takes precedence over this option.
Inhibit all warning messages.
Make all warnings into errors.
Make the specified warning into an error. The specifier for a warning is appended; for example -Werror=switch turns the warnings controlled by -Wswitch into errors. This switch takes a negative form, to be used to negate -Werror for specific warnings; for example -Wno-error=switch makes -Wswitch warnings not be errors, even when -Werror is in effect.

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

Note that specifying -Werror=foo automatically implies -Wfoo. However, -Wno-error=foo does not imply anything.

This option causes the compiler to abort compilation on the first error occurred rather than trying to keep going and printing further error messages.

You can request many specific warnings with options beginning with -W, for example -Wimplicit to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning -Wno- to turn off warnings; for example, -Wno-implicit. This manual lists only one of the two forms, whichever is not the default. For further language-specific options also refer to C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. Additional warnings can be produced by enabling the static analyzer;

Some options, such as -Wall and -Wextra, turn on other options, such as -Wunused, which may turn on further options, such as -Wunused-value. The combined effect of positive and negative forms is that more specific options have priority over less specific ones, independently of their position in the command-line. For options of the same specificity, the last one takes effect. Options enabled or disabled via pragmas take effect as if they appeared at the end of the command-line.

When an unrecognized warning option is requested (e.g., -Wunknown-warning), GCC emits a diagnostic stating that the option is not recognized. However, if the -Wno- form is used, the behavior is slightly different: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are being produced. This allows the use of new -Wno- options with old compilers, but if something goes wrong, the compiler warns that an unrecognized option is present.

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

Issue all the warnings demanded by strict ISO C and ISO C++; diagnose all programs that use forbidden extensions, and some other programs that do not follow ISO C and ISO C++. This follows the version of the ISO C or C++ standard specified by any -std option used.

Valid ISO C and ISO C++ programs should compile properly with or without this option (though a rare few require -ansi or a -std option specifying the version of the standard). However, without this option, certain GNU extensions and traditional C and C++ features are supported as well. With this option, they are diagnosed (or rejected with -pedantic-errors).

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

Some warnings about non-conforming programs are controlled by options other than -Wpedantic; in many cases they are implied by -Wpedantic but can be disabled separately by their specific option, e.g. -Wpedantic -Wno-pointer-sign.

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

Give an error whenever the base standard (see -Wpedantic) requires a diagnostic, in some cases where there is undefined behavior at compile-time and in some other cases that do not prevent compilation of programs that are valid according to the standard. This is not equivalent to -Werror=pedantic: the latter option is unlikely to be useful, as it only makes errors of the diagnostics that are controlled by -Wpedantic, whereas this option also affects required diagnostics that are always enabled or controlled by options other than -Wpedantic.

If you want the required diagnostics that are warnings by default to be errors instead, but don't also want to enable the -Wpedantic diagnostics, you can specify -pedantic-errors -Wno-pedantic (or -pedantic-errors -Wno-error=pedantic to enable them but only as warnings).

Some required diagnostics are errors by default, but can be reduced to warnings using -fpermissive or their specific warning option, e.g. -Wno-error=narrowing.

Some diagnostics for non-ISO practices are controlled by specific warning options other than -Wpedantic, but are also made errors by -pedantic-errors. For instance:

-Wattributes (for standard attributes) -Wchanges-meaning (C++) -Wcomma-subscript (C++23 or later) -Wdeclaration-after-statement (C90 or earlier) -Welaborated-enum-base (C++11 or later) -Wimplicit-int (C99 or later) -Wimplicit-function-declaration (C99 or later) -Wincompatible-pointer-types -Wint-conversion -Wlong-long (C90 or earlier) -Wmain -Wnarrowing (C++11 or later) -Wpointer-arith -Wpointer-sign -Wincompatible-pointer-types -Wregister (C++17 or later) -Wvla (C90 or earlier) -Wwrite-strings (C++11 or later)

Downgrade some required diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive allows some nonconforming code to compile. Some C++ diagnostics are controlled only by this flag, but it also downgrades some C and C++ diagnostics that have their own flag:

-Wdeclaration-missing-parameter-type (C and Objective-C only) -Wimplicit-function-declaration (C and Objective-C only) -Wimplicit-int (C and Objective-C only) -Wincompatible-pointer-types (C and Objective-C only) -Wint-conversion (C and Objective-C only) -Wnarrowing (C++ and Objective-C++ only) -Wreturn-mismatch (C and Objective-C only)

The -fpermissive option is the default for historic C language modes (-std=c89, -std=gnu89, -std=c90, -std=gnu90).

This enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros. This also enables some language-specific warnings described in C++ Dialect Options and Objective-C and Objective-C++ Dialect Options.

-Wall turns on the following warning flags:

-Waddress -Waligned-new (C++ and Objective-C++ only) -Warray-bounds=1 (only with -O2) -Warray-compare -Warray-parameter=2 -Wbool-compare -Wbool-operation -Wc++11-compat -Wc++14-compat -Wc++17compat -Wc++20compat -Wcatch-value (C++ and Objective-C++ only) -Wchar-subscripts -Wclass-memaccess (C++ and Objective-C++ only) -Wcomment -Wdangling-else -Wdangling-pointer=2 -Wdelete-non-virtual-dtor (C++ and Objective-C++ only) -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=1 -Wformat-contains-nul -Wformat-diag -Wformat-extra-args -Wformat-overflow=1 -Wformat-truncation=1 -Wformat-zero-length -Wframe-address -Wimplicit (C and Objective-C only) -Wimplicit-function-declaration (C and Objective-C only) -Wimplicit-int (C and Objective-C only) -Winfinite-recursion -Winit-self (C++ and Objective-C++ only) -Wint-in-bool-context -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 (C++ and Objective-C++ only) -Wmissing-attributes -Wmissing-braces (only for C/ObjC) -Wmultistatement-macros -Wnarrowing (C++ and Objective-C++ only) -Wnonnull -Wnonnull-compare -Wopenmp-simd (C and C++ only) -Woverloaded-virtual=1 (C++ and Objective-C++ only) -Wpacked-not-aligned -Wparentheses -Wpessimizing-move (C++ and Objective-C++ only) -Wpointer-sign (only for C/ObjC) -Wrange-loop-construct (C++ and Objective-C++ only) -Wreorder (C++ and Objective-C++ only) -Wrestrict -Wreturn-type -Wself-move (C++ and Objective-C++ only) -Wsequence-point -Wsign-compare (C++ and Objective-C++ only) -Wsizeof-array-div -Wsizeof-pointer-div -Wsizeof-pointer-memaccess -Wstrict-aliasing -Wstrict-overflow=1 -Wswitch -Wtautological-compare -Wtrigraphs -Wuninitialized -Wunknown-pragmas -Wunused -Wunused-but-set-variable -Wunused-const-variable=1 (only for C/ObjC) -Wunused-function -Wunused-label -Wunused-local-typedefs -Wunused-value -Wunused-variable -Wuse-after-free=2 -Wvla-parameter -Wvolatile-register-var -Wzero-length-bounds

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

This enables some extra warning flags that are not enabled by -Wall. (This option used to be called -W. The older name is still supported, but the newer name is more descriptive.)

-Wabsolute-value (only for C/ObjC) -Walloc-size -Wcalloc-transposed-args -Wcast-function-type -Wclobbered -Wdeprecated-copy (C++ and Objective-C++ only) -Wempty-body -Wenum-conversion (only for C/ObjC) -Wexpansion-to-defined -Wignored-qualifiers (only for C/C++) -Wimplicit-fallthrough=3 -Wmaybe-uninitialized -Wmissing-field-initializers -Wmissing-parameter-type (C/ObjC only) -Wold-style-declaration (C/ObjC only) -Woverride-init (C/ObjC only) -Wredundant-move (C++ and Objective-C++ only) -Wshift-negative-value (in C++11 to C++17 and in C99 and newer) -Wsign-compare (C++ and Objective-C++ only) -Wsized-deallocation (C++ and Objective-C++ only) -Wstring-compare -Wtype-limits -Wuninitialized -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.
Warn about code affected by ABI changes. This includes code that may not be compatible with the vendor-neutral C++ ABI as well as the psABI for the particular target.

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

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

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

Although an effort has been made to warn about all such cases, there are probably some cases that are not warned about, even though G++ is generating incompatible code. There may also be cases where warnings are emitted even though the code that is generated is compatible.

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

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

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

    This was fixed in -fabi-version=3.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

"union U" is now always passed in memory.

C++ requires that unqualified uses of a name within a class have the same meaning in the complete scope of the class, so 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.

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

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

Suppress warning messages emitted by "#warning" directives.
Give a warning when a value of type "float" is implicitly promoted to "double". CPUs with a 32-bit "single-precision" floating-point unit implement "float" in hardware, but emulate "double" in software. On such a machine, doing computations using "double" values is much more expensive because of the overhead required for software emulation.

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

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

the compiler performs the entire computation with "double" because the floating-point literal is a "double".

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

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

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.
Enable -Wformat plus additional format checks. Currently equivalent to -Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k.
If -Wformat is specified, do not warn about format strings that contain NUL bytes.
If -Wformat is specified, do not warn about excess arguments to a "printf" or "scanf" format function. The C standard specifies that such arguments are ignored.

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

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

void f (int a, int b)
{
  char buf [23];
  sprintf (buf, "a = %hi, b = %i\n", a, (short)b);
}
If -Wformat is specified, do not warn about zero-length formats. The C standard specifies that zero-length formats are allowed.
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".
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.)
If -Wformat is specified, also warn if the format string requires an unsigned argument and the argument is signed and vice versa.
Warn about calls to formatted input/output functions such as "snprintf" and "vsnprintf" that might result in output truncation. When the exact number of bytes written by a format directive cannot be determined at compile-time it is estimated based on heuristics that depend on the level argument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives. Except as noted otherwise, the option uses the same logic -Wformat-overflow.
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.
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.
If -Wformat is specified, also warn about "strftime" formats that may yield only a two-digit year.
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.

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.

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.
Warn if the compiler does not elide the copy from a local variable to the return value of a function in a context where it is allowed by [class.copy.elision]. This elision is commonly known as the Named Return Value Optimization. For instance, in the example below the compiler cannot elide copies from both v1 and v2, so it elides neither.
std::vector<int> f()
{
  std::vector<int> v1, v2;
  // ...
  if (cond) return v1;
  else return v2; // warning: not eliding copy
}
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).

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

This option controls warnings when a declaration does not specify a type. This warning is enabled by default, as an error, in C99 and later dialects of C, and also by -Wall. The error can be downgraded to a warning using -fpermissive (along with certain other errors), or for this error alone, with -Wno-error=implicit-int.

This warning is upgraded to an error by -pedantic-errors.

This option controls warnings when a function is used before being declared. This warning is enabled by default, as an error, in C99 and later dialects of C, and also by -Wall. The error can be downgraded to a warning using -fpermissive (along with certain other errors), or for this error alone, with -Wno-error=implicit-function-declaration.

This warning is upgraded to an error by -pedantic-errors.

Same as -Wimplicit-int and -Wimplicit-function-declaration. This warning is enabled by -Wall.
Warn when -fhardened did not enable an option from its set (for which see -fhardened). For instance, using -fhardened and -fstack-protector at the same time on the command line causes -Whardened to warn because -fstack-protector-strong is not enabled by -fhardened.

This warning is enabled by default and has effect only when -fhardened is enabled.

-Wimplicit-fallthrough is the same as -Wimplicit-fallthrough=3 and -Wno-implicit-fallthrough is the same as -Wimplicit-fallthrough=0.
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 function declared with the noreturn attribute. -Wimplicit-fallthrough= also takes into account control flow statements, such as ifs, and only warns when appropriate. E.g.

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

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

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

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

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

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

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

The -Wimplicit-fallthrough=3 warning is enabled by -Wextra.

Control if warnings triggered by the "warn_if_not_aligned" attribute should be issued. These warnings are enabled by default.
Warn if the return type of a function has a type qualifier such as "const". For ISO C such a type qualifier has no effect, since the value returned by a function is not an lvalue. For C++, the warning is only emitted for scalar types or "void". ISO C prohibits qualified "void" return types on function definitions, so such return types always receive a warning even without this option.

This warning is also enabled by -Wextra.

This option controls warnings when an attribute is ignored. This is different from the -Wattributes option in that it warns whenever the compiler decides to drop an attribute, not that the attribute is either unknown, used in a wrong place, etc. This warning is enabled by default.
Warn 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.

This warning is upgraded to an error by -pedantic-errors.

Warn when the indentation of the code does not reflect the block structure. Specifically, a warning is issued for "if", "else", "while", and "for" clauses with a guarded statement that does not use braces, followed by an unguarded statement with the same indentation.

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

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

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

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

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

The warning is not issued after a "#line" directive, since this typically indicates autogenerated code, and no assumptions can be made about the layout of the file that the directive references.

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

Warn 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);
Warn if an aggregate or union initializer is not fully bracketed. In the following example, the initializer for "a" is not fully bracketed, but that for "b" is fully bracketed.
int a[2][2] = { 0, 1, 2, 3 };
int b[2][2] = { { 0, 1 }, { 2, 3 } };

This warning is enabled by -Wall.

Warn 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.
This option 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.
Warn for calls to deallocation functions with pointer arguments returned from allocation functions for which the former isn't a suitable deallocator. A pair of functions can be associated as matching allocators and deallocators by use of attribute "malloc". Unless disabled by the -fno-builtin option the standard functions "calloc", "malloc", "realloc", and "free", as well as the corresponding forms of C++ "operator new" and "operator delete" are implicitly associated as matching allocators and deallocators. In the following example "mydealloc" is the deallocator for pointers returned from "myalloc".
void mydealloc (void*);

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

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

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

Option -Wmismatched-dealloc is included in -Wall.

Warn 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. The can usually be fixed by wrapping the macro in a do-while loop:

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

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

Warn 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 warn 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 warn for dangerous uses of the GNU extension to "?:" with omitted middle operand. When the condition in the "?": operator is a boolean expression, the omitted value is always 1. Often programmers expect it to be a value computed inside the conditional expression instead.

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

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

This warning is enabled by -Wall.

This warning warns when a value is moved to itself with "std::move". Such a "std::move" typically has no effect.
struct T {
...
};
void fn()
{
  T t;
  ...
  t = std::move (t);
}

This warning is enabled by -Wall.

Warn about code that may have undefined semantics because of violations of sequence point rules in the C and C++ standards.

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

It is not specified when between sequence points modifications to the values of objects take effect. Programs whose behavior depends on this have undefined behavior; the C and C++ standards specify that "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.". If a program breaks these rules, the results on any particular implementation are entirely unpredictable.

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

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

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

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

Do not warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns.
Warn about return statements without an expressions in functions which do not return "void". Also warn about a "return" statement with an expression in a function whose return type is "void", unless the expression type is also "void". As a GNU extension, the latter case is accepted without a warning unless -Wpedantic is used.

Attempting to use the return value of a non-"void" function other than "main" that flows off the end by reaching the closing curly brace that terminates the function is undefined.

This warning is specific to C and enabled by default. In C99 and later language dialects, it is treated as an error. It can be downgraded to a warning using -fpermissive (along with other warnings), or for just this warning, with -Wno-error=return-mismatch.

Warn whenever a function is defined with a return type that defaults to "int" (unless -Wimplicit-int is active, which takes precedence). Also warn if execution may reach the end of the function body, or if the function does not contain any return statement at all.

Attempting to use the return value of a non-"void" function other than "main" that flows off the end by reaching the closing curly brace that terminates the function is undefined.

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

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

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

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

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

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

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

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

Warn when "__sync_fetch_and_nand" and "__sync_nand_and_fetch" built-in functions are used. These functions changed semantics in GCC 4.4.
Warn when "-ftrivial-auto-var-init" cannot initialize the automatic variable. A common situation is an automatic variable that is declared between the controlling expression and the first case label of a "switch" statement.
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.

Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). This warning is enabled by -Wall.

To suppress this warning use the "unused" attribute.

This warning is also enabled by -Wunused, which is enabled by -Wall.

Warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by -Wall.
Warn whenever a label is declared but not used. This warning is enabled by -Wall.

To suppress this warning use the "unused" attribute.

Warn when a typedef locally defined in a function is not used. This warning is enabled by -Wall.
Warn whenever a function parameter is unused aside from its declaration. This option is not enabled by "-Wunused" unless "-Wextra" is also specified.

To suppress this warning use the "unused" attribute.

Do not warn if a caller of a function marked with attribute "warn_unused_result" does not use its return value. The default is -Wunused-result.
Warn whenever a local or static variable is unused aside from its declaration. This option implies -Wunused-const-variable=1 for C, but not for C++. This warning is enabled by -Wall.

To suppress this warning use the "unused" attribute.

Warn whenever a constant static variable is unused aside from its declaration.

To suppress this warning use the "unused" attribute.

Warn about unused static const variables defined in the main compilation unit, but not about static const variables declared in any header included.

-Wunused-const-variable=1 is enabled by either -Wunused-variable or -Wunused 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 "#define"s.

This warning level also warns for unused constant static variables in headers (excluding system headers). It is equivalent to the short form -Wunused-const-variable. This level must be explicitly requested in both C and C++ because it might be hard to clean up all headers included.
Warn whenever a statement computes a result that is explicitly not used. To suppress this warning cast the unused expression to "void". This includes an expression-statement or the left-hand side of a comma expression that contains no side effects. For example, an expression such as "x[i,j]" causes a warning, while "x[(void)i,j]" does not.

This warning is enabled by -Wall.

All the above -Wunused options combined, except those documented as needing to be specified explicitly.

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 and/or -Wunused-but-set-parameter.

-Wunused enables only -Wunused-const-variable=1 rather than -Wunused-const-variable, and only for C, not C++.

Warn about uses of pointers to dynamically allocated objects that have been rendered indeterminate by a call to a deallocation function. The warning is enabled at all optimization levels but may yield different results with optimization than without.
At level 1 the warning attempts to diagnose only unconditional uses of pointers made indeterminate by a deallocation call or a successful call to "realloc", regardless of whether or not the call resulted in an actual reallocation of memory. This includes double-"free" calls as well as uses in arithmetic and relational expressions. Although undefined, uses of indeterminate pointers in equality (or inequality) expressions are not diagnosed at this level.
At level 2, in addition to unconditional uses, the warning also diagnoses conditional uses of pointers made indeterminate by a deallocation call. As at level 2, uses in equality (or inequality) expressions are not diagnosed. For example, the second call to "free" in the following function is diagnosed at this level:
struct A { int refcount; void *data; };

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

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

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

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

Warn when an expression is cast to its own type. This warning does not occur when a class object is converted to a non-reference type as that is 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&&
}
Warn if an object with automatic or allocated storage duration is used without having been initialized. In C++, also warn if a non-static reference or non-static "const" member appears in a class without constructors.

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.

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

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.

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.

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.

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.

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.

Warn 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.
Do not warn about misuses of pragmas, such as incorrect parameters, invalid syntax, or conflicts between pragmas. See also -Wunknown-pragmas.
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.
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
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.

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.

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.

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.
Also warn about other cases where a comparison is simplified to a constant. For example: "abs (x) >= 0". This can only be simplified when signed integer overflow is undefined, because "abs (INT_MIN)" overflows to "INT_MIN", which is less than zero. -Wstrict-overflow (with no level) is the same as -Wstrict-overflow=2.
Also warn about other cases where a comparison is simplified. For example: "x + 1 > 1" is simplified to "x > 0".
Also warn about other simplifications not covered by the above cases. For example: "(x * 10) / 5" is simplified to "x * 2".
Also warn about cases where the compiler reduces the magnitude of a constant involved in a comparison. For example: "x + 2 > y" is simplified to "x + 1 >= y". This is reported only at the highest warning level because this simplification applies to many comparisons, so this warning level gives a very large number of false positives.
Warn for calls to "strcmp" and "strncmp" whose result is determined to be either zero or non-zero in tests for such equality owing to the length of one argument being greater than the size of the array the other argument is stored in (or the bound in the case of "strncmp"). Such calls could be mistakes. For example, the call to "strcmp" below is diagnosed because its result is necessarily non-zero irrespective of the contents of the array "a".
extern char a[4];
void f (char *d)
{
  strcpy (d, "string");
  ...
  if (0 == strcmp (a, d))   // cannot be true
    puts ("a and d are the same");
}

-Wstring-compare is enabled by -Wextra.

Warn for calls to string manipulation functions such as "memcpy" and "strcpy" that are determined to overflow the destination buffer. The optional argument is one greater than the type of Object Size Checking to perform to determine the size of the destination. The argument is meaningful only for functions that operate on character arrays but not for raw memory functions like "memcpy" which always make use of Object Size type-0. The option also warns for calls that specify a size in excess of the largest possible object or at most "SIZE_MAX / 2" bytes. The option produces the best results with optimization enabled but can detect a small subset of simple buffer overflows even without optimization in calls to the GCC built-in functions like "__builtin_memcpy" that correspond to the standard functions. In any case, the option warns about just a subset of buffer overflows detected by the corresponding overflow checking built-ins. For example, the option issues a warning for the "strcpy" call below because it copies at least 5 characters (the string "blue" including the terminating NUL) into the buffer of size 4.
enum Color { blue, purple, yellow };
const char* f (enum Color clr)
{
  static char buf [4];
  const char *str;
  switch (clr)
    {
      case blue: str = "blue"; break;
      case purple: str = "purple"; break;
      case yellow: str = "yellow"; break;
    }

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

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

The -Wstringop-overflow=1 option uses type-zero Object Size Checking to determine the sizes of destination objects. At this setting the option does not warn for writes past the end of subobjects of larger objects accessed by pointers unless the size of the largest surrounding object is known. When the destination may be one of several objects it is assumed to be the largest one of them. On Linux systems, when optimization is enabled at this setting the option warns for the same code as when the "_FORTIFY_SOURCE" macro is defined to a non-zero value.
The -Wstringop-overflow=2 option uses type-one Object Size Checking to determine the sizes of destination objects. At this setting the option warns about overflows when writing to members of the largest complete objects whose exact size is known. However, it does not warn for excessive writes to the same members of unknown objects referenced by pointers since they may point to arrays containing unknown numbers of elements. This is the default setting of the option.
The -Wstringop-overflow=3 option uses type-two Object Size Checking to determine the sizes of destination objects. At this setting the option 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.
The -Wstringop-overflow=4 option uses type-three Object Size Checking to determine the sizes of destination objects. At this setting the option warns about overflowing any data members, and when the destination is one of several objects it uses the size of the largest of them to decide whether to issue a warning. Similarly to -Wstringop-overflow=3 this setting of the option may result in warnings for benign code.
Warn for calls to string manipulation functions such as "memchr", or "strcpy" that are determined to read past the end of the source sequence.

Option -Wstringop-overread is enabled by default.

Do not warn for calls to bounded string manipulation functions such as "strncat", "strncpy", and "stpncpy" that may either truncate the copied string or leave the destination unchanged.

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

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

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

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

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

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

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

Warn about improper usages of flexible array members according to the level of the "strict_flex_array (level)" attribute attached to the trailing array field of a structure if it's available, otherwise according to the level of the option -fstrict-flex-arrays=level. "-Wstrict-flex-arrays" is effective only when level is greater than 0.

When level=1, warnings are issued for a trailing array reference of a structure that have 2 or more elements if the trailing array is referenced as a flexible array member.

When level=2, in addition to level=1, additional warnings are issued for a trailing one-element array reference of a structure if the array is referenced as a flexible array member.

When level=3, in addition to level=2, additional warnings are issued for a trailing zero-length array reference of a structure if the array is referenced as a flexible array member.

This option is more effective when -ftree-vrp is active (the default for -O2 and above) but some warnings may be diagnosed even without optimization.

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

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

Warn about functions that might be candidates for "cold" attribute. This is based on static detection and generally only warns about functions which always leads to a call to another "cold" function such as wrappers of C++ "throw" or fatal error reporting functions leading to "abort".
Warn about calls to allocation functions decorated with attribute "alloc_size" that specify insufficient size for the target type of the pointer the result is assigned to, including those to the built-in forms of the functions "aligned_alloc", "alloca", "calloc", "malloc", and "realloc".
Warn about calls to allocation functions decorated with attribute "alloc_size" that specify zero bytes, including those to the built-in forms of the functions "aligned_alloc", "alloca", "calloc", "malloc", and "realloc". Because the behavior of these functions when called with a zero size differs among implementations (and in the case of "realloc" has been deprecated) relying on it may result in subtle portability bugs and should be avoided.
Warn about calls to allocation functions decorated with attribute "alloc_size" with two arguments, which use "sizeof" operator as the earlier size argument and don't use it as the later size argument. This is a coding style warning. The first argument to "calloc" is documented to be number of elements in array, while the second argument is size of each element, so "calloc (n, sizeof (int))" is preferred over "calloc (sizeof (int), n)". If "sizeof" in the earlier argument and not the latter is intentional, the warning can be suppressed by using "calloc (sizeof (struct S) + 0, n)" or "calloc (1 * sizeof (struct S), 4)" or using "sizeof" in the later argument as well.
Warn 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.
Disable -Walloc-size-larger-than= warnings. The option is equivalent to -Walloc-size-larger-than=SIZE_MAX or larger.
This option warns on all uses of "alloca" in the source.
This option warns on calls to "alloca" with an integer argument whose value is either zero, or that is not bounded by a controlling predicate that limits its value to at most byte-size. It also warns for calls to "alloca" where the bound value is unknown. 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.

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.

Disable -Walloca-larger-than= warnings. The option is equivalent to -Walloca-larger-than=SIZE_MAX or larger.
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>
}
Warn about out of bounds subscripts or offsets into arrays. This warning is enabled by -Wall. It is more effective when -ftree-vrp is active (the default for -O2 and above) but a subset of instances are issued even without optimization.

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.

This is the default warning level of -Warray-bounds and is enabled by -Wall; higher levels are not, and must be explicitly requested.
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.
Warn about equality and relational comparisons between two operands of array type. This comparison was deprecated in C++20. For example:
int arr1[5];
int arr2[5];
bool same = arr1 == arr2;

-Warray-compare is enabled by -Wall.

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

If the first function declaration uses the array form for a parameter declaration, 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 or -Wstringop-overflow. At level 1, the warning diagnoses inconsistencies involving array parameters declared using the "T[static N]" form.

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

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

void g (void)
{
  int *p = (int *)malloc (1 * sizeof (int));
  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.

The short form of the option -Warray-parameter is equivalent to -Warray-parameter=2. The negative form -Wno-array-parameter is equivalent to -Warray-parameter=0.

Warn about declarations using the "alias" and similar attributes whose target is incompatible with the type of the alias.
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.
At this level -Wattribute-alias also diagnoses cases where the attributes of the alias declaration are more restrictive than the attributes applied to its target. These mismatches can potentially result in incorrect code generation. In other cases they may be benign and could be resolved simply by adding the missing attribute to the target. For comparison, see the -Wmissing-attributes option, which controls diagnostics when the alias declaration is less restrictive than the target, rather than more restrictive.

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

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

Warn about possibly misleading UTF-8 bidirectional control characters in comments, string literals, character constants, and identifiers. Such characters can change left-to-right writing direction into right-to-left (and vice versa), which can cause confusion between the logical order and visual order. This may be dangerous; for instance, it may seem that a piece of code is not commented out, whereas it in fact is.

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

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

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

This warning is enabled by -Wall.

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

This warning is enabled by -Wall.

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

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

int i = x ? *p : *p;
Warn about duplicated conditions in an if-else-if chain. For instance, warn for the following code:
if (p->q != NULL) { ... }
else if (p->q != NULL) { ... }
Warn when the __builtin_frame_address or __builtin_return_address is called with an argument greater than 0. Such calls may return indeterminate values or crash the program. The warning is included in -Wall.
Do not warn if type qualifiers on pointers are being discarded. Typically, the compiler warns if a "const char *" variable is passed to a function that takes a "char *" parameter. This option can be used to suppress such a warning.
Do not warn if type qualifiers on arrays which are pointer targets are being discarded. Typically, the compiler warns if a "const int (*)[]" variable is passed to a function that takes a "int (*)[]" parameter. This option can be used to suppress such a warning.
Do not warn when there is a conversion between pointers that have incompatible types. This warning is for cases not covered by -Wno-pointer-sign, which warns for pointer argument passing or assignment with different signedness.

By default, in C99 and later dialects of C, GCC treats this issue as an error. The error can be downgraded to a warning using -fpermissive (along with certain other errors), or for this error alone, with -Wno-error=incompatible-pointer-types.

This warning is upgraded to an error by -pedantic-errors.

Do not warn about incompatible integer to pointer and pointer to integer conversions. This warning is about implicit conversions; for explicit conversions the warnings -Wno-int-to-pointer-cast and -Wno-pointer-to-int-cast may be used.

By default, in C99 and later dialects of C, GCC treats this issue as an error. The error can be downgraded to a warning using -fpermissive (along with certain other errors), or for this error alone, with -Wno-error=int-conversion.

This warning is upgraded to an error by -pedantic-errors.

Warn about accesses to elements of zero-length array members that might overlap other members of the same object. Declaring interior zero-length arrays is discouraged because accesses to them are undefined.

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

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

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

Option -Wzero-length-bounds is enabled by -Warray-bounds.

Do not warn about compile-time integer division by zero. Floating-point division by zero is not warned about, as it can be a legitimate way of obtaining infinities and NaNs.
Print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed, on the assumption that they usually do not 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 in conjunction with this option does not warn about unknown pragmas in system headers---for that, -Wunknown-pragmas must also be used.
Warn if a self-comparison always evaluates to true or false. This warning detects various mistakes such as:
int i = 1;
...
if (i > i) { ... }

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

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

will always be false.

This warning is enabled by -Wall.

Warn about trampolines generated for pointers to nested functions. A trampoline is a small piece of data or 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. For some targets, it is made up of data only and thus requires no special treatment. But, for most targets, it is made up of code and thus requires the stack to be made executable in order for the program to work properly.
Warn if floating-point values are used in equality comparisons.

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

Warn about certain constructs that behave differently in traditional and ISO C. Also warn about ISO C constructs that have no traditional C equivalent, and/or problematic constructs that should be avoided.
  • Macro parameters that appear within string literals in the macro body. In traditional C macro replacement takes place within string literals, but in ISO C it does not.
  • In traditional C, some preprocessor directives did not exist. Traditional preprocessors only considered a line to be a directive if the # appeared in column 1 on the line. Therefore -Wtraditional warns about directives that traditional C understands but ignores because the # does not appear as the first character on the line. It also suggests you hide directives like "#pragma" not understood by traditional C by indenting them. Some traditional implementations do not recognize "#elif", so this option suggests avoiding it altogether.
  • A function-like macro that appears without arguments.
  • The unary plus operator.
  • The U integer constant suffix, or the F or L floating-point constant suffixes. (Traditional C does support the L suffix on integer constants.) Note, these suffixes appear in macros defined in the system headers of most modern systems, e.g. the _MIN/_MAX macros in "<limits.h>". Use of these macros in user code might normally lead to spurious warnings, however GCC's integrated preprocessor has enough context to avoid warning in these cases.
  • A function declared external in one block and then used after the end of the block.
  • A "switch" statement has an operand of type "long".
  • A non-"static" function declaration follows a "static" one. This construct is not accepted by some traditional C compilers.
  • The ISO type of an integer constant has a different width or signedness from its traditional type. This warning is only issued if the base of the constant is ten. I.e. hexadecimal or octal values, which typically represent bit patterns, are not warned about.
  • Usage of ISO string concatenation is detected.
  • Initialization of automatic aggregates.
  • Identifier conflicts with labels. Traditional C lacks a separate namespace for labels.
  • Initialization of unions. If the initializer is zero, the warning is omitted. This is done under the assumption that the zero initializer in user code appears conditioned on e.g. "__STDC__" to avoid missing initializer warnings and relies on default initialization to zero in the traditional C case.
  • Conversions by prototypes between fixed/floating-point values and vice versa. The absence of these prototypes when compiling with traditional C causes serious problems. This is a subset of the possible conversion warnings; for the full set use -Wtraditional-conversion.
  • Use of ISO C style function definitions. This warning intentionally is not issued for prototype declarations or variadic functions because these ISO C features appear in your code when using libiberty's traditional C compatibility macros, "PARAMS" and "VPARAMS". This warning is also bypassed for nested functions because that feature is already a GCC extension and thus not relevant to traditional C compatibility.
Warn 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.
Warn 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.

This warning is upgraded to an error by -pedantic-errors.

Warn 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.
Do not warn whenever a local variable shadows an instance variable in an Objective-C method.
Warn for any shadowing. Same as -Wshadow.
Warn when a local variable shadows another local variable or parameter.
Warn when a local variable shadows another local variable or parameter whose type is compatible with that of the shadowing variable. In C++, type compatibility here means the type of the shadowing variable can be converted to that of the shadowed variable. The creation of this flag (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.

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

Disable -Wlarger-than= warnings. The option is equivalent to -Wlarger-than=SIZE_MAX or larger.
Warn 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.
Disable -Wframe-larger-than= warnings. The option is equivalent to -Wframe-larger-than=SIZE_MAX or larger.
Warn 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.

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

Disable -Wstack-usage= warnings. The option is equivalent to -Wstack-usage=SIZE_MAX or larger.
Warn 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.
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.
Warn 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.

This warning is upgraded to an error by -pedantic-errors.

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.

Disable warnings about unsupported features in ThreadSanitizer.

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

Warn 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.
Warn 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.
Warn whenever a comment-start sequence /* appears in a /* comment, or whenever a backslash-newline appears in a // comment. This warning is enabled by -Wall.
Warn 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.

Warn if an undefined identifier is evaluated in an "#if" directive. Such identifiers are replaced with zero.
Warn 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.
Warn 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.

Note: If a macro is actually used, but only used in skipped conditional blocks, then the preprocessor reports it as unused. To avoid the warning in such a 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
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.

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.
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__".
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__".
Warn about features not present in ISO C11, but present in ISO C23. 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 name -Wc11-c2x-compat is deprecated.

When not compiling in C23 mode, these warnings are upgraded to errors by -pedantic-errors.

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.
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.
Warn about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014. This warning is enabled by -Wall.
Warn about C++ constructs whose meaning differs between ISO C++ 2014 and ISO C++ 2017. This warning is enabled by -Wall.
Warn about C++ constructs whose meaning differs between ISO C++ 2017 and ISO C++ 2020. This warning is enabled by -Wall.
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.
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.
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.
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.
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.
Do not warn about C++26 constructs in code being compiled using an older C++ standard. Even without this option, some C++26 constructs will only be diagnosed if -Wpedantic is used.
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 *".

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';
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.
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.
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.
Warn when a cast to reference type does not involve a user-defined conversion that the programmer might expect to be called.
struct A { operator const int&(); } a;
auto r = (int&)a; // warning

This warning is enabled by default.

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.

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

This warning is upgraded to an error by -pedantic-errors in C++11 mode or later.

Warn for variables that might be changed by "longjmp" or "vfork". This warning is also enabled by -Wextra.
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.

Warn if pointers of distinct types are compared without a cast. This warning is enabled by default.
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.

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.

Warn about uses of pointers (or C++ references) to objects with automatic storage duration after their lifetime has ended. This includes local variables declared in nested blocks, compound literals and other unnamed temporary objects. In addition, warn about storing the address of such objects in escaped pointers. The warning is enabled at all optimization levels but may yield different results with optimization than without.
At level 1, the warning diagnoses only unconditional uses of dangling pointers.
At level 2, in addition to unconditional uses the warning also diagnoses conditional uses of dangling pointers.

The short form -Wdangling-pointer is equivalent to -Wdangling-pointer=2, while -Wno-dangling-pointer and -Wdangling-pointer=0 have the same effect of disabling the warnings. -Wdangling-pointer=2 is included in -Wall.

This example triggers the warning at level 1; the address of the unnamed temporary is unconditionally referenced outside of its scope.

char f (char c1, char c2, char c3)
{
  char *p;
  {
    p = (char[]) { c1, c2, c3 };
  }
  // warning: using dangling pointer 'p' to an unnamed temporary
  return *p;
}

In the following function the store of the address of the local variable "x" in the escaped pointer *p triggers the warning at level 1.

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

In this example, the array a is out of scope when the pointer s is used. Since the code that sets "s" is conditional, the warning triggers at level 2.

extern void frob (const char *);
void h (char *s)
{
  if (!s)
    {
      char a[12] = "tmpname";
      s = a;
    }
  // warning: dangling pointer 's' to 'a' may be used
  frob (s);
}
Warn when macros "__TIME__", "__DATE__" or "__TIMESTAMP__" are encountered as they might prevent bit-wise-identical reproducible compilations.
Warn if an empty body occurs in an "if", "else" or "do while" statement. This warning is also enabled by -Wextra.
Do not warn about stray tokens after "#else" and "#endif".
Warn about a comparison between values of different enumerated types. In C++ enumerated type mismatches in conditional expressions are also diagnosed and the warning is enabled by default. In C this warning is enabled by -Wall.
Warn when a value of enumerated type is implicitly converted to a different enumerated type. This warning is enabled by -Wextra in C.
Warn 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.

Warn if a "goto" statement or a "switch" statement jumps forward across the initialization of a variable, or jumps backward to a label after the variable has been initialized. 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.

Warn 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.
Warn for implicit conversions that may change the sign of an integer value, like assigning a signed integer expression to an unsigned integer variable. An explicit cast silences the warning. In C, this option is enabled also by -Wconversion.
Warn when a structure containing a C99 flexible array member as the last field is not at the end of another structure. This warning warns e.g. about
struct flex  { int length; char data[]; };
struct mid_flex { int m; struct flex flex_data; int n; };
Warn 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.
Do not warn on suspicious constructs involving reverse scalar storage order.
Warn about divisions of two sizeof operators when the first one is applied to an array and the divisor does not equal the size of the array element. In 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.

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

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

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.
Warn 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) { ... }
Warn 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) { ... }

It is possible to suppress the warning by wrapping the LHS into parentheses:

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

This warning is enabled by -Wall.

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

Warnings about ill-formed uses of standard attributes are upgraded to errors by -pedantic-errors.

Additionally, using -Wno-attributes=, it is possible to suppress warnings about unknown scoped attributes (in C++11 and C23). 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.

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);
}
Do not warn if certain built-in macros are redefined. This suppresses warnings for redefinition of "__TIMESTAMP__", "__TIME__", "__DATE__", "__FILE__", and "__BASE_FILE__".
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.)
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.
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 C23 mode, because it is equivalent to (void) in that case, but is considered an old-style definition for older standards.
A function parameter is declared without a type specifier in K&R-style functions:
void foo(bar) { }

This warning is also enabled by -Wextra.

Do not warn if a function declaration contains a parameter name without a type. Such function declarations do not provide a function prototype and prevent most type checking in function calls.

This warning is enabled by default. In C99 and later dialects of C, it is treated as an error. The error can be downgraded to a warning using -fpermissive (along with certain other errors), or for this error alone, with -Wno-error=declaration-missing-parameter-type.

This warning is upgraded to an error by -pedantic-errors.

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++.
Warn if a global variable is defined without a previous declaration. Use this option to detect global variables that do not have a matching extern declaration in a header file.
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.
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 };

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

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.

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.

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.
In ISO C and ISO C++, two identifiers are different if they are different sequences of characters. However, sometimes when characters outside the basic ASCII character set are used, you can have two different character sequences that look the same. To avoid confusion, the ISO 10646 standard sets out some normalization rules which when applied ensure that two sequences that look the same are turned into the same sequence. GCC can warn you if you are using identifiers that have not been normalized; this option controls that warning.

There are four levels of warning supported by GCC. The default is -Wnormalized=nfc, which warns about any identifier that is not in the ISO 10646 "C" normalized form, NFC. NFC is the recommended form for most uses. It is equivalent to -Wnormalized.

Unfortunately, there are some characters allowed in identifiers by ISO C and ISO C++ that, when turned into NFC, are not allowed in identifiers. That is, there's no way to use these symbols in portable ISO C or C++ and have all your identifiers in NFC. -Wnormalized=id suppresses the warning for these characters. It is hoped that future versions of the standards involved will correct this, which is why this option is not the default.

You can switch the warning off for all characters by writing -Wnormalized=none or -Wno-normalized. You should only do this if you are using some other normalization scheme (like "D"), because otherwise you can easily create bugs that are literally impossible to see.

Some characters in ISO 10646 have distinct meanings but look identical in some fonts or display methodologies, especially once formatting has been applied. For instance "\u207F", "SUPERSCRIPT LATIN SMALL LETTER N", displays just like a regular "n" that has been placed in a superscript. ISO 10646 defines the NFKC normalization scheme to convert all these into a standard form as well, and GCC warns if your code is not in NFKC if you use -Wnormalized=nfkc. This warning is comparable to warning about every identifier that contains the letter O because it might be confused with the digit 0, and so is not the default, but may be useful as a local coding convention if the programming environment cannot be fixed to display these characters distinctly.

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.
Do not warn about usage of deprecated features.
Do not warn about uses of functions, variables, and types marked as deprecated by using the "deprecated" attribute.
Do not warn about compile-time overflow in constant expressions.
Warn about One Definition Rule violations during link-time optimization. Enabled by default.
Warn about potentially suboptimal choices related to OpenACC parallelism.
Warn about suspicious OpenMP code.
Warn if the vectorizer cost model overrides the OpenMP simd directive set by user. The -fsimd-cost-model=unlimited option can be used to relax the cost model.
Warn if an initialized field without side effects is overridden when using designated initializers.

This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-override-init.

Do not warn if an initialized field with side effects is overridden when using designated initializers. This warning is enabled by default.
Warn if a structure is given the packed attribute, but the packed attribute has no effect on the layout or size of the structure. Such structures may be mis-aligned for little benefit. For instance, in this code, the variable "f.x" in "struct bar" is misaligned even though "struct bar" does not itself have the packed attribute:
struct foo {
  int x;
  char a, b, c, d;
} __attribute__((packed));
struct bar {
  char z;
  struct foo f;
};
The 4.1, 4.2 and 4.3 series of GCC ignore the "packed" attribute on bit-fields of type "char". This was fixed in GCC 4.4 but the change can lead to differences in the structure layout. GCC informs you when the offset of such a field has changed in GCC 4.4. For example there is no longer a 4-bit padding between field "a" and "b" in this structure:
struct foo
{
  char a:4;
  char b:8;
} __attribute__ ((packed));

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

Warn if a structure field with explicitly specified alignment in a packed struct or union is misaligned. For example, a warning will be issued on "struct S", like, "warning: alignment 1 of 'struct S' is less than 8", in this code:
struct __attribute__ ((aligned (8))) S8 { char a[8]; };
struct __attribute__ ((packed)) S {
  struct S8 s8;
};

This warning is enabled by -Wall.

Warn if padding is included in a structure, either to align an element of the structure or to align the whole structure. Sometimes when this happens it is possible to rearrange the fields of the structure to reduce the padding and so make the structure smaller.
Warn if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing.
Warn when an object referenced by a "restrict"-qualified parameter (or, in C++, a "__restrict"-qualified parameter) is aliased by another argument, or when copies between such objects overlap. For example, the call to the "strcpy" function below attempts to truncate the string by replacing its initial characters with the last four. However, because the call writes the terminating NUL into "a[4]", the copies overlap and the call is diagnosed.
void foo (void)
{
  char a[] = "abcd1234";
  strcpy (a, a + 4);
  ...
}

The -Wrestrict option detects some instances of simple overlap even without optimization but works best at -O2 and above. It is included in -Wall.

Warn if an "extern" declaration is encountered within a function.
Warn if a function that is declared as inline cannot be inlined. Even with this option, the compiler does not warn about failures to inline functions declared in system headers.

The compiler uses a variety of heuristics to determine whether or not to inline a function. For example, the compiler takes into account the size of the function being inlined and the amount of inlining that has already been done in the current function. Therefore, seemingly insignificant changes in the source program can cause the warnings produced by -Winline to appear or disappear.

Warn about use of C++17 "std::hardware_destructive_interference_size" without specifying its value with --param destructive-interference-size. Also warn about questionable values for that option.

This variable is intended to be used for controlling class layout, to avoid false sharing in concurrent code:

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

Here one and two are intended to be far enough apart that stores to one won't require accesses to the other to reload the cache line.

By default, --param destructive-interference-size and --param constructive-interference-size are set based on the current -mtune option, typically to the L1 cache line size for the particular target CPU, sometimes to a range if tuning for a generic target. So all translation units that depend on ABI compatibility for the use of these variables must be compiled with the same -mtune (or -mcpu).

If ABI stability is important, such as if 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 are confident that your use of the variable does not affect ABI outside a single build of your project, you can turn off the warning with -Wno-interference-size.

Warn for suspicious use of integer values where boolean values are expected, such as conditional expressions (?:) using non-boolean integer constants in boolean context, like "if (a <= b ? 2 : 3)". Or left shifting of signed integers in boolean context, like "for (a = 0; 1 << a; a++);". Likewise for all kinds of multiplications regardless of the data type. This warning is enabled by -Wall.
Suppress 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.
Suppress warnings from casts from a pointer to an integer type of a different size.
Warn if a precompiled header is found in the search path but cannot be used.
Warn if an invalid UTF-8 character is found. This warning is on by default for C++23 if -finput-charset=UTF-8 is used and turned into error with -pedantic-errors.
Don't diagnose invalid forms of delimited or named escape sequences which are treated as separate tokens. Wunicode is enabled by default.
Warn if "long long" type is used. This is enabled by either -Wpedantic or -Wtraditional in ISO C90 and C++98 modes. To inhibit the warning messages, use -Wno-long-long.

This warning is upgraded to an error by -pedantic-errors.

Warn if variadic macros are used in ISO C90 mode, or if the GNU alternate syntax is used in ISO C99 mode. This is enabled by either -Wpedantic or -Wtraditional. To inhibit the warning messages, use -Wno-variadic-macros.
Do not warn upon questionable usage of the macros used to handle variable arguments like "va_start". These warnings are enabled by default.
Warn if vector operation is not implemented via SIMD capabilities of the architecture. Mainly useful for the performance tuning. Vector operation can be implemented "piecewise", which means that the scalar operation is performed on every vector element; "in parallel", which means that the vector operation is implemented using scalars of wider type, which normally is more performance efficient; and "as a single scalar", which means that vector fits into a scalar type.
Warn if a variable-length array is used in the code. -Wno-vla prevents the -Wpedantic warning of the variable-length array.

This warning is upgraded to an error by -pedantic-errors.

If this option is used, the compiler warns for declarations of variable-length arrays whose size is either unbounded, or bounded by an argument that allows the array size to exceed byte-size bytes. This is similar to how -Walloca-larger-than=byte-size works, but with variable-length arrays.

Note that GCC may optimize small variable-length arrays of a known value into plain arrays, so this warning may not get triggered for such arrays.

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

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

Disable -Wvla-larger-than= warnings. The option is equivalent to -Wvla-larger-than=SIZE_MAX or larger.
Warn about redeclarations of functions involving arguments of Variable Length Array types of inconsistent kinds or forms, and enable the detection of out-of-bounds accesses to such parameters by warnings such as -Warray-bounds.

If the first function declaration uses the VLA form the bound specified in the array is assumed to be the minimum number of elements expected to be provided in calls to the function and the maximum number of elements accessed by it. Failing to provide arguments of sufficient size or accessing more than the maximum number of elements may be diagnosed.

For example, the warning triggers for the following redeclarations because the first one allows an array of any size to be passed to "f" while the second one specifies that the array argument must have at least "n" elements. In addition, calling "f" with the associated VLA bound parameter in excess of the actual VLA bound triggers a warning as well.

void f (int n, int[n]);
// 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. The -Warray-parameter option triggers warnings for similar problems involving ordinary array arguments.

Warn if a register variable is declared volatile. The volatile modifier does not inhibit all optimizations that may eliminate reads and/or writes to register variables. This warning is enabled by -Wall.
Disable warnings about uses of "^", the exclusive or operator, where it appears the code meant exponentiation. Specifically, the warning occurs when the left-hand side is the decimal constant 2 or 10 and the right-hand side is also a decimal constant.

In C and C++, "^" means exclusive or, whereas in some other languages (e.g. TeX and some versions of BASIC) it means exponentiation.

This warning can be silenced by converting one of the operands to hexadecimal as well as by compiling with -Wno-xor-used-as-pow.

Warn if a requested optimization pass is disabled. This warning does not generally indicate that there is anything wrong with your code; it merely indicates that GCC's optimizers are unable to handle the code effectively. Often, the problem is that your code is too big or too complex; GCC refuses to optimize programs when the optimization itself is likely to take inordinate amounts of time.
Warn for pointer argument passing or assignment with different signedness. This option is only supported for C and Objective-C. It is implied by -Wall and by -Wpedantic, which can be disabled with -Wno-pointer-sign.

This warning is upgraded to an error by -pedantic-errors.

This option is only active when -fstack-protector is active. It warns about functions that are not protected against stack smashing.
Warn about string constants that are longer than the "minimum maximum" length specified in the C standard. Modern compilers generally allow string constants that are much longer than the standard's minimum limit, but very portable programs should avoid using longer strings.

The limit applies after string constant concatenation, and does not count the trailing NUL. In C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 does not specify a normative minimum maximum, so we do not diagnose overlength strings in C++.

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

Issue a warning for any floating constant that does not have a suffix. When used together with -Wsystem-headers it warns about such constants in system header files. This can be useful when preparing code to use with the "FLOAT_CONST_DECIMAL64" pragma from the decimal floating-point extension to C99.
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.
Suppress warnings when a positional initializer is used to initialize a structure that has been marked with the "designated_init" attribute.

This option enables an static analysis of program flow which looks for "interesting" interprocedural paths through the code, and issues warnings for problems found on them.

This analysis is much more expensive than other GCC warnings.

In technical terms, it performs coverage-guided symbolic execution of the code being compiled. It is neither sound nor complete: it can have false positives and false negatives. It is a bug-finding tool, rather than a tool for proving program correctness.

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

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-loop -Wanalyzer-infinite-recursion -Wanalyzer-jump-through-null -Wanalyzer-malloc-leak -Wanalyzer-mismatching-deallocation -Wanalyzer-null-argument -Wanalyzer-null-dereference -Wanalyzer-out-of-bounds -Wanalyzer-overlapping-buffers -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-tainted-allocation-size -Wanalyzer-tainted-array-index -Wanalyzer-tainted-assertion -Wanalyzer-tainted-divisor -Wanalyzer-tainted-offset -Wanalyzer-tainted-size -Wanalyzer-undefined-behavior-strtok -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.

If -fanalyzer is enabled, the analyzer uses various heuristics to attempt to track the state of memory, but these can be defeated by sufficiently complicated code.

By default, the analysis silently stops tracking values of expressions if they exceed the threshold defined by --param analyzer-max-svalue-depth=value, and falls back to an imprecise representation for such expressions. The -Wanalyzer-symbol-too-complex option warns if this occurs.

If -fanalyzer is enabled, the analyzer uses various heuristics to attempt to explore the control flow and data flow in the program, but these can be defeated by sufficiently complicated code.

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

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

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

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

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.

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.

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

This diagnostic warns for paths through the code in which a "FILE *" can have "fclose" called on it more than once.

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

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

This diagnostic warns for paths through the code in which a pointer can have a deallocator called on it more than once, either "free", or a deallocator referenced by attribute "malloc".

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

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

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

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

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

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.

This diagnostic also warns for code paths in a which a function with attribute "fd_arg_read (N)" is called with a file descriptor opened with "O_WRONLY" at referenced argument "N" or a function with attribute "fd_arg_write (N)" is called with a file descriptor opened with "O_RDONLY" at referenced argument N.

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-fd-double-close to disable it.

This diagnostic warns for paths through code in which a file descriptor can be closed more than once.

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

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

This diagnostic warns for paths through code in which an open file descriptor is leaked.

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

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-fd-phase-mismatch to disable it.

This diagnostic warns for paths through code in which an operation is attempted in the wrong phase of a file descriptor's lifetime. For example, it will warn on attempts to call "accept" on a stream socket that has not yet had "listen" successfully called on it.

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

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-fd-type-mismatch to disable it.

This diagnostic warns for paths through code in which an operation is attempted on the wrong type of file descriptor. For example, it will warn on attempts to use socket operations on a file descriptor obtained via "open", or when attempting to use a stream socket operation on a datagram socket.

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

This diagnostic warns for paths through code in which a read or write is called on a closed file descriptor.

This diagnostic also warns for paths through code in which a function with attribute "fd_arg (N)" or "fd_arg_read (N)" or "fd_arg_write (N)" is called with a closed file descriptor at referenced argument "N".

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-fd-use-without-check to disable it.

This diagnostic warns for paths through code in which a file descriptor is used without being checked for validity.

This diagnostic also warns for paths through code in which a function with attribute "fd_arg (N)" or "fd_arg_read (N)" or "fd_arg_write (N)" is called with a file descriptor, at referenced argument "N", without being checked for validity.

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

This diagnostic warns for paths through the code in which a "<stdio.h>" "FILE *" stream object is leaked.

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

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

This diagnostic warns for paths through the code in which "free" is called on a non-heap pointer (e.g. an on-stack buffer, or a global).

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

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-imprecise-fp-arithmetic to disable it.

This diagnostic warns for paths through the code in which floating-point arithmetic is used in locations where precise computation is needed. This diagnostic only warns on use of floating-point operands inside the calculation of an allocation size at the moment.

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

This diagnostics warns for paths through the code which appear to lead to an infinite loop.

Specifically, the analyzer will issue this warning when it "sees" a loop in which:

  • no externally-visible work could be being done within the loop
  • there is no way to escape from the loop
  • the analyzer is sufficiently confident about the program state throughout the loop to know that the above are true

One way for this warning to be emitted is when there is an execution path through a loop for which taking the path on one iteration implies that the same path will be taken on all subsequent iterations.

For example, consider:

while (1)
  {
    char opcode = *cpu_state.pc;
    switch (opcode)
     {
     case OPCODE_FOO:
       handle_opcode_foo (&cpu_state);
       break;
     case OPCODE_BAR:
       handle_opcode_bar (&cpu_state);
       break;
     }
  }

The analyzer will complain for the above case because if "opcode" ever matches none of the cases, the "switch" will follow the implicit "default" case, making the body of the loop be a "no-op" with "cpu_state.pc" unchanged, and thus using the same value of "opcode" on all subseqent iterations, leading to an infinite loop.

See CWE-835: Loop with Unreachable Exit Condition ('Infinite Loop') ("https://cwe.mitre.org/data/definitions/835.html").

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

This diagnostics warns for paths through the code which appear to lead to infinite recursion.

Specifically, when the analyzer "sees" a recursive call, it will compare the state of memory at the entry to the new frame with that at the entry to the previous frame of that function on the stack. The warning is issued if nothing in memory appears to be changing; any changes observed to parameters or globals are assumed to lead to termination of the recursion and thus suppress the warning.

This diagnostic is likely to miss cases of infinite recursion that are convered to iteration by the optimizer before the analyzer "sees" them. Hence optimization should be disabled when attempting to trigger this diagnostic.

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

See CWE-674: Uncontrolled Recursion ("https://cwe.mitre.org/data/definitions/674.html").

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

This diagnostic warns for paths through the code in which a "NULL" function pointer is called.

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

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

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

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

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

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

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-out-of-bounds to disable it.

This diagnostic warns for paths through the code in which a buffer is definitely read or written out-of-bounds. The diagnostic applies for cases where the analyzer is able to determine a constant offset and for accesses past the end of a buffer, also a constant capacity. Further, the diagnostic does limited checking for accesses past the end when the offset as well as the capacity is symbolic.

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

For cases where the analyzer is able, it will emit a text art diagram visualizing the spatial relationship between the memory region that the analyzer predicts would be accessed, versus the range of memory that is valid to access: whether they overlap, are touching, are close or far apart; which one is before or after in memory, the relative sizes involved, the direction of the access (read vs write), and, in some cases, the values of data involved. This diagram can be suppressed using -fdiagnostics-text-art-charset=none.

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

This diagnostic warns for paths through the code in which overlapping buffers are passed to an API for which the behavior on such buffers is undefined.

Specifically, the diagnostic occurs on calls to the following functions

*<"memcpy">
*<"strcat">
*<"strcpy">

for cases where the buffers are known to overlap.

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

This diagnostic warns for paths through the code in which a possibly-NULL value is passed to a function argument marked with "__attribute__((nonnull))" as requiring a non-NULL value.

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

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

This diagnostic warns for paths through the code in which a possibly-NULL value is dereferenced.

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

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

This diagnostic warns for paths through the code in which a value known to be NULL is passed to a function argument marked with "__attribute__((nonnull))" as requiring a non-NULL value.

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

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

This diagnostic warns for paths through the code in which a value known to be NULL is dereferenced.

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

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-putenv-of-auto-var to disable it.

This diagnostic warns for paths through the code in which a call to "putenv" is passed a pointer to an automatic variable or an on-stack buffer.

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

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

This diagnostic warns for paths through the code in which a shift is attempted with a negative count. It is analogous to the -Wshift-count-negative diagnostic implemented in the C/C++ front ends, but is implemented based on analyzing interprocedural paths, rather than merely parsing the syntax tree. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings.

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

This diagnostic warns for paths through the code in which a shift is attempted with a count greater than or equal to the precision of the operand's type. It is analogous to the -Wshift-count-overflow diagnostic implemented in the C/C++ front ends, but is implemented based on analyzing interprocedural paths, rather than merely parsing the syntax tree. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings.

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

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

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

This warning requires -fanalyzer which enables it; use -Wno-analyzer-tainted-allocation-size to disable it.

This diagnostic warns for paths through the code in which a value that could be under an attacker's control is used as the size of an allocation without being sanitized, so that 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").

This warning requires -fanalyzer which enables it; use -Wno-analyzer-tainted-assertion to disable it.

This diagnostic warns for paths through the code in which a value that could be under an attacker's control is used as part of a condition without being first sanitized, and that condition guards a call to a function marked with attribute "noreturn" (such as the function "__builtin_unreachable"). Such functions typically indicate abnormal termination of the program, such as for 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, such as by defining "NDEBUG", an attacker could inject data that subverts the process, since it presumably violates a precondition that is being assumed by the code.

Note that when assertion-checking is disabled, the assertions are typically removed by the preprocessor before the analyzer has a chance to "see" them, so this diagnostic can only generate warnings on builds in which assertion-checking is enabled.

For the purpose of this warning, any function marked with attribute "noreturn" is considered as a possible assertion failure handler, including "__builtin_unreachable". Note that these functions are sometimes removed by the optimizer before the analyzer "sees" them. Hence optimization should be disabled when attempting to trigger this diagnostic.

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

The warning can also report problematic constructions such as

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

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

despite the above not being an assertion failure, strictly speaking.

This warning requires -fanalyzer which enables it; use -Wno-analyzer-tainted-array-index to disable it.

This diagnostic warns for paths through the code in which a value that could be under an attacker's control is used as the index of an array access without being sanitized, so that 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").

This warning requires -fanalyzer which enables it; use -Wno-analyzer-tainted-divisor to disable it.

This diagnostic warns for paths through the code in which a value that could be under an attacker's control is used as the divisor in a division or modulus operation without being sanitized, so that an attacker could inject a division-by-zero.

See CWE-369: Divide By Zero ("https://cwe.mitre.org/data/definitions/369.html").

This warning requires -fanalyzer which enables it; use -Wno-analyzer-tainted-offset to disable it.

This diagnostic warns for paths through the code in which a value that could be under an attacker's control is used as a pointer offset without being sanitized, so that 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").

This warning requires -fanalyzer which enables it; use -Wno-analyzer-tainted-size to disable it.

This diagnostic warns for paths through the code in which a value that could be under an attacker's control is used as the size of an operation such as "memset" without being sanitized, so that 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").

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-undefined-behavior-strtok to disable it.

This diagnostic warns for paths through the code in which a call is made to "strtok" with undefined behavior.

Specifically, passing NULL as the first parameter for the initial call to "strtok" within a process has undefined behavior.

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

This diagnostic warns for paths through the code in which a function known to be async-signal-unsafe (such as "fprintf") is called from a signal handler.

See CWE-479: Signal Handler Use of a Non-reentrant Function ("https://cwe.mitre.org/data/definitions/479.html").

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

This diagnostic warns for paths through the code in which a pointer is used after a deallocator is called on it: either "free", or a deallocator referenced by attribute "malloc".

See CWE-416: Use After Free ("https://cwe.mitre.org/data/definitions/416.html").

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

This diagnostic warns for paths through the code in which a pointer is dereferenced that points to a variable in a stale stack frame.

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-va-arg-type-mismatch to disable it.

This diagnostic warns for interprocedural paths through the code for which the analyzer detects an attempt to use "va_arg" to extract a value passed to a variadic call, but uses a type that does not match that of the expression passed to the call.

See CWE-686: Function Call With Incorrect Argument Type ("https://cwe.mitre.org/data/definitions/686.html").

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-va-list-exhausted to disable it.

This diagnostic warns for interprocedural paths through the code for which the analyzer detects an attempt to use "va_arg" to access the next value passed to a variadic call, but all of the values in the "va_list" have already been consumed.

See CWE-685: Function Call With Incorrect Number of Arguments ("https://cwe.mitre.org/data/definitions/685.html").

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

This diagnostic warns for interprocedural paths through the code for which the analyzer detects that "va_start" or "va_copy" has been called on a "va_list" without a corresponding call to "va_end".

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

This diagnostic warns for interprocedural paths through the code for which the analyzer detects an attempt to use a "va_list" after "va_end" has been called on it. "va_list".

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

This diagnostic warns for paths through the code in which the analyzer detects an attempt to write through a pointer to a "const" object. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings.

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

This diagnostic warns for paths through the code in which the analyzer detects an attempt to write through a pointer to a string literal. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings.

This warning requires -fanalyzer, which enables it; use -Wno-analyzer-use-of-uninitialized-value to disable it.

This diagnostic 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", @item "__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">

of the following functions for working with file descriptors:

*<"open">
*<"close">
*<"creat">
*<"dup", "dup2" and "dup3">
*<"isatty">
*<"pipe", and "pipe2">
*<"read">
*<"write">
*<"socket", "bind", "listen", "accept", and "connect">

of the following functions for working with "<stdio.h>" streams:

*<The built-in functions "__builtin_fprintf",>
"__builtin_fprintf_unlocked", "__builtin_fputc", "__builtin_fputc_unlocked", "__builtin_fputs", "__builtin_fputs_unlocked", "__builtin_fwrite", "__builtin_fwrite_unlocked", "__builtin_printf", "__builtin_printf_unlocked", "__builtin_putc", "__builtin_putchar", "__builtin_putchar_unlocked", "__builtin_putc_unlocked", "__builtin_puts", "__builtin_puts_unlocked", "__builtin_vfprintf", and "__builtin_vprintf"
*<"fopen">
*<"fclose">
*<"ferror">
*<"fgets">
*<"fgets_unlocked">
*<"fileno">
*<"fread">
*<"getc">
*<"getchar">
*<"fprintf">
*<"printf">
*<"fwrite">

and of the following functions:

*<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">
*<"strcat">
*<"strchr">
*<"strlen">

In addition, various functions with an "__analyzer_" prefix have special meaning to the analyzer, described in the GCC Internals manual.

Pertinent parameters for controlling the exploration are:

*<--param analyzer-bb-explosion-factor=value>
*<--param analyzer-max-enodes-per-program-point=value>
*<--param analyzer-max-recursion-depth=value>
*<--param analyzer-min-snodes-for-call-summary=value>

The following options control the analyzer.

Simplify interprocedural analysis by computing the effect of certain calls, rather than exploring all paths through the function from callsite to each possible return.

If enabled, call summaries are only used for functions with more than one call site, and that are sufficiently complicated (as per --param analyzer-min-snodes-for-call-summary=value).

Restrict the analyzer to run just the named checker, and enable it.
This option is intended for analyzer developers. If enabled, the analyzer will add extra annotations to any diagrams it generates.
This option is intended for analyzer developers.

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

This option is intended 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.

This option is intended for analyzer developers: 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.
By default the analyzer emits simplified diagnostics paths by hiding events fully located within a system header. With -fanalyzer-show-events-in-system-headers such events are no longer suppressed.
This option is intended for analyzer developers.

By default the analyzer attempts 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.

This option is intended for analyzer developers.

By default the analyzer attempts 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.

This option is intended for analyzer developers.

By default the analyzer will stop exploring an execution path after encountering certain diagnostics, in order 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 continue to explore such paths even after such diagnostics, which may be helpful for debugging issues in the analyzer, or for microbenchmarks for detecting undefined behavior.

This option enables transitivity of constraints within the analyzer.
This option is intended for analyzer developers.

-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 attempts 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 be of help when debugging issues in the analyzer.

This option is intended for analyzer developers. It enables more verbose, lower-level detail in the descriptions of control flow within diagnostic paths.
This option is intended for analyzer developers. It enables more verbose, lower-level detail in the descriptions of events relating to state machines within diagnostic paths.
This option controls the complexity of the control flow paths that are 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.
Dump internal details about what the analyzer is doing to file.analyzer.txt. -fdump-analyzer-stderr overrides this option.
Dump internal details about what the analyzer is doing to stderr. This option overrides -fdump-analyzer.
Dump a representation of the call graph suitable for viewing with GraphViz to file.callgraph.dot.
Dump 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.
Emit diagnostics showing where nodes in the "exploded graph" are in relation to the program source.
Dump a textual representation of the "exploded graph" to file.eg.txt.
Dump 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.
Dump a textual representation of the "exploded path" for each diagnostic to file.idx.kind.epath.txt.
Dump 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.
Dump internal details about the analyzer's search for infinite loops. The details are written in a form suitable for viewing with GraphViz to filenames of the form file.*.infinite-loop.dot.
Dump a compressed JSON representation of analyzer internals to file.analyzer.json.gz. The precise format is subject to change.
As per -fdump-analyzer-supergraph, dump a representation of the "supergraph" suitable for viewing with GraphViz, but annotate the graph with information on what state will be purged at each node. The graph is written to file.state-purge.dot.
Dump representations of the "supergraph" suitable for viewing with GraphViz to file.supergraph.dot and to file.supergraph-eg.dot. These show all of the control flow graphs in the program, with interprocedural edges for calls and returns. The second dump contains annotations showing nodes in the "exploded graph" and diagnostics associated with them.
Emit custom warnings with internal details intended for analyzer developers.

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. Some debug formats can co-exist (like DWARF with CTF) when each of them is enabled explicitly by adding the respective command line option to your other options.

GCC allows you to use -g with -O. The shortcuts taken by optimized code may occasionally be surprising: some variables you declared may not exist at all; flow of control may briefly move where you did not expect it; some statements may not be executed because they compute constant results or their values are already at hand; some statements may execute in different places because they have been moved out of loops. Nevertheless it is possible to debug optimized output. This makes it reasonable to use the optimizer for programs that might have bugs.

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

-g
Produce debugging information in the operating system's native format (stabs, COFF, XCOFF, or DWARF). GDB can work with this debugging information.

On most systems that use stabs format, -g enables use of extra debugging information that only GDB can use; this extra information makes debugging work better in GDB but probably makes other debuggers crash or refuse to read the program. If you want to control for certain whether to generate the extra information, use -gvms (see below).

Produce debugging information for use by GDB. This means to use the most expressive format available (DWARF, stabs, or the native format if neither of those are supported), including GDB extensions if at all possible.
Produce debugging information in DWARF format (if that is supported). The value of version may be either 2, 3, 4 or 5; the default version for most targets is 5 (with the exception of VxWorks, TPF and Darwin / macOS, which default to version 2, and AIX, which defaults to version 4).

Note that with DWARF Version 2, some ports require and always use some non-conflicting DWARF 3 extensions in the unwind tables.

Version 4 may require GDB 7.0 and -fvar-tracking-assignments for maximum benefit. Version 5 requires GDB 8.0 or higher.

GCC no longer supports DWARF Version 1, which is substantially different than Version 2 and later. For historical reasons, some other DWARF-related options such as -fno-dwarf2-cfi-asm) retain a reference to DWARF Version 2 in their names, but apply to all currently-supported versions of DWARF.

Request BTF debug information. BTF is the default debugging format for the eBPF target. On other targets, like x86, BTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options.
Request CTF debug information and use level to specify how much CTF debug information should be produced. If -gctf is specified without a value for level, the default level of CTF debug information is 2.

CTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options.

Level 0 produces no CTF debug information at all. Thus, -gctf0 negates -gctf.

Level 1 produces CTF information for tracebacks only. This includes callsite information, but does not include type information.

Level 2 produces type information for entities (functions, data objects etc.) at file-scope or global-scope only.

Produce debugging information in Alpha/VMS debug format (if that is supported). This is the format used by DEBUG on Alpha/VMS systems.
Produce debugging information in CodeView debug format (if that is supported). This is the format used by Microsoft Visual C++ on Windows.
-glevel
Request debugging information and also use level to specify how much information. The default level is 2.

Level 0 produces no debug information at all. Thus, -g0 negates -g.

Level 1 produces minimal information, enough for making backtraces in parts of the program that you don't plan to debug. This includes descriptions of functions and external variables, and line number tables, but no information about local variables.

Level 3 includes extra information, such as all the macro definitions present in the program. Some debuggers support macro expansion when you use -g3.

If you use multiple -g options, with or without level numbers, the last such option is the one that is effective.

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

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

Annotate assignments to user variables early in the compilation and attempt to carry the annotations over throughout the compilation all the way to the end, in an attempt to improve debug information while optimizing. Use of -gdwarf-4 is recommended along with it.

It can be enabled even if var-tracking is disabled, in which case annotations are created and maintained, but discarded at the end. By default, this flag is enabled together with -fvar-tracking, except when selective scheduling is enabled.

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.
If DWARF debugging information is enabled, the -gdwarf32 selects the 32-bit DWARF format and the -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.
Add description attributes to some DWARF DIEs that have no name attribute, such as artificial variables, external references and call site parameter DIEs.
Generate DWARF ".debug_pubnames" and ".debug_pubtypes" sections.
Generate ".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.
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.
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.
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.
Allow using extensions of later DWARF standard version than selected with -gdwarf-version.
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.

Force GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are to be generated.
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.

Force GCC to assign view numbers internally, if -gvariable-location-views are explicitly requested.
Emit location column information into DWARF debugging information, rather than just file and line. This option is enabled by default.
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.
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.

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. Debug information consumers are not expected to support this extended format, and they would be rendered unable to decode location lists using it.

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

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.

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.

Emit DWARF unwind info as compiler generated ".eh_frame" section instead of using GAS ".cfi_*" directives.
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.

These options control various sorts of optimizations.

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.

The compiler performs optimization based on the knowledge it has of the program. Compiling multiple files at once to a single output file mode allows the compiler to use information gained from all of the files when compiling each of them.

Not all optimizations are controlled directly by a flag. Only optimizations that have a flag are listed in this section.

Most optimizations are completely disabled at -O0 or if an -O level is not set on the command line, even if individual optimization flags are specified. Similarly, -Og suppresses many optimization passes.

Depending on the target and how GCC was configured, a slightly different set of optimizations may be enabled at each -O level than those listed here. You can invoke GCC with -Q --help=optimizers to find out the exact set of optimizations that are enabled at each level.

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

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.

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

Reduce compilation time and make debugging produce the expected results. This is the default.
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.

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

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.

Options of the form -fflag specify machine-independent flags. Most flags have both positive and negative forms; the negative form of -ffoo is -fno-foo. In the table below, only one of the forms is listed---the one you typically use. You can figure out the other form by either removing no- or adding it.

The following options control specific optimizations. They are either activated by -O options or are related to ones that are. You can use the following flags in the rare cases when "fine-tuning" of optimizations to be performed is desired.

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.
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=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 implemented for C and C++, where it enables contraction within one expression, but not across different statements.

The default is -ffp-contract=off for C in a standards compliant mode (-std=c11 or similar), -ffp-contract=fast otherwise.

Omit the frame pointer in functions that don't need one. This avoids the instructions to save, set up and restore the frame pointer; on many targets it also makes an extra register available.

On some targets this flag has no effect because the standard calling sequence always uses a frame pointer, so it cannot be omitted.

Note that -fno-omit-frame-pointer doesn't guarantee the frame pointer is used in all functions. Several targets always omit the frame pointer in leaf functions.

Enabled by default at -O1 and higher.

Optimize sibling and tail recursive calls.

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

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.

Expand memory and string operations (for now, only "memset") inline, even when the length is variable or big enough as to require looping. This is most useful along with -ffreestanding and -fno-builtin.

In some circumstances, it enables the compiler to generate code that takes advantage of known alignment and length multipliers, but even then it may be less efficient than optimized runtime implementations, and grow code size so much that even a less performant but shared implementation runs faster due to better use of code caches. This option is disabled by default.

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.

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.

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.

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.

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.

Inline functions marked by "always_inline" and functions whose body seems smaller than the function call overhead early before doing -fprofile-generate instrumentation and real inlining pass. Doing so makes profiling significantly cheaper and usually inlining faster on programs having large chains of nested wrapper functions.

Enabled by default.

Perform interprocedural scalar replacement of aggregates, removal of unused parameters and replacement of parameters passed by reference by parameters passed by value.

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

By default, GCC limits the size of functions that can be inlined. This flag allows coarse control of this limit. n is the size of functions that can be inlined in number of pseudo instructions.

Inlining is actually controlled by a number of parameters, which may be specified individually by using --param name=value. The -finline-limit=n option sets some of these parameters as follows:

is set to n/2.
is set to n/2.

See below for a documentation of the individual parameters controlling inlining and for the defaults of these parameters.

Note: there may be no value to -finline-limit that results in default behavior.

Note: pseudo instruction represents, in this particular context, an abstract measurement of function's size. In no way does it represent a count of assembly instructions and as such its exact meaning might change from one release to an another.

This is a more fine-grained version of -fkeep-inline-functions, which applies only to functions that are declared using the "dllexport" attribute or declspec.
In C, emit "static" functions that are declared "inline" into the object file, even if the function has been inlined into all of its callers. This switch does not affect functions using the "extern inline" extension in GNU C90. In C++, emit any and all inline functions into the object file.
Emit "static" functions into the object file, even if the function is never used.
Emit variables declared "static const" when optimization isn't turned on, even if the variables aren't referenced.

GCC enables this option by default. If you want to force the compiler to check if a variable is referenced, regardless of whether or not optimization is turned on, use the -fno-keep-static-consts option.

Attempt to merge identical constants (string constants and floating-point constants) across compilation units.

This option is the default for optimized compilation if the assembler and linker support it. Use -fno-merge-constants to inhibit this behavior.

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

Attempt to merge identical constants and identical variables.

This option implies -fmerge-constants. In addition to -fmerge-constants this considers e.g. even constant initialized arrays or initialized constant variables with integral or floating-point types. Languages like C or C++ require each variable, including multiple instances of the same variable in recursive calls, to have distinct locations, so using this option results in non-conforming behavior.

Perform swing modulo scheduling immediately before the first scheduling pass. This pass looks at innermost loops and reorders their instructions by overlapping different iterations.
Perform more aggressive SMS-based modulo scheduling with register moves allowed. By setting this flag certain anti-dependences edges are deleted, which triggers the generation of reg-moves based on the life-range analysis. This option is effective only with -fmodulo-sched enabled.
Disable the optimization pass that scans for opportunities to use "decrement and branch" instructions on a count register instead of instruction sequences that decrement a register, compare it against zero, and then branch based upon the result. This option is only meaningful on architectures that support such instructions, which include x86, PowerPC, IA-64 and S/390. Note that the -fno-branch-count-reg option 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.

Do not put function addresses in registers; make each instruction that calls a constant function contain the function's address explicitly.

This option results in less efficient code, but some strange hacks that alter the assembler output may be confused by the optimizations performed when this option is not used.

The default is -ffunction-cse

If the target supports a BSS section, GCC by default puts variables that are initialized to zero into BSS. This can save space in the resulting code.

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

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

Perform optimizations that check to see if a jump branches to a location where another comparison subsumed by the first is found. If so, the first branch is redirected to either the destination of the second branch or a point immediately following it, depending on whether the condition is known to be true or false.

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

When using a type that occupies multiple registers, such as "long long" on a 32-bit system, split the registers apart and allocate them independently. This normally generates better code for those types, but may make debugging more difficult.

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

Fully split wide types early, instead of very late. This option has no effect unless -fsplit-wide-types is turned on.

This is the default on some targets.

In common subexpression elimination (CSE), scan through jump instructions when the target of the jump is not reached by any other path. For example, when CSE encounters an "if" statement with an "else" clause, CSE follows the jump when the condition tested is false.

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

This is similar to -fcse-follow-jumps, but causes CSE to follow jumps that conditionally skip over blocks. When CSE encounters a simple "if" statement with no else clause, -fcse-skip-blocks causes CSE to follow the jump around the body of the "if".

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

Re-run common subexpression elimination after loop optimizations are performed.

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

Perform a global common subexpression elimination pass. This pass also performs 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.

When -fgcse-lm is enabled, global common subexpression elimination attempts to move loads that are only killed by stores into themselves. This allows a loop containing a load/store sequence to be changed to a load outside the loop, and a copy/store within the loop.

Enabled by default when -fgcse is enabled.

When -fgcse-sm is enabled, a store motion pass is run after global common subexpression elimination. This pass attempts to move stores out of loops. When used in conjunction with -fgcse-lm, loops containing a load/store sequence can be changed to a load before the loop and a store after the loop.

Not enabled at any optimization level.

When -fgcse-las is enabled, the global common subexpression elimination pass eliminates redundant loads that come after stores to the same memory location (both partial and full redundancies).

Not enabled at any optimization level.

When -fgcse-after-reload is enabled, a redundant load elimination pass is performed after reload. The purpose of this pass is to clean up redundant spilling.

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

This option tells the loop optimizer to use language constraints to derive bounds for the number of iterations of a loop. This assumes that loop code does not invoke undefined behavior by for example causing signed integer overflows or out-of-bound array accesses. The bounds for the number of iterations of a loop are used to guide loop unrolling and peeling and loop exit test optimizations. This option is enabled by default.
This option tells the compiler that variables declared in common blocks (e.g. Fortran) may later be overridden with longer trailing arrays. This prevents certain optimizations that depend on knowing the array bounds.
Perform cross-jumping transformation. This transformation unifies equivalent code and saves code size. The resulting code may or may not perform better than without cross-jumping.

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

Combine increments or decrements of addresses with memory accesses. This pass is always skipped on architectures that do not have instructions to support this. Enabled by default at -O1 and higher on architectures that support this.
Perform dead code elimination (DCE) on RTL. Enabled by default at -O1 and higher.
Perform dead store elimination (DSE) on RTL. Enabled by default at -O1 and higher.
Attempt to transform conditional jumps into branch-less equivalents. This includes use of conditional moves, min, max, set flags and abs instructions, and some tricks doable by standard arithmetics. The use of conditional execution on chips where it is available is controlled by -fif-conversion2.

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

Use conditional execution (where available) to transform conditional jumps into branch-less equivalents.

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

The C++ ABI requires multiple entry points for constructors and destructors: one for a base subobject, one for a complete object, and one for a virtual destructor that calls operator delete afterwards. For a hierarchy with virtual bases, the base and complete variants are clones, which means two copies of the function. With this option, the base and complete variants are changed to be thunks that call a common implementation.

Enabled by -Os.

Assume that programs cannot safely dereference null pointers, and that no code or data element resides at address zero. This option enables simple constant folding optimizations at all optimization levels. In addition, other optimization passes in GCC use this flag to control global dataflow analyses that eliminate useless checks for null pointers; these assume that a memory access to address zero always results in a trap, so that if a pointer is checked after it has already been dereferenced, it cannot be null.

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.

Attempt to convert calls to virtual functions to direct calls. This is done both within a procedure and interprocedurally as part of indirect inlining (-findirect-inlining) and interprocedural constant propagation (-fipa-cp). Enabled at levels -O2, -O3, -Os.
Attempt to convert calls to virtual functions to speculative direct calls. Based on the analysis of the type inheritance graph, determine for a given call the set of likely targets. If the set is small, preferably of size 1, change the call into a conditional deciding between direct and indirect calls. The speculative calls enable more optimizations, such as inlining. When they seem useless after further optimization, they are converted back into original form.
Stream extra information needed for aggressive devirtualization when running the link-time optimizer in local transformation mode. This option enables more devirtualization but significantly increases the size of streamed data. For this reason it is disabled by default.
Perform a number of minor optimizations that are relatively expensive.

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

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, LoongArch, PowerPC, RISC-V, SPARC, h83000 and x86 at levels -O2, -O3, -Os.

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. -flifetime-dse=0 is equivalent to -fno-lifetime-dse.
Attempt to decrease register pressure through register live range shrinkage. This is helpful for fast processors with small or moderate size register sets.
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 is the default because it generates better code.
Use specified regions for the integrated register allocator. The region argument should be one of the following:
Use all loops as register allocation regions. This can give the best results for machines with a small and/or irregular register set.
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, ...).
Use all functions as a single region. This typically results in the smallest code size, and is enabled by default for -Os or -O0.
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.

This option is enabled at level -Os for all targets.

Use IRA to evaluate register pressure in loops for decisions to move loop invariants. This option usually results in generation of faster and smaller code on machines with large register files (>= 32 registers), but it can slow the compiler down.

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

Disable sharing of stack slots used for saving call-used hard registers living through a call. Each hard register gets a separate stack slot, and as a result function stack frames are larger.
Disable 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.
Enable CFG-sensitive rematerialization in LRA. Instead of loading values of spilled pseudos, LRA tries to rematerialize (recalculate) values if it is profitable.

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

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.

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.

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.

Disable instruction scheduling across basic blocks, which is normally enabled when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher.
Disable speculative motion of non-load instructions, which is normally enabled when scheduling before register allocation, i.e. with -fschedule-insns or at -O2 or higher.
Enable register pressure sensitive insn scheduling before register allocation. This only makes sense when scheduling before register allocation is enabled, i.e. with -fschedule-insns or at -O2 or higher. 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.
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.
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.
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, -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.
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. -fsched-stalled-insns-dep without a value is equivalent to -fsched-stalled-insns-dep=1.
When scheduling after register allocation, use superblock scheduling. This allows motion across basic block boundaries, resulting in faster schedules. This option is experimental, as not all machine descriptions used by GCC model the CPU closely enough to avoid unreliable results from the algorithm.

This only makes sense when scheduling after register allocation, i.e. with -fschedule-insns2 or at -O2 or higher.

Enable the group heuristic in the scheduler. This heuristic favors the instruction that belongs to a schedule group. This is enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
Enable the critical-path heuristic in the scheduler. This heuristic favors instructions on the critical path. This is enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
Enable the speculative instruction heuristic in the scheduler. This heuristic favors speculative instructions with greater dependency weakness. This is enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
Enable the rank heuristic in the scheduler. This heuristic favors the instruction belonging to a basic block with greater size or frequency. This is enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
Enable the last-instruction heuristic in the scheduler. This heuristic favors the instruction that is less dependent on the last instruction scheduled. This is enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
Enable the dependent-count heuristic in the scheduler. This heuristic favors the instruction that has more instructions depending on it. This is enabled by default when scheduling is enabled, i.e. with -fschedule-insns or -fschedule-insns2 or at -O2 or higher.
Modulo scheduling is performed before traditional scheduling. If a loop is modulo scheduled, later scheduling passes may change its schedule. Use this option to control that behavior.
Schedule instructions using selective scheduling algorithm. Selective scheduling runs instead of the first scheduler pass.
Schedule instructions using selective scheduling algorithm. Selective scheduling runs instead of the second scheduler pass.
Enable software pipelining of innermost loops during selective scheduling. This option has no effect unless one of -fselective-scheduling or -fselective-scheduling2 is turned on.
When pipelining loops during selective scheduling, also pipeline outer loops. This option has no effect unless -fsel-sched-pipelining is turned on.
Some object formats, like ELF, allow interposing of symbols by the dynamic linker. This means that for symbols exported from the DSO, the compiler cannot perform interprocedural propagation, inlining and other optimizations in anticipation that the function or variable in question may change. While this feature is useful, for example, to rewrite memory allocation functions by a debugging implementation, it is expensive in the terms of code quality. With -fno-semantic-interposition the compiler assumes that if interposition happens for functions the overwriting function will have precisely the same semantics (and side effects). Similarly if interposition happens for variables, the constructor of the variable will be the same. The flag has no effect for functions explicitly declared inline (where it is never allowed for interposition to change semantics) and for symbols explicitly declared weak.
Emit function prologues only before parts of the function that need it, rather than at the top of the function. This flag is enabled by default at -O and higher.
Shrink-wrap separate parts of the prologue and epilogue separately, so that those parts are only executed when needed. This option is on by default, but has no effect unless -fshrink-wrap is also turned on and the target supports this.
Enable allocation of values to registers that are clobbered by function calls, by emitting extra instructions to save and restore the registers around such calls. Such allocation is done only when it seems to result in better code.

This option is always enabled by default on certain machines, usually those which have no call-preserved registers to use instead.

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

Tracks stack adjustments (pushes and pops) and stack memory references and then tries to find ways to combine them.

Enabled by default at -O1 and higher.

Use caller save registers for allocation if those registers are not used by any called function. In that case it is not necessary to save and restore them around calls. This is only possible if called functions are part of same compilation unit as current function and they are 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 callee's register usage cannot be known exactly (this happens on targets that do not expose prologues and epilogues in RTL).

Attempt to minimize stack usage. The compiler attempts 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.
Perform reassociation on trees. This flag is enabled by default at -O1 and higher.
Perform code hoisting. Code hoisting tries to move the evaluation of expressions executed on all paths to the function exit as early as possible. This is especially useful as a code size optimization, but it often helps for code speed as well. This flag is enabled by default at -O2 and higher.
Perform partial redundancy elimination (PRE) on trees. This flag is enabled by default at -O2 and -O3.
Make partial redundancy elimination (PRE) more aggressive. This flag is enabled by default at -O3.
Perform forward propagation on trees. This flag is enabled by default at -O1 and higher.
Perform full redundancy elimination (FRE) on trees. The difference between FRE and PRE is that FRE only considers expressions that are computed on all paths leading to the redundant computation. This analysis is faster than PRE, though it exposes fewer redundancies. This flag is enabled by default at -O1 and higher.
Perform hoisting of loads from conditional pointers on trees. This pass is enabled by default at -O1 and higher.
Speculatively hoist loads from both branches of an if-then-else if the loads are from adjacent locations in the same structure and the target architecture has a conditional move instruction. This flag is enabled by default at -O2 and higher.
Perform copy propagation on trees. This pass eliminates unnecessary copy operations. This flag is enabled by default at -O1 and higher.
Discover which functions are pure or constant. Enabled by default at -O1 and higher.
Discover which static variables do not escape the compilation unit. Enabled by default at -O1 and higher.
Discover read-only, write-only and non-addressable static variables. Enabled by default at -O1 and higher.
Reduce stack alignment on call sites if possible. Enabled by default.
Perform interprocedural pointer analysis and interprocedural modification and reference analysis. This option can cause excessive memory and compile-time usage on large compilation units. It is not enabled by default at any optimization level.
Perform interprocedural profile propagation. The 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.
Perform interprocedural mod/ref analysis. This optimization analyzes the side effects of functions (memory locations that are modified or referenced) and enables better optimization across the function call boundary. This flag is enabled by default at -O1 and higher.
Perform interprocedural constant propagation. This optimization analyzes the program to determine when values passed to functions are constants and then optimizes accordingly. This optimization can substantially increase performance if the application has constants passed to functions. This flag is enabled by default at -O2, -Os and -O3. It is also enabled by -fprofile-use and -fauto-profile.
Perform function cloning to make interprocedural constant propagation stronger. When enabled, interprocedural constant propagation performs function cloning when 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). This flag is enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile.
When enabled, perform interprocedural bitwise constant propagation. This flag is enabled by default at -O2 and by -fprofile-use and -fauto-profile. It requires that -fipa-cp is enabled.
When enabled, perform interprocedural propagation of value ranges. This flag is enabled by default at -O2. It requires that -fipa-cp is enabled.
Perform Identical Code Folding for functions and read-only variables. The optimization reduces code size and may disturb unwind stacks by replacing a function by equivalent one with a different name. The optimization works more effectively with link-time optimization enabled.

Although the behavior is similar to the Gold Linker's ICF optimization, GCC ICF works on different levels and thus the optimizations are not same - there are equivalences that are found only by GCC and equivalences found only by Gold.

This flag is enabled by default at -O2 and -Os.

Control GCC's optimizations to produce output suitable for live-patching.

If the compiler's optimization uses a function's body or information extracted from its body to optimize/change another function, the latter is called an impacted function of the former. If a function is patched, its impacted functions should be patched too.

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

Usually, the more IPA optimizations enabled, the larger the number of impacted functions for each function. In order to control the number of impacted functions and more easily compute the list of impacted function, IPA optimizations can be partially enabled at two different levels.

The level argument should be one of the following:

Only enable inlining and cloning optimizations, which includes inlining, cloning, interprocedural scalar replacement of aggregates and partial inlining. As a result, when patching a function, all its callers and its clones' callers are impacted, therefore need to be patched as well.

-flive-patching=inline-clone disables the following optimization flags: -fwhole-program -fipa-pta -fipa-reference -fipa-ra -fipa-icf -fipa-icf-functions -fipa-icf-variables -fipa-bit-cp -fipa-vrp -fipa-pure-const -fipa-reference-addressable -fipa-stack-alignment -fipa-modref

Only enable inlining of static functions. As a result, when patching a static function, all its callers are impacted and so need to be patched as well.

In addition to all the flags that -flive-patching=inline-clone disables, -flive-patching=inline-only-static disables the following additional optimization flags: -fipa-cp-clone -fipa-sra -fpartial-inlining -fipa-cp

When -flive-patching is specified without any value, the default value is inline-clone.

This flag is disabled by default.

Note that -flive-patching is not supported with link-time optimization (-flto).

Detect paths that trigger erroneous or undefined behavior due to dereferencing a null pointer. Isolate those paths from the main control flow and turn the statement with erroneous or undefined behavior into a trap. This flag is enabled by default at -O2 and higher and depends on -fdelete-null-pointer-checks also being enabled.
Detect paths that trigger erroneous or undefined behavior due to a null value being used in a way forbidden by a "returns_nonnull" or "nonnull" attribute. Isolate those paths from the main control flow and turn the statement with erroneous or undefined behavior into a trap. This is not currently enabled, but may be enabled by -O2 in the future.
Perform forward store motion on trees. This flag is enabled by default at -O1 and higher.
Perform sparse conditional bit constant propagation on trees and propagate 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.
Perform sparse conditional constant propagation (CCP) on trees. This pass only operates on local scalar variables and is enabled by default at -O1 and higher.
Propagate information about uses of a value up the definition chain in order to simplify the definitions. For example, this pass strips sign operations if the sign of a value never matters. The flag is enabled by default at -O1 and higher.
Perform pattern matching on SSA PHI nodes to optimize conditional code. This pass is enabled by default at -O1 and higher, except for -Og.
Perform conversion of simple initializations in a switch to initializations from a scalar array. This flag is enabled by default at -O2 and higher.
Look for identical code sequences. When found, replace one with a jump to the other. This optimization is known as tail merging or cross jumping. This flag is enabled by default at -O2 and higher. The compilation time in this pass can be limited using max-tail-merge-comparisons parameter and max-tail-merge-iterations parameter.
Perform dead code elimination (DCE) on trees. This flag is enabled by default at -O1 and higher.
Perform conditional dead code elimination (DCE) for calls to built-in functions that may set "errno" but are otherwise free of side effects. This flag is enabled by default at -O2 and higher if -Os is not also specified.
Assume that a loop with an exit will eventually take the exit and not loop indefinitely. This allows the compiler to remove loops that otherwise have no side-effects, not considering eventual endless looping as such.

This option is enabled by default at -O2 for C++ with -std=c++11 or higher.

Perform a variety of simple scalar cleanups (constant/copy propagation, redundancy elimination, range propagation and expression simplification) based on a dominator tree traversal. This also performs jump threading (to reduce jumps to jumps). This flag is enabled by default at -O1 and higher.
Perform dead store elimination (DSE) on trees. A dead store is a store into a memory location that is later overwritten by another store without any intervening loads. In this case the earlier store can be deleted. This flag is enabled by default at -O1 and higher.
Perform loop header copying on trees. This is beneficial since it increases effectiveness of code motion optimizations. It also saves one jump. This flag is enabled by default at -O1 and higher. It is not enabled for -Os, since it usually increases code size.
Perform loop optimizations on trees. This flag is enabled by default at -O1 and higher.
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.
Enable 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.
Enable the isl based loop nest optimizer. This is a generic loop nest optimizer based on the Pluto optimization algorithms. It calculates a loop structure optimized for data-locality and parallelism. This option is experimental.
Use the Graphite data dependence analysis to identify loops that can be parallelized. Parallelize all the loops that can be analyzed to not contain loop carried dependences without checking that it is profitable to parallelize the loops.
While transforming the program out of the SSA representation, attempt to reduce copying by coalescing versions of different user-defined variables, instead of just compiler temporaries. This may severely limit the ability to debug an optimized program compiled with -fno-var-tracking-assignments. In the negated form, this flag prevents SSA coalescing of user variables. This option is enabled by default if optimization is enabled, and it does very little otherwise.
Attempt to transform conditional jumps in the innermost loops to branch-less equivalents. The intent is to remove control-flow from the innermost loops in order to improve the ability of the vectorization pass to handle these loops. This is enabled by default if vectorization is enabled.
Perform loop distribution. This flag can improve cache performance on big loop bodies and allow further loop optimizations, like parallelization or vectorization, to take place. For example, the loop
DO I = 1, N
  A(I) = B(I) + C
  D(I) = E(I) * F
ENDDO

is transformed to

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

This flag is enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile.

Perform loop distribution of patterns that can be code generated with calls to a library. This flag is enabled by default at -O2 and higher, and by -fprofile-use and -fauto-profile.

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

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

is transformed to

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

and the initialization loop is transformed into a call to memset zero.

Perform loop interchange outside of graphite. This flag can improve cache performance on loop nest and allow further loop optimizations, like vectorization, to take place. For example, the loop
for (int i = 0; i < N; i++)
  for (int j = 0; j < N; j++)
    for (int k = 0; k < N; k++)
      c[i][j] = c[i][j] + a[i][k]*b[k][j];

is transformed to

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

This flag is enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile.

Apply unroll and jam transformations on feasible loops. In a loop nest this unrolls the outer loop by some factor and fuses the resulting multiple inner loops. This flag is enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile.
Perform loop invariant motion on trees. This pass moves only invariants that are hard to handle at RTL level (function calls, operations that expand to nontrivial sequences of insns). With -funswitch-loops it also moves operands of conditions that are invariant out of the loop, so that we can use just trivial invariantness analysis in loop unswitching. The pass also includes store motion.
Create a canonical counter for number of iterations in loops for which determining number of iterations requires complicated analysis. Later optimizations then may determine the number easily. Useful especially in connection with unrolling.
Perform final value replacement. If a variable is modified in a loop in such a way that its value when exiting the loop can be determined using only its initial value and the number of loop iterations, replace uses of the final value by such a computation, provided it is sufficiently cheap. This reduces data dependencies and may allow further simplifications. Enabled by default at -O1 and higher.
Perform induction variable optimizations (strength reduction, induction variable merging and induction variable elimination) on trees.
Parallelize loops, i.e., split their iteration space to run in n threads. This is only possible for loops whose iterations are independent and can be arbitrarily reordered. The optimization is only profitable on multiprocessor machines, for loops that are CPU-intensive, rather than constrained e.g. by memory bandwidth. This option implies -pthread, and thus is only supported on targets that have support for -pthread.
Perform function-local points-to analysis on trees. This flag is enabled by default at -O1 and higher, except for -Og.
Perform scalar replacement of aggregates. This pass replaces structure references with scalars to prevent committing structures to memory too early. This flag is enabled by default at -O1 and higher, except for -Og.
Perform merging of narrow stores to consecutive memory addresses. This pass merges contiguous stores of immediate values narrower than a word into fewer wider stores to reduce the number of instructions. This is enabled by default at -O2 and higher as well as -Os.
Perform temporary expression replacement during the SSA->normal phase. Single use/single def temporaries are replaced at their use location with their defining expression. This results in non-GIMPLE code, but gives the expanders much more complex trees to work on resulting in better RTL generation. This is enabled by default at -O1 and higher.
Perform straight-line strength reduction on trees. This recognizes related expressions involving multiplications and replaces them by less expensive calculations when possible. This is enabled by default at -O1 and higher.
Perform vectorization on trees. This flag enables -ftree-loop-vectorize and -ftree-slp-vectorize if not explicitly specified.
Perform loop vectorization on trees. This flag is enabled by default at -O2 and by -ftree-vectorize, -fprofile-use, and -fauto-profile.
Perform basic block vectorization on trees. This flag is enabled by default at -O2 and by -ftree-vectorize, -fprofile-use, and -fauto-profile.
Initialize automatic variables with either a pattern or with zeroes to increase the security and predictability of a program by preventing uninitialized memory disclosure and use. GCC still considers an automatic variable that doesn't have an explicit initializer as uninitialized, -Wuninitialized and -Wanalyzer-use-of-uninitialized-value will still report warning messages on such automatic variables and the compiler will perform optimization as if the variable were uninitialized. With this option, GCC will also initialize any padding of automatic variables that have structure or union types to zeroes. However, the current implementation cannot initialize automatic variables that are declared between the controlling expression and the first case of a "switch" statement. Using -Wtrivial-auto-var-init to report all such cases.

The three values of choice are:

  • uninitialized doesn't initialize any automatic variables. This is C and C++'s default.
  • pattern Initialize automatic variables with values which will likely transform logic bugs into crashes down the line, are easily recognized in a crash dump and without being values that programmers can rely on for useful program semantics. The current value is byte-repeatable pattern with byte "0xFE". The values used for pattern initialization might be changed in the future.
  • zero Initialize automatic variables with zeroes.

The default is uninitialized.

Note that the initializer values, whether zero or pattern, refer to data representation (in memory or machine registers), rather than to their interpretation as numerical values. This distinction may be important in languages that support types with biases or implicit multipliers, and with such extensions as hardbool. For example, a variable that uses 8 bits to represent (biased) quantities in the "range 160..400" will be initialized with the bit patterns 0x00 or 0xFE, depending on choice, whether or not these representations stand for values in that range, and even if they do, the interpretation of the value held by the variable will depend on the bias. A hardbool variable that uses say "0X5A" and 0xA5 for "false" and "true", respectively, will trap with either choice of trivial initializer, i.e., zero initialization will not convert to the representation for "false", even if it would for a "static" variable of the same type. This means the initializer pattern doesn't generally depend on the type of the initialized variable. One notable exception is that (non-hardened) boolean variables that fit in registers are initialized with "false" (zero), even when pattern is requested.

You can control this behavior for a specific variable by using the variable attribute "uninitialized".

Alter 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 while with the dynamic model a runtime check guards the vectorized code-path to enable it only for iteration counts that will likely execute faster than when executing the original scalar loop. The cheap model disables vectorization of loops where doing so would be cost prohibitive for example due to required runtime checks for data dependence or alignment but otherwise is equal to the dynamic model. The very-cheap model only allows vectorization if the vector code would entirely replace the scalar code that is being vectorized. For example, if each iteration of a vectorized loop would only be able to handle exactly four iterations of the scalar loop, the very-cheap model would only allow vectorization if the scalar iteration count is known to be a multiple of four.

The default cost model depends on other optimization flags and is either dynamic or cheap.

Alter the cost model used for vectorization of loops marked with the OpenMP simd directive. The model argument should be one of unlimited, dynamic, cheap. All values of model have the same meaning as described in -fvect-cost-model and by default a cost model defined with -fvect-cost-model is used.
Perform Value Range Propagation on trees. This is similar to the constant propagation pass, but instead of values, ranges of values are propagated. This allows the optimizers to remove unnecessary range checks like array bound checks and null pointer checks. This is enabled by default at -O2 and higher. Null pointer check elimination is only done if -fdelete-null-pointer-checks is enabled.
Split paths leading to loop backedges. This can improve dead code elimination and common subexpression elimination. This is enabled by default at -O3 and above.
Enables expression of values of induction variables in later iterations of the unrolled loop using the value in the first iteration. This breaks long dependency chains, thus improving efficiency of the scheduling passes.

A combination of -fweb and CSE is often sufficient to obtain the same effect. However, that is not reliable in cases where the loop body is more complicated than a single basic block. It also does not work at all on some architectures due to restrictions in the CSE pass.

This optimization is enabled by default.

With this option, the compiler creates multiple copies of some local variables when unrolling a loop, which can result in superior code.

This optimization is enabled by default for PowerPC targets, but disabled by default otherwise.

Inline parts of functions. 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.

Perform predictive commoning optimization, i.e., reusing computations (especially memory loads and stores) performed in previous iterations of loops.

This option is enabled at level -O3. It is also enabled by -fprofile-use and -fauto-profile.

If supported by the target machine, generate instructions to prefetch memory to improve the performance of loops that access large arrays.

This option may generate better or worse code; results are highly dependent on the structure of loops within the source code.

Disabled at level -Os.

Do not substitute constants for known return value of formatted output functions such as "sprintf", "snprintf", "vsprintf", and "vsnprintf" (but not "printf" of "fprintf"). This transformation allows GCC to optimize or even eliminate branches based on the known return value of these functions called with arguments that are either constant, or whose values are known to be in a range that makes determining the exact return value possible. For example, when -fprintf-return-value is in effect, both the branch and the body of the "if" statement (but not the call to "snprint") can be optimized away when "i" is a 32-bit or smaller integer because the return value is guaranteed to be at most 8.
char buf[9];
if (snprintf (buf, "%08x", i) >= sizeof buf)
  ...

The -fprintf-return-value option relies on other optimizations and yields best results with -O2 and above. It works in tandem with the -Wformat-overflow and -Wformat-truncation options. The -fprintf-return-value option is enabled by default.

Disable any machine-specific peephole optimizations. The difference between -fno-peephole and -fno-peephole2 is in how they are implemented in the compiler; some targets use one, some use the other, a few use both.

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

Do not guess branch probabilities using heuristics.

GCC uses heuristics to guess branch probabilities if they are not 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 is also possible to specify expected probability of the expression with "__builtin_expect_with_probability" built-in function.

The default is -fguess-branch-probability at levels -O, -O2, -O3, -Os.

Reorder basic blocks in the compiled function in order to reduce number of taken branches and improve code locality.

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

Use the specified algorithm for basic block reordering. The algorithm argument can be simple, which does not increase code size (except sometimes due to secondary effects like alignment), or stc, the "software trace cache" algorithm, which tries to put all often executed code together, minimizing the number of branches executed by making extra copies of code.

The default is simple at levels -O1, -Os, and stc at levels -O2, -O3.

In addition to reordering basic blocks in the compiled function, in order to reduce number of taken branches, partitions hot and cold basic blocks into separate sections of the assembly and .o files, to improve paging and cache locality performance.

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

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

Reorder functions in the object file in order to improve code locality. This is implemented by using special subsections ".text.hot" for most frequently executed functions and ".text.unlikely" for unlikely executed functions. Reordering is done by the linker so object file format must support named sections and linker must place them in a reasonable way.

This option isn't effective unless you either provide profile feedback (see -fprofile-arcs for details) or manually annotate functions with "hot" or "cold" attributes.

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

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

Pay special attention to code like this:

union a_union {
  int i;
  double d;
};

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

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

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

Similarly, access by taking the address, casting the resulting pointer and dereferencing the result has undefined behavior, even if the cast uses a union type, e.g.:

int f() {
  double d = 3.0;
  return ((union a_union *) &d)->i;
}

The -fstrict-aliasing option is enabled at levels -O2, -O3, -Os.

Controls whether rules of -fstrict-aliasing are applied across function boundaries. Note that if multiple functions gets 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.

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. This is 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 is not specified, it defaults to n.

Examples: -falign-functions=32 aligns functions to the next 32-byte boundary, -falign-functions=24 aligns to the next 32-byte boundary only if this can be done by skipping 23 bytes or less, -falign-functions=32:7 aligns to the next 32-byte boundary only if this can be done by skipping 6 bytes or less.

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

Some assemblers only support this flag when n is a power of two; in that case, it is rounded up.

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

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

Enabled at levels -O2, -O3.

If this option is enabled, the compiler tries to avoid unnecessarily overaligning functions. It attempts to instruct the assembler to align by the amount specified by -falign-functions, but not to skip more bytes than the size of the function.
Align all branch targets to a power-of-two boundary.

Parameters of this option are analogous to the -falign-functions option. -fno-align-labels and -falign-labels=1 are equivalent and mean that labels are not aligned.

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

If n is not specified or is zero, use a machine-dependent default which is very likely to be 1, meaning no alignment. The maximum allowed n option value is 65536.

Enabled at levels -O2, -O3.

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. This is 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 that loops are not aligned. The maximum allowed n option value is 65536.

If n is not specified or is zero, use a machine-dependent default.

Enabled at levels -O2, -O3.

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

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
Do not remove unused C++ allocations in dead code elimination.
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.

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.

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.

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.

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.

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

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:

B<-fPIC> + B<-fpic> = B<-fpic>
B<-fPIC> + B<-fno-pic> = B<-fno-pic>
B<-fpic/-fPIC> + (no option) = (no option)
B<-fPIC> + B<-fPIE> = B<-fPIE>
B<-fpic> + B<-fPIE> = B<-fpie>
B<-fPIC/-fpic> + B<-fpie> = B<-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.

To enable debug info generation you need to supply -g at compile time. If any of the input files at link time were built with debug info generation enabled the link will enable debug info generation as well. Any elaborate debug info settings like the dwarf level -gdwarf-5 need to be explicitly repeated at the linker command line and mixing different settings in different translation units is discouraged.

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

Another feature of LTO is that it is possible to apply interprocedural optimizations on files written in different languages:

gcc -c -flto foo.c
g++ -c -flto bar.cc
gfortran -c -flto baz.f90
g++ -o myprog -flto -O3 foo.o bar.o baz.o -lgfortran

Notice that the final link is done with g++ to get the C++ runtime libraries and -lgfortran is added to get the Fortran runtime libraries. In general, when mixing languages in LTO mode, you should use the same link command options as when mixing languages in a regular (non-LTO) compilation.

If object files containing GIMPLE bytecode are stored in a library archive, say libfoo.a, it is possible to extract and use them in an LTO link if you are using a linker with plugin support. To create static libraries suitable for LTO, use gcc-ar and gcc-ranlib instead of ar and ranlib; to show the symbols of object files with GIMPLE bytecode, use gcc-nm. Those commands require that ar, ranlib and nm have been compiled with plugin support. At link time, use the flag -fuse-linker-plugin to ensure that the library participates in the LTO optimization process:

gcc -o myprog -O2 -flto -fuse-linker-plugin a.o b.o -lfoo

With the linker plugin enabled, the linker extracts the needed GIMPLE files from libfoo.a and passes them on to the running GCC to make them part of the aggregated GIMPLE image to be optimized.

If you are not using a linker with plugin support and/or do not enable the linker plugin, then the objects inside libfoo.a are extracted and linked as usual, but they do not participate in the LTO optimization process. In order to make a static library suitable for both LTO optimization and usual linkage, compile its object files with -flto -ffat-lto-objects.

Link-time optimizations do not require the presence of the whole program to operate. If the program does not require any symbols to be exported, it is possible to combine -flto and -fwhole-program to allow the interprocedural optimizers to use more aggressive assumptions which may lead to improved optimization opportunities. Use of -fwhole-program is not needed when linker plugin is active (see -fuse-linker-plugin).

The current implementation of LTO makes no attempt to generate bytecode that is portable between different types of hosts. The bytecode files are versioned and there is a strict version check, so bytecode files generated in one version of GCC do not work with an older or newer version of GCC.

Link-time optimization does not work well with generation of debugging information on systems other than those using a combination of ELF and DWARF.

If you specify the optional n, the optimization and code generation done at link time is executed in parallel using n parallel jobs by utilizing an installed make program. The environment variable MAKE may be used to override the program used.

You can also specify -flto=jobserver to use GNU make's job server mode to determine the number of parallel jobs. This is useful when the Makefile calling GCC is already executing in parallel. You must prepend a + to the command recipe in the parent Makefile for this to work. This option likely only works if MAKE is GNU make. Even without the option value, GCC tries to automatically detect a running GNU make's job server.

Use -flto=auto to use GNU make's job server, if available, or otherwise fall back to autodetection of the number of CPU threads present in your system.

Specify the partitioning algorithm used by the link-time optimizer. The value is either 1to1 to specify a partitioning mirroring the original source files or balanced to specify partitioning into equally sized chunks (whenever possible) or max to create 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 an workaround for various code ordering issues, the max partitioning is intended for internal testing only. The value one specifies that exactly one partition should be used while the value none bypasses partitioning and executes the link-time optimization step directly from the WPA phase.
This option specifies the level of compression used for intermediate language written to LTO object files, and is only meaningful in conjunction with LTO mode (-flto). GCC currently supports two LTO compression algorithms. For zstd, valid values are 0 (no compression) to 19 (maximum compression), while zlib supports values from 0 to 9. Values outside this range are clamped to either minimum or maximum of the supported values. If the option is not given, a default balanced compression setting is used.
Enables the use of a linker plugin during link-time optimization. This option relies on plugin support in the linker, which is available in gold or in GNU ld 2.21 or newer.

This option enables the extraction of object files with GIMPLE bytecode out of library archives. This improves the quality of optimization by exposing more code to the link-time optimizer. This information specifies what symbols can be accessed externally (by non-LTO object or during dynamic linking). Resulting code quality improvements on binaries (and shared libraries that use hidden visibility) are similar to -fwhole-program. See -flto for a description of the effect of this flag and how to use it.

This option is enabled by default when LTO support in GCC is enabled and GCC was configured for use with a linker supporting plugins (GNU ld 2.21 or newer or gold).

Fat LTO objects are object files that contain both the intermediate language and the object code. This makes them usable for both LTO linking and normal linking. This option is effective only when compiling with -flto and is ignored at link time.

-fno-fat-lto-objects improves compilation time over plain LTO, but requires the complete toolchain to be aware of LTO. It requires a linker with linker plugin support for basic functionality. Additionally, nm, ar and ranlib need to support linker plugins to allow a full-featured build environment (capable of building static libraries etc). GCC provides the gcc-ar, gcc-nm, gcc-ranlib wrappers to pass the right options to these tools. With non fat LTO makefiles need to be modified to use them.

Note that modern binutils provide plugin auto-load mechanism. Installing the linker plugin into $libdir/bfd-plugins has the same effect as usage of the command wrappers (gcc-ar, gcc-nm and gcc-ranlib).

The default is -fno-fat-lto-objects on targets with linker plugin support.

After register allocation and post-register allocation instruction splitting, identify arithmetic instructions that compute processor flags similar to a comparison operation based on that arithmetic. If possible, eliminate the explicit comparison operation.

This pass only applies to certain targets that cannot explicitly represent the comparison operation before register allocation is complete.

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

Try to eliminate add instructions by folding them in memory loads/stores.

Enabled at levels -O2, -O3.

After register allocation and post-register allocation instruction splitting, perform a copy-propagation pass to try to reduce scheduling dependencies and occasionally eliminate the copy.

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

Profiles collected using an instrumented binary for multi-threaded programs may be inconsistent due to missed counter updates. When this option is specified, GCC uses heuristics to correct or smooth out such inconsistencies. By default, GCC emits an error message when an inconsistent profile is detected.

This option is enabled by -fauto-profile.

With "-fprofile-use" all portions of programs not executed during train run are optimized agressively for size rather than speed. In some cases it is not practical to train all possible hot paths in the program. (For example, program may contain functions specific for a given hardware and trianing may not cover all hardware configurations program is run on.) With "-fprofile-partial-training" profile feedback will be ignored for all functions not executed during the train run leading them to be optimized as if they were compiled without profile feedback. This leads to better performance when train run is not representative but also leads to significantly bigger code.
Enable profile feedback-directed optimizations, and the following optimizations, many of which are generally profitable only with profile feedback available:

-fbranch-probabilities -fprofile-values -funroll-loops -fpeel-loops -ftracer -fvpt -finline-functions -fipa-cp -fipa-cp-clone -fipa-bit-cp -fpredictive-commoning -fsplit-loops -funswitch-loops -fgcse-after-reload -ftree-loop-vectorize -ftree-slp-vectorize -fvect-cost-model=dynamic -ftree-loop-distribute-patterns -fprofile-reorder-functions

Before you can use this option, you must first generate profiling information.

By default, GCC emits an error message if the feedback profiles do not match the source code. This error can be turned into a warning by using -Wno-error=coverage-mismatch. Note this may result in poorly optimized code. Additionally, by default, GCC also emits a warning message if the feedback profiles do not exist (see -Wmissing-profile).

If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.

Enable sampling-based feedback-directed optimizations, and the following optimizations, many of which are generally profitable only with profile feedback available:

-fbranch-probabilities -fprofile-values -funroll-loops -fpeel-loops -ftracer -fvpt -finline-functions -fipa-cp -fipa-cp-clone -fipa-bit-cp -fpredictive-commoning -fsplit-loops -funswitch-loops -fgcse-after-reload -ftree-loop-vectorize -ftree-slp-vectorize -fvect-cost-model=dynamic -ftree-loop-distribute-patterns -fprofile-correction

path is the name of a file containing AutoFDO profile information. If omitted, it defaults to fbdata.afdo in the current directory.

Producing an AutoFDO profile data file requires running your program with the perf utility on a supported GNU/Linux target system. For more information, see https://perf.wiki.kernel.org/.

E.g.

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

Then use the create_gcov tool to convert the raw profile data to a format that can be used by GCC. You must also supply the unstripped binary for your program to this tool. See https://github.com/google/autofdo.

E.g.

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

The following options control compiler behavior regarding floating-point arithmetic. These options trade off between speed and correctness. All must be specifically enabled.

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.

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. If -fexcess-precision=16 is specified, constants and the results of expressions with types "_Float16" and "__bf16" are computed without excess precision.

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

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.

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.

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.

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.

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.

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.

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.

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

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

Compile code assuming that IEEE signaling NaNs may generate user-visible traps during floating-point operations. Setting this option disables optimizations that may change the number of exceptions visible with signaling NaNs. This option implies -ftrapping-math.

This option causes the preprocessor macro "__SUPPORT_SNAN__" to be defined.

The default is -fno-signaling-nans.

This option is experimental and does not currently guarantee to disable all GCC optimizations that affect signaling NaN behavior.

Do not allow the built-in functions "ceil", "floor", "round" and "trunc", and their "float" and "long double" variants, to generate code that raises the "inexact" floating-point exception for noninteger arguments. ISO C99 and C11 allow these functions to raise the "inexact" exception, but ISO/IEC TS 18661-1:2014, the C bindings to IEEE 754-2008, as integrated into ISO C23, does not allow these functions to do so.

The default is -ffp-int-builtin-inexact, allowing the exception to be raised, unless C23 or a later C standard is selected. This option does nothing unless -ftrapping-math is in effect.

Even if -fno-fp-int-builtin-inexact is used, if the functions generate a call to a library function then the "inexact" exception may be raised if the library implementation does not follow TS 18661.

Treat floating-point constants as single precision instead of implicitly converting them to double-precision constants.
When enabled, this option states that a range reduction step is not needed when performing complex division. Also, there is no checking whether the result of a complex multiplication or division is "NaN + I*NaN", with an attempt to rescue the situation in that case. The default is -fno-cx-limited-range, but is enabled by -ffast-math.

This option controls the default setting of the ISO C99 "CX_LIMITED_RANGE" pragma. Nevertheless, the option applies to all languages.

Complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there is no checking whether the result of a complex multiplication or division is "NaN + I*NaN", with an attempt to rescue the situation in that case.

The default is -fno-cx-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.

After running a program compiled with -fprofile-arcs, you can compile it a second time using -fbranch-probabilities, to improve optimizations based on the number of times each branch was taken. When a program compiled with -fprofile-arcs exits, it saves arc execution counts to a file called sourcename.gcda for each source file. The information in this data file is very dependent on the structure of the generated code, so you must use the same source code and the same optimization options for both compilations. See details about the file naming in -fprofile-arcs.

With -fbranch-probabilities, GCC puts a REG_BR_PROB note on each JUMP_INSN and CALL_INSN. These can be used to improve optimization. Currently, they are 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.

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.

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.

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.

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.

Performs a target dependent pass over the instruction stream to schedule instructions of same type together because target machine can execute them more efficiently if they are adjacent to each other in the instruction flow.

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

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.

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.

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.
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 small constant number of iterations).

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

Enables the loop invariant motion pass in the RTL loop optimizer. Enabled at level -O1 and higher, except for -Og.
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.
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.

Move branches with loop invariant conditions out of the loop, with duplicates of the loop on both branches (modified according to result of the condition).

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

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.

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.

Optimize the prologue of variadic argument functions with respect to usage of those arguments.
Try to reduce the number of symbolic address calculations by using shared "anchor" symbols to address nearby objects. This transformation can help to reduce the number of GOT entries and GOT accesses on some targets.

For example, the implementation of the following function "foo":

static int a, b, c;
int foo (void) { return a + b + c; }

usually calculates the addresses of all three variables, but if you compile it with -fsection-anchors, it accesses the variables from a common anchor point instead. The effect is similar to the following pseudocode (which isn't valid C):

int foo (void)
{
  register int *xr = &x;
  return xr[&a - &x] + xr[&b - &x] + xr[&c - &x];
}

Not all targets support this option.

Zero call-used registers at function return to increase program security by either mitigating Return-Oriented Programming (ROP) attacks or preventing information leakage through registers.

The possible values of choice are the same as for the "zero_call_used_regs" attribute. The default is skip.

You can control this behavior for a specific function by using the function attribute "zero_call_used_regs".

In some places, GCC uses various constants to control the amount of optimization that is done. For example, GCC does not inline functions that contain more than a certain number of instructions. You can control some of these constants on the command line using the --param option.

The names of specific parameters, and the meaning of the values, are tied to the internals of the compiler, and are subject to change without notice in future releases.

In order to get the minimal, maximal and default values of a parameter, use the --help=param -Q options.

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

When branch is predicted to be taken with probability lower than this threshold (in percent), then it is considered well predictable.
RTL if-conversion tries to remove conditional branches around a block and replace them with conditionally executed instructions. This parameter gives the maximum number of instructions in a block which should be considered for if-conversion. The compiler will also use other heuristics to decide whether if-conversion is likely to be profitable.
RTL if-conversion will try to remove conditional branches around a block and replace them with conditionally executed instructions. These parameters give the maximum permissible cost for the sequence that would be generated by if-conversion 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.
The maximum number of incoming edges to consider for cross-jumping. The algorithm used by -fcrossjumping is O(N^2) in the number of edges incoming to each block. Increasing values mean more aggressive optimization, making the compilation time increase with probably small improvement in executable size.
The minimum number of instructions that must be matched 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.
The maximum code size expansion factor when copying basic blocks instead of jumping. The expansion is relative to a jump instruction.
The maximum number of instructions to duplicate to a block that jumps to a computed goto. To avoid O(N^2) behavior in a number of passes, GCC factors computed gotos early in the compilation process, and unfactors them as late as possible. Only computed jumps at the end of a basic blocks with no more than max-goto-duplication-insns are unfactored.
The maximum number of instructions to consider when looking for an instruction to fill a delay slot. If more than this arbitrary number of instructions are searched, the time savings from filling the delay slot are minimal, so stop searching. Increasing values mean more aggressive optimization, making the compilation time increase with probably small improvement in execution time.
When trying to fill delay slots, the maximum number of instructions to consider when searching for a block with valid live register information. Increasing this arbitrarily chosen value means more aggressive optimization, increasing the compilation time. This parameter should be removed when the delay slot code is rewritten to maintain the control-flow graph.
The approximate maximum amount of memory in "kB" that can be allocated in order to perform the global common subexpression elimination optimization. If more memory than specified is required, the optimization is not done.
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.
The maximum number of pending dependencies scheduling allows before flushing the current state and starting over. Large functions with few branches or calls can create excessively large lists which needlessly consume memory and resources.
The maximum number of backtrack attempts the scheduler should make when modulo scheduling a loop. Larger values can exponentially increase compilation time.
Maximal loop depth of a call considered by inline heuristics that tries to inline all functions called once.
Maximal estimated size of functions produced while inlining functions called once.
Several parameters control the tree inliner used in GCC. This number sets the maximum number of instructions (counted in GCC's internal representation) in a single function that the tree inliner considers for inlining. This only affects functions declared inline and methods implemented in a class declaration (C++).
When you use -finline-functions (included in -O3), a lot of functions that would otherwise not be considered for inlining by the compiler are investigated. To those functions, a different (more restrictive) limit compared to functions declared inline can be applied (--param max-inline-insns-auto).
This is bound applied to calls which are considered relevant with -finline-small-functions.
This is bound applied to calls which are optimized for size. Small growth may be desirable to anticipate optimization oppurtunities exposed by inlining.
Number of instructions accounted by inliner for function overhead such as function prologue and epilogue.
Extra time accounted by inliner for function overhead such as time needed to execute function prologue and epilogue.
The scale (in percents) applied to inline-insns-single, inline-insns-single-O2, inline-insns-auto when inline heuristics hints that inlining is very profitable (will enable later optimizations).
Same as --param uninlined-function-insns and --param uninlined-function-time but applied to function thunks.
When estimated performance improvement of caller + callee runtime exceeds this threshold (in percent), the function can be inlined regardless of the limit on --param max-inline-insns-single and --param max-inline-insns-auto.
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.
Specifies maximal growth of large function caused by inlining in percents. For example, parameter value 100 limits large function growth to 2.0 times the original size.
The limit specifying large translation unit. Growth caused by inlining of units larger than this limit is limited by --param inline-unit-growth. For small units this might be too tight. For example, consider a unit consisting of function A that is inline and B that just calls A three times. If B is small relative to A, the growth of unit is 300\% and yet such inlining is very sane. For very large units consisting of small inlineable functions, however, the overall unit growth limit is needed to avoid exponential explosion of code size. Thus for smaller units, the size is increased to --param large-unit-insns before applying --param inline-unit-growth.
Maximum number of concurrently open C++ module files when lazy loading.
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.
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.
The size of translation unit that IPA-CP pass considers large.
The limit specifying large stack frames. While inlining the algorithm is trying to not grow past this limit too much.
Specifies maximal growth of large stack frames caused by inlining in percents. For example, parameter value 1000 limits large stack frame growth to 11 times the original size.
Specifies the maximum number of instructions an out-of-line copy of a self-recursive inline function can grow into by performing recursive inlining.

--param max-inline-insns-recursive applies to functions declared inline. For functions not declared inline, recursive inlining happens only when -finline-functions (included in -O3) is enabled; --param max-inline-insns-recursive-auto applies instead.

Specifies the maximum recursion depth used for recursive inlining.

--param max-inline-recursive-depth applies to functions declared inline. For functions not declared inline, recursive inlining happens only when -finline-functions (included in -O3) is enabled; --param max-inline-recursive-depth-auto applies instead.

Recursive inlining is profitable only for function having deep recursion in average and can hurt for function having little recursion depth by increasing the prologue size or complexity of function body to other optimizers.

When profile feedback is available (see -fprofile-generate) the actual recursion depth can be guessed from the probability that function recurses via a given call expression. This parameter limits inlining only to call expressions whose probability exceeds the given threshold (in percents).

Specify growth that the early inliner can make. In effect it increases the amount of inlining for code having a large abstraction penalty.
Limit of iterations of the early inliner. This basically bounds the number of nested indirect calls the early inliner can resolve. Deeper chains are still handled by late inlining.
Probability (in percent) that C++ inline function with comdat visibility are shared across multiple compilation units.
Specifies the maximal number of base pointers, references and accesses stored for a single function by mod/ref analysis.
Specifies the maxmal number of tests alias oracle can perform to disambiguate memory locations using the mod/ref information. This parameter ought to be bigger than --param modref-max-bases and --param modref-max-refs.
Specifies the maximum depth of DFS walk used by modref escape analysis. Setting to 0 disables the analysis completely.
Specifies the maximum number of escape points tracked by modref per SSA-name.
Specifies the maximum number the access range is enlarged during modref dataflow analysis.
A parameter to control whether to use function internal id in profile database lookup. If the value is 0, the compiler uses an id that is based on function assembler name and filename, which makes old profile data more tolerant to source changes such as function reordering etc.
The minimum number of iterations under which loops are not vectorized when -ftree-vectorize is used. The number of iterations after vectorization needs to be greater than the value specified by this option to allow vectorization.
Scaling factor in calculation of maximum distance an expression can be moved by GCSE optimizations. This is currently supported only in the code hoisting pass. The bigger the ratio, the more aggressive code hoisting is with simple expressions, i.e., the expressions that have cost less than gcse-unrestricted-cost. Specifying 0 disables hoisting of simple expressions.
Cost, roughly measured as the cost of a single typical machine instruction, at which GCSE optimizations do not constrain the distance an expression can travel. This is currently supported only in the code hoisting pass. The lesser the cost, the more aggressive code hoisting is. Specifying 0 allows all expressions to travel unrestricted distances.
The depth of search in the dominator tree for expressions to hoist. This is used to avoid quadratic behavior in hoisting algorithm. The value of 0 does not limit on the search, but may slow down compilation of huge functions.
The maximum amount of similar bbs to compare a bb with. This is used to avoid quadratic behavior in tree tail merging.
The maximum amount of iterations of the pass over the function. This is used to limit compilation time in tree tail merging.
Allow the store merging pass to introduce unaligned stores if it is legal to do so.
The maximum number of stores to attempt to merge into wider stores in the store merging pass.
The maximum number of store chains to track at the same time in the attempt to merge them into wider stores in the store merging pass.
The maximum number of stores to track at the same time in the attemt to to merge them into wider stores in the store merging pass.
The maximum number of instructions 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.
The maximum number of instructions biased by probabilities of their execution that a loop may have to be unrolled. If a loop is unrolled, this parameter also determines how many times the loop code is unrolled.
The maximum number of unrollings of a single loop.
The maximum number of instructions that a loop may have to be peeled. If a loop is peeled, this parameter also determines how many times the loop code is peeled.
The maximum number of peelings of a single loop.
The maximum number of branches on the hot path through the peeled sequence.
The maximum number of insns of a completely peeled loop.
The maximum number of iterations of a loop to be suitable for complete peeling.
The maximum depth of a loop nest suitable for complete peeling.
The maximum number of insns of an unswitched loop.
The maximum depth of a loop nest to be unswitched.
The minimum cost of an expensive expression in the loop invariant motion.
When FDO profile information is available, min-loop-cond-split-prob specifies minimum threshold for probability of semi-invariant condition statement to trigger loop split.
Bound on number of candidates for induction variables, below which all candidates are considered for each use in induction variable optimizations. If there are more candidates than this, only the most relevant ones are considered to avoid quadratic time complexity.
The induction variable optimizations give up on loops that contain more induction variable uses.
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.
Average number of iterations of a loop.
Maximum size (in bytes) of objects tracked bytewise by dead store elimination. Larger values may result in larger compilation times.
Maximum number of queries into the alias oracle per store. Larger values result in larger compilation times and may result in more removed dead stores.
Bound on size of expressions used in the scalar evolutions analyzer. Large expressions slow the analyzer.
Bound on the complexity of the expressions in the scalar evolutions analyzer. Complex expressions slow the analyzer.
Maximum number of arguments in a PHI supported by TREE if conversion unless the loop is marked with simd pragma.
The maximum number of possible vector layouts (such as permutations) to consider when optimizing to-be-vectorized code.
The maximum number of run-time checks that can be performed when doing loop versioning for alignment in the vectorizer.
The maximum number of run-time checks that can be performed when doing loop versioning for alias in the vectorizer.
The maximum number of loop peels to enhance access alignment for vectorizer. Value -1 means no limit.
The maximum number of iterations of a loop the brute-force algorithm for analysis of the number of iterations of the loop tries to evaluate.
The denominator n of fraction 1/n of the maximal execution count of a basic block in the entire program that a basic block needs to at least have in order to be considered hot. The default is 10000, which means that a basic block is considered hot if its execution count is greater than 1/10000 of the maximal execution count. 0 means that it is never considered hot. Used in non-LTO mode.
The number of most executed permilles, ranging from 0 to 1000, of the profiled execution of the entire program to which the execution count of a basic block must be part of in order to be considered hot. The default is 990, which means that a basic block is considered hot if its execution count contributes to the upper 990 permilles, or 99.0%, of the profiled execution of the entire program. 0 means that it is never considered hot. Used in LTO mode.
The denominator n of fraction 1/n of the execution frequency of the entry block of a function that a basic block of this function needs to at least have in order to be considered hot. The default is 1000, which means that a basic block is considered hot in a function if it is executed more frequently than 1/1000 of the frequency of the entry block of the function. 0 means that it is never considered hot.
The denominator n of fraction 1/n of the number of profiled runs of the entire program below which the execution count of a basic block must be in order for the basic block to be considered unlikely executed. The default is 20, which means that a basic block is considered unlikely executed if it is executed in fewer than 1/20, or 5%, of the runs of the program. 0 means that it is always considered unlikely executed.
The maximum number of loop iterations we predict statically. This is useful in cases where a function contains a single loop with known bound and another loop with unknown bound. The known number of iterations is predicted correctly, while the unknown number of iterations average to roughly 10. This means that the loop without bounds appears artificially cold relative to the other one.
Control the probability of the expression having the specified value. This parameter takes a percentage (i.e. 0 ... 100) as input.
The maximum length of a constant string for a builtin string cmp call eligible for inlining.
Select fraction of the maximal frequency of executions of a basic block in a function to align the basic block.
A loop expected to iterate at least the selected number of iterations is aligned.
This value is used to limit superblock formation once the given percentage of executed instructions is covered. This limits unnecessary code size expansion.

The tracer-dynamic-coverage-feedback parameter is used only when profile feedback is available. The real profiles (as opposed to statically estimated ones) are much less balanced allowing the threshold to be larger value.

Stop tail duplication once code growth has reached given percentage. This is a rather artificial limit, as most of the duplicates are eliminated later in cross jumping, so it may be set to much higher values than is the desired code growth.
Stop reverse growth when the reverse probability of best edge is less than this threshold (in percent).
Stop forward growth if the best edge has probability lower than this threshold.

Similarly to tracer-dynamic-coverage two parameters are provided. tracer-min-branch-probability-feedback is used for compilation with profile feedback and tracer-min-branch-probability compilation without. The value for compilation with profile feedback needs to be more conservative (higher) in order to make tracer effective.

Specify the size of the operating system provided stack guard as 2 raised to num bytes. Higher values may reduce the number of explicit probes, but a value larger than the operating system provided guard will leave code vulnerable to stack clash style attacks.
Stack clash protection involves probing stack space as it is 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.
The maximum number of basic blocks on path that CSE considers.
The maximum number of instructions CSE processes before flushing.
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 is not able to calculate RAM on a particular platform, the lower bound of 30% is used. Setting this parameter and ggc-min-heapsize to zero causes a full collection to occur at every opportunity. This is extremely slow, but can be useful for debugging.

Minimum size of the garbage collector's heap before it begins bothering to collect garbage. The first collection occurs after the heap expands by ggc-min-expand% beyond ggc-min-heapsize. Again, tuning this may improve compilation speed, and has no effect on code generation.

The default is the smaller of RAM/8, RLIMIT_RSS, or a limit that tries to ensure that RLIMIT_DATA or RLIMIT_AS are not exceeded, but with a lower bound of 4096 (four megabytes) and an upper bound of 131072 (128 megabytes). If GCC is not able to calculate RAM on a particular platform, the lower bound is used. Setting this parameter very large effectively disables garbage collection. Setting this parameter and ggc-min-expand to zero causes a full collection to occur at every opportunity.

The maximum number of instruction reload should look backward for equivalent register. Increasing values mean more aggressive optimization, making the compilation time increase with probably slightly better performance.
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.
The maximum number of instructions ready to be issued the scheduler should consider at any given time during the first scheduling pass. Increasing values mean more thorough searches, making the compilation time increase with probably little benefit.
The maximum number of blocks in a region to be considered for interblock scheduling.
The maximum number of blocks in a region to be considered for pipelining in the selective scheduler.
The maximum number of insns in a region to be considered for interblock scheduling.
The maximum number of insns in a region to be considered for pipelining in the selective scheduler.
The minimum probability (in percents) of reaching a source block for interblock speculative scheduling.
The maximum number of iterations through CFG to extend regions. A value of 0 disables region extensions.
The maximum conflict delay for an insn to be considered for speculative motion.
The minimal probability of speculation success (in percents), so that speculative insns are scheduled.
The minimum probability an edge must have for the scheduler to save its state across it.
Minimal distance (in CPU cycles) between store and load targeting same memory locations.
The maximum size of the lookahead window of selective scheduling. It is a depth of search for available instructions.
The maximum number of times that an instruction is scheduled during selective scheduling. This is the limit on the number of iterations through which the instruction may be pipelined.
The maximum number of best instructions in the ready list that are considered for renaming in the selective scheduler.
The minimum value of stage count that swing modulo scheduler generates.
The maximum size measured as number of RTLs that can be recorded in an expression in combiner for a pseudo register as last known value of that register.
The maximum number of instructions the RTL combiner tries to combine.
Small integer constants can use a shared data structure, reducing the compiler's memory usage and increasing its speed. This sets the maximum value of a shared integer constant.
The minimum size of buffers (i.e. arrays) that receive stack smashing protection when -fstack-protector is used.
The minimum size of variables taking part in stack slot sharing when not optimizing.
Maximum number of statements allowed in a block that needs to be duplicated when threading jumps.
The maximum number of paths to consider when searching for jump threading opportunities. When arriving at a block, incoming edges are only considered if the number of paths to be searched so far multiplied by the number of incoming edges does not exhaust the specified maximum number of paths to consider.
Maximum number of fields in a structure treated in a field sensitive manner during pointer analysis.
Estimate on average number of instructions that are executed before prefetch finishes. The distance prefetched ahead is proportional to this constant. Increasing this number may also lead to less streams being prefetched (see simultaneous-prefetches).
Maximum number of prefetches that can run at the same time.
The size of cache line in L1 data cache, in bytes.
The size of L1 data cache, in kilobytes.
The size of L2 data cache, in kilobytes.
Whether the loop array prefetch pass should issue software prefetch hints for strides that are non-constant. In some cases this may be beneficial, though the fact the stride is non-constant may make it hard to predict when there is clear benefit to issuing these hints.

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

Minimum constant stride, in bytes, to start using prefetch hints for. If the stride is less than this threshold, prefetch hints will not be issued.

This setting is useful for processors that have hardware prefetchers, in which case there may be conflicts between the hardware prefetchers and the software prefetchers. If the hardware prefetchers have a maximum stride they can handle, it should be used here to improve the use of software prefetchers.

A value of -1 means we don't have a threshold and therefore prefetch hints can be issued for any constant stride.

This setting is only useful for strides that are known and constant.

The values for the C++17 variables "std::hardware_destructive_interference_size" and "std::hardware_constructive_interference_size". The destructive interference size is the minimum recommended offset between two independent concurrently-accessed objects; the constructive interference size is the maximum recommended size of contiguous memory accessed together. Typically both will be the size of an L1 cache line for the target, in bytes. For a generic target covering a range of L1 cache line sizes, typically the constructive interference size will be the small end of the range and the destructive size will be the large end.

The destructive interference size is intended to be used for layout, and thus has ABI impact. The default value is not expected to be stable, and on some targets varies with -mtune, so use of this variable in a context where ABI stability is important, such as the public interface of a library, is strongly discouraged; if it is used in that context, users can stabilize the value using this option.

The constructive interference size is less sensitive, as it is typically only used in a static_assert to make sure that a type fits within a cache line.

See also -Winterference-size.

The maximum number of stmts in a loop to be interchanged.
The minimum ratio between stride of two loops for interchange to be profitable.
The minimum ratio between the number of instructions and the number of prefetches to enable prefetching in a loop.
The minimum ratio between the number of instructions and the number of memory references to enable prefetching in a loop.
Whether the compiler should use the "canonical" type system. Should always be 1, which uses a more efficient internal mechanism for comparing types in C++ and Objective-C++. However, if bugs in the canonical type system are causing compilation failures, set this value to 0 to disable canonical types.
Switch initialization conversion refuses to create arrays that are bigger than switch-conversion-max-branch-ratio times the number of branches in the switch.
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 run away, consuming all of the memory available on the host machine. This parameter sets a limit on the length of the sets that are computed, which prevents the runaway behavior. Setting a value of 0 for this parameter allows an unlimited set length.
Maximum loop depth that is value-numbered optimistically. When the limit hits the innermost rpo-vn-max-loop-depth loops and the outermost loop in the loop nest are value-numbered optimistically and the remaining ones not.
Maximum number of alias-oracle queries we perform when looking for redundancies for loads and stores. If this limit is hit the search is aborted and the load or store is not considered redundant. The number of queries is algorithmically limited to the number of stores on all paths from the load to the function entry.
IRA uses regional register allocation by default. If a function contains more loops than the number given by this parameter, only at most the given number of the most frequently-executed loops form regions for regional register allocation.
Although IRA uses a sophisticated algorithm to compress the conflict table, the table can still require excessive amounts of memory for huge functions. If the conflict table for a function could be more than the size in MB given by this parameter, the register allocator instead uses a faster, simpler, and lower-quality algorithm that does not require building a pseudo-register conflict table.
IRA can be used to evaluate more accurate register pressure in loops for decisions to move loop invariants (see -O3). The number of available registers reserved for some other purposes is given by this parameter. Default of the parameter is the best found from numerous experiments.
Make IRA to consider matching constraint (duplicated operand number) heavily in all available alternatives for preferred register class. If it is set as zero, it means IRA only respects the matching constraint when it's in the only available alternative with an appropriate register class. Otherwise, it means IRA will check all available alternatives for preferred register class even if it has found some choice with an appropriate register class and respect the found qualified matching constraint.
Approximate function insn number in 1K units triggering simple local RA.
LRA tries to reuse values reloaded in registers in subsequent insns. This optimization is called inheritance. EBB is used as a region to do this optimization. The parameter defines a minimal fall-through edge probability in percentage used to add BB to inheritance EBB in LRA. The default value was chosen from numerous runs of SPEC2000 on x86-64.
Loop invariant motion can be very expensive, both in compilation time and in amount of needed compile-time memory, with very large loops. Loops with more basic blocks than this parameter won't have loop invariant motion optimization performed on them.
Building data dependencies is expensive for very large loops. This parameter limits the number of data references in loops that are considered for data dependence analysis. These large loops are no handled by the optimizations using loop data dependencies.
Sets a maximum number of hash table slots to use during variable tracking dataflow analysis of any function. If this limit is exceeded with variable tracking at assignments enabled, analysis for that function is retried without it, after removing all debug insns from the function. If the limit is exceeded even without debug insns, var tracking analysis is completely disabled for the function. Setting the parameter to zero makes it unlimited.
Sets a maximum number of recursion levels when attempting to map variable names or debug temporaries to value expressions. This trades compilation time for more complete debug information. If this is set too low, value expressions that are available and could be represented in debug information may end up not being used; setting this higher may enable the compiler to find more complex debug expressions, but compile time and memory use may grow.
Sets a threshold on the number of debug markers (e.g. begin stmt markers) to avoid complexity explosion at inlining or expanding to RTL. If a function has more such gimple stmts than the set limit, such stmts will be dropped from the inlined copy of a function, and from its RTL expansion.
Use uids starting at this parameter for nondebug insns. The range below the parameter is reserved exclusively for debug insns created by -fvar-tracking-assignments, but debug insns may get (non-overlapping) uids above it if the reserved range is exhausted.
IPA-SRA replaces a pointer which is known not be NULL with one or more new parameters only when the probability (in percent, relative to function entry) of it being dereferenced is higher than this parameter.
IPA-SRA replaces a pointer to an aggregate with one or more new parameters only when their cumulative size is less or equal to ipa-sra-ptr-growth-factor times the size of the original pointer parameter.
Additional maximum allowed growth of total size of new parameters that ipa-sra replaces a pointer to an aggregate with, if it points to a local variable that the caller only writes to and passes it as an argument to other functions.
Maximum pieces of an aggregate that IPA-SRA tracks. As a consequence, it is also the maximum number of replacements of a formal parameter.
The two Scalar Reduction of Aggregates passes (SRA and IPA-SRA) aim to replace scalar parts of aggregates with uses of independent scalar variables. These parameters control the maximum size, in storage units, of aggregate which is considered for replacement when compiling for speed (sra-max-scalarization-size-Ospeed) or size (sra-max-scalarization-size-Osize) respectively.
The maximum number of artificial accesses that Scalar Replacement of Aggregates (SRA) will track, per one local variable, in order to facilitate copy propagation.
When making copies of thread-local variables in a transaction, this parameter specifies the size in bytes after which variables are saved with the logging functions as opposed to save/restore code sequence pairs. This option only applies when using -fgnu-tm.
To avoid exponential effects in the Graphite loop transforms, the number of parameters in a Static Control Part (SCoP) is bounded. A value of zero can be used to lift the bound. A variable whose value is unknown at compilation time and defined outside a SCoP is a parameter of the SCoP.
Disable -fharden-control-flow-redundancy for functions with a larger number of blocks than the specified value. Zero removes any limit.
Force -fharden-control-flow-redundancy to use out-of-line checking for functions with a larger number of basic blocks than the specified value.
Loop blocking or strip mining transforms, enabled with -floop-block or -floop-strip-mine, strip mine each loop in the loop nest by a given number of iterations. The strip length can be changed using the loop-block-tile-size parameter.
Specifies number of statements visited during jump function offset discovery.
IPA-CP attempts to track all possible values and types passed to a function's parameter in order to propagate them and perform devirtualization. ipa-cp-value-list-size is the maximum number of values and types it stores per one formal parameter of a function.
IPA-CP calculates its own score of cloning profitability heuristics and performs those cloning opportunities with scores that exceed ipa-cp-eval-threshold.
Maximum depth of recursive cloning for self-recursive function.
Recursive cloning only when the probability of call being executed exceeds the parameter.
When using -fprofile-use option, IPA-CP will consider the measured execution count of a call graph edge at this percentage position in their histogram as the basis for its heuristics calculation.
The number of times interprocedural copy propagation expects recursive functions to call themselves.
Percentage penalty the recursive functions will receive when they are evaluated for cloning.
Percentage penalty functions containing a single call to another function will receive when they are evaluated for cloning.
IPA-CP is also capable to propagate a number of scalar values passed in an aggregate. ipa-max-agg-items controls the maximum number of such values per one parameter.
When IPA-CP determines that a cloning candidate would make the number of iterations of a loop known, it adds a bonus of ipa-cp-loop-hint-bonus to the profitability score of the candidate.
The maximum number of different predicates IPA will use to describe when loops in a function have known properties.
During its analysis of function bodies, IPA-CP employs alias analysis in order to track values pointed to by function parameters. In order not spend too much time analyzing huge functions, it gives up and consider all memory clobbered after examining ipa-max-aa-steps statements modifying memory.
Maximal number of boundary endpoints of case ranges of switch statement. For switch exceeding this limit, IPA-CP will not construct cloning cost predicate, which is used to estimate cloning benefit, for default case of the switch statement.
IPA-CP will analyze conditional statement that references some function parameter to estimate benefit for cloning upon certain constant value. But if number of operations in a parameter expression exceeds ipa-max-param-expr-ops, the expression is treated as complicated one, and is not handled by IPA analysis.
Specify desired number of partitions produced during WHOPR compilation. The number of partitions should exceed the number of CPUs used for compilation.
Size of minimal partition for WHOPR (in estimated instructions). This prevents expenses of splitting very small programs into too many partitions.
Size of max partition for WHOPR (in estimated instructions). to provide an upper bound for individual size of partition. Meant to be used only with balanced partitioning.
Maximal number of parallel processes used for LTO streaming.
The maximum number of namespaces to consult for suggestions when C++ name lookup fails for an identifier.
The maximum relative execution frequency (in percents) of the target block relative to a statement's original block to allow statement sinking of a statement. Larger numbers result in more aggressive statement sinking. A small positive adjustment is applied for statements with memory operands as those are even more profitable so sink.
The maximum number of conditional store pairs that can be sunk. Set to 0 if either vectorization (-ftree-vectorize) or if-conversion (-ftree-loop-if-convert) is disabled.
The smallest number of different values for which it is best to use a jump-table instead of a tree of conditional branches. If the value is 0, use the default for the machine.
The maximum code size growth ratio when expanding into a jump table (in percent). The parameter is used when optimizing for size.
The maximum code size growth ratio when expanding into a jump table (in percent). The parameter is used when optimizing for speed.
Set the maximum number of instructions executed in parallel in reassociated tree. This parameter overrides target dependent heuristics used by default if has non zero value.
Choose between the two available implementations of -fsched-pressure. Algorithm 1 is the original implementation and is the more likely to prevent instructions from being reordered. Algorithm 2 was designed to be a compromise between the relatively conservative approach taken by algorithm 1 and the rather aggressive approach taken by the default scheduler. It relies more heavily on having a regular register file and accurate register pressure classes. See haifa-sched.cc in the GCC sources for more details.

The default choice depends on the target.

Set the maximum number of existing candidates that are considered when seeking a basis for a new straight-line strength reduction candidate.
Enable buffer overflow detection for global objects. This kind of protection is enabled by default if you are using -fsanitize=address option. To disable global objects protection use --param asan-globals=0.
Enable buffer overflow detection for stack objects. This kind of protection is enabled by default when using -fsanitize=address. To disable stack protection use --param asan-stack=0 option.
Enable buffer overflow detection for memory reads. This kind of protection is enabled by default when using -fsanitize=address. To disable memory reads protection use --param asan-instrument-reads=0.
Enable buffer overflow detection for memory writes. This kind of protection is enabled by default when using -fsanitize=address. To disable memory writes protection use --param asan-instrument-writes=0 option.
Enable detection for built-in functions. This kind of protection is enabled by default when using -fsanitize=address. To disable built-in functions protection use --param asan-memintrin=0.
Enable detection of use-after-return. This kind of protection is enabled by default when using the -fsanitize=address option. To disable it use --param asan-use-after-return=0.

Note: By default the check is disabled at run time. To enable it, add "detect_stack_use_after_return=1" to the environment variable ASAN_OPTIONS.

If number of memory accesses in function being instrumented is greater or equal to this number, use callbacks instead of inline checks. E.g. to disable inline code use --param asan-instrumentation-with-call-threshold=0.
If nonzero, prefix calls to "memcpy", "memset" and "memmove" with __asan_ or __hwasan_ for -fsanitize=kernel-address or -fsanitize=kernel-hwaddress, respectively.
Enable hwasan instrumentation of statically sized stack-allocated variables. This kind of instrumentation is enabled by default when using -fsanitize=hwaddress and disabled by default when using -fsanitize=kernel-hwaddress. To disable stack instrumentation use --param hwasan-instrument-stack=0, and to enable it use --param hwasan-instrument-stack=1.
When using stack instrumentation, decide tags for stack variables using a deterministic sequence beginning at a random tag for each frame. With this parameter unset tags are chosen using the same sequence but beginning from 1. This is enabled by default for -fsanitize=hwaddress and unavailable for -fsanitize=kernel-hwaddress. To disable it use --param hwasan-random-frame-tag=0.
Enable hwasan instrumentation of dynamically sized stack-allocated variables. This kind of instrumentation is enabled by default when using -fsanitize=hwaddress and disabled by default when using -fsanitize=kernel-hwaddress. To disable instrumentation of such variables use --param hwasan-instrument-allocas=0, and to enable it use --param hwasan-instrument-allocas=1.
Enable hwasan checks on memory reads. Instrumentation of reads is enabled by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. To disable checking memory reads use --param hwasan-instrument-reads=0.
Enable hwasan checks on memory writes. Instrumentation of writes is enabled by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. To disable checking memory writes use --param hwasan-instrument-writes=0.
Enable hwasan instrumentation of builtin functions. Instrumentation of these builtin functions is enabled by default for both -fsanitize=hwaddress and -fsanitize=kernel-hwaddress. To disable instrumentation of builtin functions use --param hwasan-instrument-mem-intrinsics=0.
If the size of a local variable in bytes is smaller or equal to this number, directly poison (or unpoison) shadow memory instead of using run-time callbacks.
Emit special instrumentation for accesses to volatiles.
Emit instrumentation calls to __tsan_func_entry() and __tsan_func_exit().
Maximum number of instructions to copy when duplicating blocks on a finite state automaton jump thread path.
threader-debug=[none|all] Enables verbose dumping of the threader solver.
Chunk size of omp schedule for loops parallelized by parloops.
Schedule type of omp schedule for loops parallelized by parloops (static, dynamic, guided, auto, runtime).
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.
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.
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.
Specifies the type of debug output to be issued for ranges.
The minimum percentage of memory references that must be optimized away for the unroll-and-jam transformation to be considered profitable.
The maximum number of times the outer loop should be unrolled by the unroll-and-jam transformation.
Maximum permissible cost for the sequence that would be generated by the RTL if-conversion pass for a branch that is considered unpredictable.
If -fvariable-expansion-in-unroller is used, the maximum number of times that an individual variable will be expanded during loop unrolling.
Maximum probability of the entry BB of split region (in percent relative to entry BB of the function) to make partial inlining happen.
Maximum number of strings for which strlen optimization pass will track string lengths.
The threshold ratio for performing partial redundancy elimination after reload.
The threshold ratio of critical edges execution count that permit performing redundancy elimination after reload.
The maximum number of insns in loop header duplicated by the copy loop headers pass.
Enable loop epilogue vectorization using smaller vector size.
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.
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.
Enable loop vectorization of floating point inductions.
Maximum number of basic blocks before VRP uses a sparse bitmap cache.
Maximum number of outgoing edges in a switch before VRP will not process it.
Maximum number of basic blocks for VRP to use a basic cache vector.
Maximum number of bits for which we avoid creating FMAs.
Whether the target fully pipelines FMA instructions. If non-zero, reassociation considers the benefit of parallelizing FMA's multiplication part and addition part, assuming FMUL and FMA use the same units that can also do FADD.
A threshold on the average loop count considered by the swing modulo scheduler.
The number of cycles the swing modulo scheduler considers when checking conflicts using DFA.
Whether codegen errors should be ICEs when -fchecking.
A factor for tuning the upper bound that swing modulo scheduler uses for scheduling a loop.
The max number of reload pseudos which are considered during spilling a non-reload pseudo.
Maximum depth of sqrt chains to use when synthesizing exponentiation by a real constant.
Maximum number of active local stores in RTL dead store elimination.
Enable asan allocas/VLAs protection.
Bound on the cost of an expression to compute the number of iterations.
Maximum number of isl operations, 0 means unlimited.
Maximum number of arrays per scop.
Max. size of loc list for which reverse ops should be added.
Scale factor to apply to the number of statements in a threading path crossing a loop backedge when comparing to --param=max-jump-thread-duplication-stmts.
Maximum number of nested calls to search for control dependencies during uninitialized variable analysis.
Maximum number of predicates anded for each predicate ored in the normalized predicate chain.
Maximum number of predicates ored in the normalized predicate chain.
Hardware autoprefetcher scheduler model control flag. Number of lookahead cycles the model looks into; at ' ' only enable instruction sorting heuristic.
The maximum number of instructions that an inner loop can have before the loop versioning pass considers it too big to copy.
The maximum number of instructions that an outer loop can have before the loop versioning pass considers it too big to copy, discounting any instructions in inner loops that directly benefit from versioning.
The maximum number of SSA_NAME assignments to follow in determining a property of a variable such as its value. This limits the number of iterations or recursive calls GCC performs when optimizing certain statements or when determining their validity prior to issuing diagnostics.
Maximum size of a single store merging region in bytes.
The number of elements for which hash table verification is done for each searched element.
Maximum number of VALUEs handled during a single find_base_term call.
The maximum number of exploded nodes per program point within the analyzer, before terminating analysis of that point.
The maximum number of constraints per state.
The minimum number of supernodes within a function for the analyzer to consider summarizing its effects at call sites.
The maximum depth of exploded nodes that should appear in a dot dump before switching to a less verbose format.
The maximum number of times a callsite can appear in a call stack within the analyzer, before terminating analysis of a call that would recurse deeper.
The maximum depth of a symbolic value, before approximating the value as unknown.
The maximum number of infeasible edges to reject before declaring a diagnostic as infeasible.
The number of executions of a basic block which is considered hot. The parameter is used only in GIMPLE FE.
The maximum number of 'after supernode' exploded nodes within the analyzer per supernode, before terminating analysis.
The number of bytes at which to ellipsize string literals in analyzer text art diagrams.
The ideal width in characters of text art diagrams generated by the analyzer.
The number of literal bytes to show at the head of a string literal in text art when ellipsizing it.
The number of literal bytes to show at the tail of a string literal in text art when ellipsizing it.
Maximum depth of logical expression evaluation ranger will look through when evaluating outgoing edge ranges.
Maximum depth of instruction chains to consider for recomputation in the outgoing range calculator.
Maximum number of relations the oracle will register in a basic block.
Minimum page size for warning purposes.
Specify mode of OpenACC `kernels' constructs handling. With --param=openacc-kernels=decompose, OpenACC `kernels' constructs are decomposed into parts, a sequence of compute constructs, each then handled individually. This is work in progress. With --param=openacc-kernels=parloops, OpenACC `kernels' constructs are handled by the parloops pass, en bloc. This is the current default.
Control whether the -fopt-info-omp-note and applicable -fdump-tree-*-details options emit OpenACC privatization diagnostics. With --param=openacc-privatization=quiet, don't diagnose. This is the current default. With --param=openacc-privatization=noisy, do diagnose.

The following choices of name are available on AArch64 targets:

When vectorizing, consider using multiple different approaches and use the cost model to choose the cheapest one. This includes:
  • Trying both SVE and Advanced SIMD, when SVE is available.
  • Trying to use 64-bit Advanced SIMD vectors for the smallest data elements, rather than using 128-bit vectors for everything.
  • Trying to use "unpacked" SVE vectors for smaller elements. This includes storing smaller elements in larger containers and accessing elements with extending loads and truncating stores.
The number of Newton iterations for calculating the reciprocal for float type. The precision of division is proportional to this param when division approximation is enabled. The default value is 1.
The number of Newton iterations for calculating the reciprocal for double type. The precision of division is propotional to this param when division approximation is enabled. The default value is 2.
Force an ISA selection strategy for auto-vectorization. Accepts values from 0 to 4, inclusive.
0
Use the default heuristics.
1
Use only Advanced SIMD for auto-vectorization.
2
Use only SVE for auto-vectorization.
3
Use both Advanced SIMD and SVE. Prefer Advanced SIMD when the costs are deemed equal.
4
Use both Advanced SIMD and SVE. Prefer SVE when the costs are deemed equal.

The default value is 0.

Fine-grained policy for load pairs. With --param=aarch64-ldp-policy=default, use the policy of the tuning structure. This is the current default. With --param=aarch64-ldp-policy=always, emit ldp regardless of alignment. With --param=aarch64-ldp-policy=never, do not emit ldp. With --param=aarch64-ldp-policy=aligned, emit ldp only if the source pointer is aligned to at least double the alignment of the type.
Fine-grained policy for store pairs. With --param=aarch64-stp-policy=default, use the policy of the tuning structure. This is the current default. With --param=aarch64-stp-policy=always, emit stp regardless of alignment. With --param=aarch64-stp-policy=never, do not emit stp. With --param=aarch64-stp-policy=aligned, emit stp only if the source pointer is aligned to at least double the alignment of the type.
Limit on the number of alias checks performed by the AArch64 load/store pair fusion pass when attempting to form an ldp/stp. Higher values make the pass more aggressive at re-ordering loads over stores, at the expense of increased compile time.
Param to control which writeback opportunities we try to handle in the AArch64 load/store pair fusion pass. A value of zero disables writeback handling. One means we try to form pairs involving one or more existing individual writeback accesses where possible. A value of two means we also try to opportunistically form writeback opportunities by folding in trailing destructive updates of the base register used by a pair.
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.
The vectorizer will use available tuning information to determine whether it would be beneficial to unroll the main vectorized loop and by how much. This parameter set's the upper bound of how much the vectorizer will unroll the main loop. The default value is four.

The following choices of name are available on GCN targets:

Preferred vectorization factor: default, 32, 64.

The following choices of name are available on i386 and x86_64 targets:

Instructions number above which STFL stall penalty can be compensated.
The maximum number of use and def visits when discovering a STV chain before the discovery is aborted.

GCC supports a number of command-line options that control adding run-time instrumentation to the code it normally generates. For example, one purpose of instrumentation is collect profiling statistics for use in finding program hot spots, code coverage analysis, or profile-guided optimizations. Another class of program instrumentation is adding run-time checking to detect programming errors like invalid pointer dereferences or out-of-bounds array accesses, as well as deliberately hostile attacks such as stack smashing or C++ vtable hijacking. There is also a general hook which can be used to implement other forms of tracing or function-level instrumentation for debug or program analysis purposes.

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.

Add code so that program flow arcs are instrumented. During execution the program records how many times each branch and call is executed and how many times it is taken or returns. On targets that support constructors with priority support, profiling properly handles constructors, destructors and C++ constructors (and destructors) of classes which are used as a type of a global variable.

When the compiled program exits it saves this data to a file called auxname.gcda for each source file. The data may be used for profile-directed optimizations (-fbranch-probabilities), or for test coverage analysis (-ftest-coverage). Each object file's auxname is generated from the name of the output file, if explicitly specified and it is not the final executable, otherwise it is the basename of the source file. In both cases any suffix is removed (e.g. foo.gcda for input file dir/foo.c, or dir/foo.gcda for output file specified as -o dir/foo.o).

Note that if a command line directly links source files, the corresponding .gcda files will be prefixed with the unsuffixed name of the output file. E.g. "gcc a.c b.c -o binary" would generate binary-a.gcda and binary-b.gcda files.

Add code so that program conditions are instrumented. During execution the program records what terms in a conditional contributes to a decision, which can be used to verify that all terms in a Boolean function are tested and have an independent effect on the outcome of a decision. The result can be read with "gcov --conditions".
This option is used to compile and link code instrumented for coverage analysis. The option is a synonym for -fprofile-arcs -ftest-coverage (when compiling) and -lgcov (when linking). See the documentation for those options for more details.
  • Compile the source files with -fprofile-arcs plus optimization and code generation options. For test coverage analysis, use the additional -ftest-coverage option. You do not need to profile every source file in a program.
  • Compile the source files additionally with -fprofile-abs-path to create absolute path names in the .gcno files. This allows gcov to find the correct sources in projects where compilations occur with different working directories.
  • Link your object files with -lgcov or -fprofile-arcs (the latter implies the former).
  • Run the program on a representative workload to generate the arc profile information. This may be repeated any number of times. You can run concurrent instances of your program, and provided that the file system supports locking, the data files will be correctly updated. Unless a strict ISO C dialect option is in effect, "fork" calls are detected and correctly handled without double counting.

    Moreover, an object file can be recompiled multiple times and the corresponding .gcda file merges as long as the source file and the compiler options are unchanged.

  • For profile-directed optimizations, compile the source files again with the same optimization and code generation options plus -fbranch-probabilities.
  • For test coverage analysis, use gcov to produce human readable information from the .gcno and .gcda files. Refer to the gcov documentation for further information.

With -fprofile-arcs, for each function of your program GCC creates a program flow graph, then finds a spanning tree for the graph. Only arcs that are not on the spanning tree have to be instrumented: the compiler adds code to count the number of times that these arcs are executed. When an arc is the only exit or only entrance to a block, the instrumentation code can be added to the block; otherwise, a new basic block must be created to hold the instrumentation code.

With -fcondition-coverage, for each conditional in your program GCC creates a bitset and records the exercised boolean values that have an independent effect on the outcome of that expression.

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

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.

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.
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.
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.
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, otherwise the default method is single.

If atomic is selected, then the profile information is updated using atomic operations on a best-effort basis. Ideally, the profile information is updated through atomic operations in hardware. If the target platform does not support the required atomic operations in hardware, however, libatomic is available, then the profile information is updated through calls to libatomic. If the target platform neither supports the required atomic operations in hardware nor libatomic, then the profile information is not atomically updated and a warning is issued. In this case, the obtained profiling information may be corrupt for multi-threaded applications.

For performance reasons, if 64-bit counters are used for the profiling information and the target platform only supports 32-bit atomic operations in hardware, then the performance critical profiling updates are done using two 32-bit atomic operations for each counter update. If a signal interrupts these two operations updating a counter, then the profiling information may be in an inconsistent state.

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

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.

Control level of reproducibility of profile gathered by "-fprofile-generate". This makes it possible to rebuild program with same outcome which is useful, for example, for distribution packages.

With -fprofile-reproducible=serial the profile gathered by -fprofile-generate is reproducible provided the trained program behaves the same at each invocation of the train run, it is not multi-threaded and profile data streaming is always done in the same order. Note that profile streaming happens at the end of program run but also before "fork" function is invoked.

Note that it is quite common that execution counts of some part of programs depends, for example, on length of temporary file names or memory space randomization (that may affect hash-table collision rate). Such non-reproducible part of programs may be annotated by "no_instrument_function" function attribute. gcov-dump with -l can be used to dump gathered data and verify that they are indeed reproducible.

With -fprofile-reproducible=parallel-runs collected profile stays reproducible regardless the order of streaming of the data into gcda files. This setting makes it possible to run multiple instances of instrumented program in parallel (such as with "make -j"). This reduces quality of gathered data, in particular of indirect call profiling.

Enable AddressSanitizer, a fast memory error detector. Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. The option enables -fsanitize-address-use-after-scope. See https://github.com/google/sanitizers/wiki/AddressSanitizer for more details. The run-time behavior can be influenced using the ASAN_OPTIONS environment variable. When set to "help=1", the available options are shown at startup of the instrumented program. See https://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flags for a list of supported options. The option cannot be combined with -fsanitize=thread or -fsanitize=hwaddress. Note that the only target -fsanitize=hwaddress is currently supported on is AArch64.

To get more accurate stack traces, it is possible to 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). 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.

Enable AddressSanitizer for Linux kernel. See https://github.com/google/kernel-sanitizers for more details.
Enable Hardware-assisted AddressSanitizer, which uses a hardware ability to ignore the top byte of a pointer to allow the detection of 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. See https://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html for more details. The run-time behavior can be influenced using the HWASAN_OPTIONS environment variable. When set to "help=1", the available options are shown at startup of the instrumented program. The option cannot be combined with -fsanitize=thread or -fsanitize=address, and is currently only available on AArch64.
Enable 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. These differences are to avoid hwasan library initialization calls and to account for the stack pointer having a different value in its top byte.

Note: This option has different defaults to the -fsanitize=hwaddress. Instrumenting the stack and alloca calls are not on by default but are still possible by specifying the command-line options --param hwasan-instrument-stack=1 and --param hwasan-instrument-allocas=1 respectively. Using a random frame tag is not implemented for kernel instrumentation.

Instrument 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 invalid operation only when both pointers are non-null.
Instrument 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 invalid operation only when both pointers are non-null.
Enable 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 and 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 is specifically designed for linux kernels that enable the CONFIG_SHADOW_CALL_STACK option. For the user space programs, runtime support is not currently provided in libc and libgcc. Users who want to use this feature in user space need to provide their own support for the runtime. 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 is 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.

Enable ThreadSanitizer, a fast data race detector. Memory access instructions are instrumented to detect data race bugs. See https://github.com/google/sanitizers/wiki#threadsanitizer for more details. The run-time behavior can be influenced using the TSAN_OPTIONS environment variable; see https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags for a list of supported options. The option cannot be combined with -fsanitize=address, -fsanitize=leak.

Note that sanitized atomic builtins cannot throw exceptions when operating on invalid memory addresses with non-call exceptions (-fnon-call-exceptions).

Enable LeakSanitizer, a memory leak detector. This option only matters for linking of executables. The executable is linked against a library that overrides "malloc" and other allocator functions. See https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer for more details. The run-time behavior can be influenced using the LSAN_OPTIONS environment variable. The option cannot be combined with -fsanitize=thread.
Enable UndefinedBehaviorSanitizer, a fast undefined behavior detector. Various computations are instrumented to detect undefined behavior at runtime. See https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html for more details. The run-time behavior can be influenced using the UBSAN_OPTIONS environment variable. Current suboptions are:
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.
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.
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.
Detect integer division by zero.
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.
This option instructs the compiler to check that the size of a variable length array is positive.
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.
This option enables return statement checking. Programs built with this option turned on will issue an error message when the end of a non-void function is reached without actually returning a value. This option works in C++ only.
This option enables signed integer overflow checking. We check that the result of "+", "*", and both unary and binary "-" does not overflow in the signed arithmetics. This also detects "INT_MIN / -1" signed division. Note, integer promotion rules must be taken into account. That is, the following is not an overflow:
signed char a = SCHAR_MAX;
a++;
This option enables instrumentation of array bounds. Various out of bounds accesses are detected. Flexible array members, flexible array member-like arrays, and initializers of variables with static storage are not instrumented, with the exception of flexible array member-like arrays for which "-fstrict-flex-arrays" or "-fstrict-flex-arrays=" options or "strict_flex_array" attributes say they shouldn't be treated like flexible array member-like arrays.
This option enables strict instrumentation of array bounds. Most out of bounds accesses are detected, including flexible array member-like arrays. Initializers of variables with static storage are not instrumented.
This option enables checking of alignment of pointers when they are dereferenced, or when a reference is bound to insufficiently aligned target, or when a method or constructor is invoked on insufficiently aligned object.
This option enables instrumentation of memory references using the "__builtin_dynamic_object_size" function. Various out of bounds pointer accesses are detected.
Detect floating-point division by zero. Unlike other similar options, -fsanitize=float-divide-by-zero is not enabled by -fsanitize=undefined, since floating-point division by zero can be a legitimate way of obtaining infinities and NaNs.
This option enables floating-point type to integer conversion checking. We check that the result of the conversion does not overflow. Unlike other similar options, -fsanitize=float-cast-overflow is not enabled by -fsanitize=undefined. This option does not work well with "FE_INVALID" exceptions enabled.
This option enables instrumentation of calls, checking whether null values are not passed to arguments marked as requiring a non-null value by the "nonnull" function attribute.
This option enables instrumentation of return statements in functions marked with "returns_nonnull" function attribute, to detect returning of null values from such functions.
This option enables instrumentation of loads from bool. If a value other than 0/1 is loaded, a run-time error is issued.
This option enables instrumentation of loads from an enum type. If a value outside the range of values for the enum type is loaded, a run-time error is issued.
This option enables instrumentation of 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.
This option enables instrumentation of pointer arithmetics. If the pointer arithmetics overflows, a run-time error is issued.
This option enables instrumentation of arguments to selected builtin functions. If an invalid value is passed to such arguments, a run-time error is issued. E.g. passing 0 as the argument to "__builtin_ctz" or "__builtin_clz" invokes undefined behavior and is diagnosed by this option.

Note that sanitizers tend to increase the rate of false positive warnings, most notably those around -Wmaybe-uninitialized. We recommend against combining -Werror and [the use of] sanitizers.

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

This option disables all previously enabled sanitizers. -fsanitize=all is not allowed, as some sanitizers cannot be used together.
This option forces GCC to use custom shadow offset in AddressSanitizer checks. It is useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer.
Sanitize global variables in selected user-defined sections. si may contain wildcards.
-fsanitize-recover= controls error recovery mode for sanitizers mentioned in 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. This 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 program then exits with a non-zero exit code.

Currently this feature only works for -fsanitize=undefined (and its suboptions except for -fsanitize=unreachable and -fsanitize=return), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero, -fsanitize=bounds-strict, -fsanitize=kernel-address and -fsanitize=address. For these sanitizers error recovery is turned on by default, except -fsanitize=address, for which this feature is experimental. -fsanitize-recover=all and -fno-sanitize-recover=all is also accepted, the former enables recovery for all sanitizers that support it, the latter disables recovery for all sanitizers that support it.

Even if a recovery mode is turned on the compiler side, it needs to be also enabled on the runtime library side, otherwise the failures are still fatal. The runtime library defaults to "halt_on_error=0" for ThreadSanitizer and UndefinedBehaviorSanitizer, while 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
Enable sanitization of local variables to detect use-after-scope bugs. The option sets -fstack-reuse to none.
The -fsanitize-trap= option instructs the compiler to report for sanitizers mentioned in comma-separated list of opts undefined behavior using "__builtin_trap" rather than a "libubsan" library routine. If this option is enabled for certain sanitizer, it takes precedence over the -fsanitizer-recover= for that sanitizer, "__builtin_trap" will be emitted and be fatal regardless of whether recovery is enabled or disabled using -fsanitize-recover=.

The advantage of this is that the "libubsan" library is not needed and is not linked in, so this is usable even in freestanding environments.

Currently this feature works with -fsanitize=undefined (and its suboptions except for -fsanitize=vptr), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero and -fsanitize=bounds-strict. "-fsanitize-trap=all" can be also specified, which enables it for "undefined" suboptions, -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero and -fsanitize=bounds-strict. If "-fsanitize-trap=undefined" or "-fsanitize-trap=all" is used and "-fsanitize=vptr" is enabled on the command line, the instrumentation is silently ignored as the instrumentation always needs "libubsan" support, -fsanitize-trap=vptr is not allowed.

The -fsanitize-undefined-trap-on-error option is deprecated equivalent of -fsanitize-trap=all.
Enable coverage-guided fuzzing code instrumentation. Inserts a call to "__sanitizer_cov_trace_pc" into every basic block.
Enable dataflow guided fuzzing code instrumentation. Inserts a call to "__sanitizer_cov_trace_cmp1", "__sanitizer_cov_trace_cmp2", "__sanitizer_cov_trace_cmp4" or "__sanitizer_cov_trace_cmp8" for integral comparison with both operands variable or "__sanitizer_cov_trace_const_cmp1", "__sanitizer_cov_trace_const_cmp2", "__sanitizer_cov_trace_const_cmp4" or "__sanitizer_cov_trace_const_cmp8" for integral comparison with one operand constant, "__sanitizer_cov_trace_cmpf" or "__sanitizer_cov_trace_cmpd" for float or double comparisons and "__sanitizer_cov_trace_switch" for switch statements.
Enable code instrumentation of control-flow transfers to increase program security by checking that target addresses of control-flow transfer instructions (such as indirect function call, function return, indirect jump) are valid. This prevents diverting the flow of control to an unexpected target. This is intended to protect against such threats as Return-oriented Programming (ROP), and similarly call/jmp-oriented programming (COP/JOP).

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

To override -fcf-protection, -fcf-protection=none needs to be added and then with -fcf-protection=xxx.

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

The macro "__CET__" is defined when -fcf-protection is used. The first bit of "__CET__" is set to 1 for the value "branch" and the second bit of "__CET__" is set to 1 for the "return".

You can also use the "nocf_check" attribute to identify which functions and calls should be skipped from instrumentation.

Currently the x86 GNU/Linux target provides an implementation based on Intel Control-flow Enforcement Technology (CET) which works for i686 processor or newer.

For every logical test that survives gimple optimizations and is not the condition in a conditional branch (for example, conditions tested for conditional moves, or to store in boolean variables), emit extra code to compute and verify the reversed condition, and to call "__builtin_trap" if the results do not match. Use with -fharden-conditional-branches to cover all conditionals.
For every non-vectorized conditional branch that survives gimple optimizations, emit extra code to compute and verify the reversed condition, and to call "__builtin_trap" if the result is unexpected. Use with -fharden-compares to cover all conditionals.
Emit extra code to set booleans when entering basic blocks, and to verify and trap, at function exits, when the booleans do not form an execution path that is compatible with the control flow graph.

Verification takes place before returns, before mandatory tail calls (see below) and, optionally, before escaping exceptions with -fhardcfr-check-exceptions, before returning calls with -fhardcfr-check-returning-calls, and before noreturn calls with -fhardcfr-check-noreturn-calls). Tuning options --param hardcfr-max-blocks and --param hardcfr-max-inline-blocks are available.

Tail call optimization takes place too late to affect control flow redundancy, but calls annotated as mandatory tail calls by language front-ends, and any calls marked early enough as potential tail calls would also have verification issued before the call, but these possibilities are merely theoretical, as these conditions can only be met when using custom compiler plugins.

Disable -fharden-control-flow-redundancy in leaf functions.
When -fharden-control-flow-redundancy is active, check the recorded execution path against the control flow graph at exception escape points, as if the function body was wrapped with a cleanup handler that performed the check and reraised. This option is enabled by default; use -fno-hardcfr-check-exceptions to disable it.
When -fharden-control-flow-redundancy is active, check the recorded execution path against the control flow graph before any function call immediately followed by a return of its result, if any, so as to not prevent tail-call optimization, whether or not it is ultimately optimized to a tail call.

This option is enabled by default whenever sibling call optimizations are enabled (see -foptimize-sibling-calls), but it can be enabled (or disabled, using its negated form) explicitly, regardless of the optimizations.

When -fharden-control-flow-redundancy is active, check the recorded execution path against the control flow graph before "noreturn" calls, either all of them (always), those that aren't expected to return control to the caller through an exception (no-xthrow, the default), those that may not return control to the caller through an exception either (nothrow), or none of them (never).

Checking before a "noreturn" function that may return control to the caller through an exception may cause checking to be performed more than once, if the exception is caught in the caller, whether by a handler or a cleanup. When -fhardcfr-check-exceptions is also enabled, the compiler will avoid associating a "noreturn" call with the implicitly-added cleanup handler, since it would be redundant with the check performed before the call, but other handlers or cleanups in the function, if activated, will modify the recorded execution path and check it again when another checkpoint is hit. The checkpoint may even be another "noreturn" call, so checking may end up performed multiple times.

Various optimizers may cause calls to be marked as "noreturn" and/or "nothrow", even in the absence of the corresponding attributes, which may affect the placement of checks before calls, as well as the addition of implicit cleanup handlers for them. This unpredictability, and the fact that raising and reraising exceptions frequently amounts to implicitly calling "noreturn" functions, have made no-xthrow the default setting for this option: it excludes from the "noreturn" treatment only internal functions used to (re)raise exceptions, that are not affected by these optimizations.

Enable a set of flags for C and C++ that improve the security of the generated code without affecting its ABI. The precise flags enabled may change between major releases of GCC, but are currently:

-D_FORTIFY_SOURCE=3 -D_GLIBCXX_ASSERTIONS -ftrivial-auto-var-init=zero -fPIE -pie -Wl,-z,relro,-z,now -fstack-protector-strong -fstack-clash-protection -fcf-protection=full (x86 GNU/Linux only)

The list of options enabled by -fhardened can be generated using the --help=hardened option.

When the system glibc is older than 2.35, -D_FORTIFY_SOURCE=2 is used instead.

This option is intended to be used in production builds, not merely in debug builds.

Currently, -fhardened is only supported on GNU/Linux targets.

-fhardened only enables a particular option if it wasn't already specified anywhere on the command line. For instance, -fhardened -fstack-protector will only enable -fstack-protector, but not -fstack-protector-strong.

Emit extra code to check for buffer overflows, such as stack smashing attacks. This is done by adding a guard variable to functions with vulnerable objects. This includes functions that call "alloca", and functions with buffers larger than or equal to 8 bytes. The guards are initialized when a function is entered and then checked when the function exits. If a guard check fails, an error message is printed and the program exits. Only variables that are actually allocated on the stack are considered, optimized away variables or variables allocated in registers don't count.
Like -fstack-protector except that all functions are protected.
Like -fstack-protector but includes additional functions to be protected --- those that have local array definitions, or have references to local frame addresses. Only variables that are actually allocated on the stack are considered, optimized away variables or variables allocated in registers don't count.
Like -fstack-protector but only protects those functions which have the "stack_protect" attribute.
Generate code to verify that you do not go beyond the boundary of the stack. You should specify this flag if you are running in an environment with multiple threads, but you only rarely need to specify it in a single-threaded environment since stack overflow is automatically detected on nearly all systems if there is only one stack.

Note that this switch does not actually cause checking to be done; the operating system or the language runtime must 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, specific means use the best checking method and is equivalent to bare -fstack-check.

Old-style checking is a generic mechanism that requires no specific target support in the compiler but comes with the following drawbacks:

1.
Modified allocation strategy for large objects: they are always allocated dynamically if their size exceeds a fixed threshold. Note this may change the semantics of some code.
2.
Fixed limit on the size of the static frame of functions: when it is topped by a particular function, stack checking is not reliable and a warning is issued by the compiler.
3.
Inefficiency: because of both the modified allocation strategy and the generic implementation, code performance is hampered.

Note that old-style stack checking is also the fallback method for specific if no target support has been added in the compiler.

-fstack-check= is designed for Ada's needs to detect infinite recursion and stack overflows. specific is an excellent choice when compiling Ada code. It is not generally sufficient to protect against stack-clash attacks. To protect against those you want -fstack-clash-protection.

Generate 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. Thus, it prevents allocations from jumping over any stack guard page provided by the operating system.

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

Generate code to ensure that the stack does not grow beyond a certain value, either the value of a register or the address of a symbol. If a larger stack is required, a signal is raised at run time. For most targets, the signal is raised before the stack overruns the boundary, so it is possible to catch the signal without taking special precautions.

For instance, if the stack starts at absolute address 0x80000000 and grows downwards, you can use the flags -fstack-limit-symbol=__stack_limit and -Wl,--defsym,__stack_limit=0x7ffe0000 to enforce a stack limit of 128KB. Note that this may only work with the GNU linker.

You can locally override stack limit checking by using the "no_stack_limit" function attribute.

Generate code to automatically split the stack before it overflows. The resulting program has a discontiguous stack which can only overflow if the program is unable to allocate any more memory. This is most useful when running threaded programs, as it is no longer necessary to calculate a good stack size to use for each thread. This is currently only implemented for the x86 targets running GNU/Linux.

When code compiled with -fsplit-stack calls code compiled without -fsplit-stack, there may not be much stack space available for the latter code to run. If compiling all code, including library code, with -fsplit-stack is not an option, then the linker can fix up these calls so that the code compiled without -fsplit-stack always has a large stack. Support for this is implemented in the gold linker in GNU binutils release 2.21 and later.

Disable stack scrubbing entirely, ignoring any "strub" attributes. See
Functions default to "strub" mode "disabled", and apply strictly the restriction that only functions associated with "strub"-"callable" modes ("at-calls", "callable" and "always_inline" "internal") are "callable" by functions with "strub"-enabled modes ("at-calls" and "internal").
Restore the default stack scrub ("strub") setting, namely, "strub" is only enabled as required by "strub" attributes associated with function and data types. "Relaxed" means that strub contexts are only prevented from calling functions explicitly associated with "strub" mode "disabled". This option is only useful to override other -fstrub=* options that precede it in the command line.
Enable "at-calls" "strub" mode where viable. The primary use of this option is for testing. It exercises the "strub" machinery in scenarios strictly local to a translation unit. This "strub" mode modifies function interfaces, so any function that is visible to other translation units, or that has its address taken, will not be affected by this option. Optimization options may also affect viability. See the "strub" attribute documentation for details on viability and eligibility requirements.
Enable "internal" "strub" mode where viable. The primary use of this option is for testing. This option is intended to exercise thoroughly parts of the "strub" machinery that implement the less efficient, but interface-preserving "strub" mode. Functions that would not be affected by this option are quite uncommon.
Enable some "strub" mode where viable. When both strub modes are viable, "at-calls" is preferred. -fdump-ipa-strubm adds function attributes that tell which mode was selected for each function. The primary use of this option is for testing, to exercise thoroughly the "strub" machinery.
This option is only available when compiling C++ code. It turns on (or off, if using -fvtable-verify=none) the security feature that verifies at run time, for every virtual call, that the vtable pointer through which the call is made is valid for the type of the object, and has not been corrupted or overwritten. If an invalid vtable pointer is detected at run time, an error is reported and execution of the program is immediately halted.

This option causes run-time data structures to be built at program startup, which are used for verifying the vtable pointers. The options std and preinit control the timing of when these data structures are built. In both cases the data structures are built before execution reaches "main". Using -fvtable-verify=std causes the data structures to be built after shared libraries have been loaded and initialized. -fvtable-verify=preinit causes them to be built before shared libraries have been loaded and initialized.

If this option appears multiple times in the command line with different values specified, none takes highest priority over both std and preinit; preinit takes priority over std.

When used in conjunction with -fvtable-verify=std or -fvtable-verify=preinit, causes debug versions of the runtime functions for the vtable verification feature to be called. This flag also causes the compiler to log information about which vtable pointers it finds for each class. This information is written to a file named vtv_set_ptr_data.log in the directory named by the environment variable VTV_LOGS_DIR if that is defined or the current working directory otherwise.

Note: This feature appends data to the log file. If you want a fresh log file, be sure to delete any existing one.

This is a debugging flag. When used in conjunction with -fvtable-verify=std or -fvtable-verify=preinit, this causes the compiler to keep track of the total number of virtual calls it encounters and the number of verifications it inserts. It also counts the number of calls to certain run-time library functions that it inserts and logs this information for each compilation unit. The compiler writes this information to a file named vtv_count_data.log in the directory named by the environment variable VTV_LOGS_DIR if that is defined or the current working directory otherwise. It also counts the size of the vtable pointer sets for each class, and writes this information to vtv_class_set_sizes.log in the same directory.

Note: This feature appends data to the log files. To get fresh log files, be sure to delete any existing ones.

Generate instrumentation calls for entry and exit to functions. Just after function entry and just before function exit, the following profiling functions are called with the address of the current function and its call site. (On some platforms, "__builtin_return_address" does not work beyond the current function, so the call site information may not be available to the profiling functions otherwise.)
void __cyg_profile_func_enter (void *this_fn,
                               void *call_site);
void __cyg_profile_func_exit  (void *this_fn,
                               void *call_site);

The first argument is the address of the start of the current function, which may be looked up exactly in the symbol table.

This instrumentation is also done for functions expanded inline in other functions. The profiling calls indicate where, conceptually, the inline function is entered and exited. This means that addressable versions of such functions must be available. If all your uses of a function are expanded inline, this may mean an additional expansion of code size. If you use "extern inline" in your C code, an addressable version of such functions must be provided. (This is normally the case anyway, but if you get lucky and the optimizer always expands the functions inline, you might have gotten away without providing static copies.)

A function may be given the attribute "no_instrument_function", in which case this instrumentation is not done. This can be used, for example, for the profiling functions listed above, high-priority interrupt routines, and any functions from which the profiling functions cannot safely be called (perhaps signal handlers, if the profiling routines generate output or allocate memory).

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.

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

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

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.

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.

Predefine name as a macro, with definition 1.
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.

Cancel any previous definition of name, either built in or provided with a -D option.
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.

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.

Do not predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined.
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.
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.

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.

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.

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.

Disable dependency generation for compiled module interfaces.
This option instructs CPP to add a phony target for each dependency other than the main file, causing each to depend on nothing. These dummy rules work around errors make gives if you remove header files without updating the Makefile to match.

This is typical output:

test.o: test.c test.h

test.h:
Change the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as .c, and appends the platform's usual object suffix. The result is the target.

An -MT option sets the target to be exactly the string you specify. If you want multiple targets, you can specify them as a single argument to -MT, or use multiple -MT options.

For example, -MT '$(objpfx)foo.o' might give

$(objpfx)foo.o: foo.c
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 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.

Like -MD except mention only user header files, not system header files.
Indicate to the preprocessor that the input file has already been preprocessed. This suppresses things like macro expansion, trigraph conversion, escaped newline splicing, and processing of most directives. The preprocessor still recognizes and removes comments, so that 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.

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

Accept $ in 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++.
When preprocessing, do not shorten system header paths with canonicalization.
Set the maximum depth of the nested #include. The default is 200.
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.
Track locations of tokens across macro expansions. This allows the compiler to emit diagnostic 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 the memory consumption if necessary. Value 0 of level de-activates this option. Value 1 tracks tokens 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 tokens 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.

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.
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.
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".
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.
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 are listed and not the files that were used to create it, because those files are not consulted when a precompiled header is used.
This option allows use of a precompiled header together with -E. It inserts a special "#pragma", "#pragma GCC pch_preprocess "filename"" in the output to mark the place where the precompiled header was found, and its filename. When -fpreprocessed is in use, GCC recognizes this "#pragma" and loads the PCH.

This option is off by default, because the resulting preprocessed output is only really suitable as input to GCC. It is switched on by -save-temps.

You should not write this "#pragma" in your own code, but it is safe to edit the filename if the PCH file is available in a different location. The filename may be absolute or it may be relative to GCC's current directory.

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.
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.
Cancel an assertion with the predicate predicate and answer answer.
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 #.

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.

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.
Try to imitate the behavior of pre-standard C preprocessors, as opposed to ISO C preprocessors. See the GNU CPP manual for details.

Note that GCC does not otherwise attempt to emulate a pre-standard C compiler, and these options are only supported with the -E switch, or when invoking CPP explicitly.

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.

Enable special code to work around file systems which only permit very short file names, such as MS-DOS.
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.
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.

Like -dM except that it outputs both the #define directives and the result of preprocessing. Both kinds of output go to the standard output file.
Like -dD, but emit only the macro names, not their expansions.
Output #include directives in addition to the result of preprocessing.
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.
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.

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

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

You can pass options to the assembler.

Pass option as an option to the assembler. If option contains commas, it is split into multiple options at the commas.
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.

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.

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
If any of these options is used, then the linker is not run, and object file names should not be used as arguments.
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.

Use the bfd linker instead of the default linker.
Use the gold linker instead of the default linker.
Use the LLVM lld linker instead of the default linker.
Use the Modern Linker (mold) instead of the default linker.
Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.)

The -l option is passed directly to the linker by GCC. Refer to your linker documentation for exact details. The general description below applies to the GNU linker.

The linker searches a standard list of directories for the library. The directories searched include several standard system directories plus any that you specify with -L.

Static libraries are archives of object files, and have file names like liblibrary.a. Some targets also support shared libraries, which typically have names like liblibrary.so. If both static and shared libraries are found, the linker gives preference to linking with the shared library unless the -static option is used.

It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in z, those functions may not be loaded.

You need this special case of the -l option in order to link an Objective-C or Objective-C++ program.
Do not use the standard system startup files when linking. The standard system libraries are used normally, unless -nostdlib, -nolibc, or -nodefaultlibs is used.
Do not use the standard system libraries when linking. Only the libraries you specify are passed to the linker, and options specifying linkage of the system libraries, such as -static-libgcc or -shared-libgcc, are ignored. The standard startup files are used normally, unless -nostartfiles is used.

The compiler may generate calls to "memcmp", "memset", "memcpy" and "memmove". These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified.

Do not use the C library or system libraries tightly coupled with it when linking. Still link with the startup files, libgcc or toolchain provided language support libraries such as libgnat, libgfortran or libstdc++ unless options preventing their inclusion are used as well. This typically removes -lc from the link command line, as well as system libraries that normally go with it and become meaningless when absence of a C library is assumed, for example -lpthread or -lm in some configurations. This is intended for bare-board targets when there is indeed no C library available.
Do not use the standard system startup files or libraries when linking. No startup files and only the libraries you specify are passed to the linker, and options specifying linkage of the system libraries, such as -static-libgcc or -shared-libgcc, are ignored.

The compiler may generate calls to "memcmp", "memset", "memcpy" and "memmove". These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified.

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

Do not implicitly link with standard C++ libraries.
-e 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.
Produce a dynamically linked position independent executable on targets that support it. For predictable results, you must also specify the same set of options used for compilation (-fpie, -fPIE, or model suboptions) when you specify this linker option.
Don't produce a dynamically linked position independent executable.
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.
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.
Produce a relocatable object as output. This is also known as partial linking.
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.
Remove all symbol table and relocation information from the executable.
On systems that support dynamic linking, this overrides -pie and prevents linking with the shared libraries. On other systems, this option has no effect.
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]
On systems that provide libgcc as a shared library, these options force the use of either the shared or static version, respectively. If no shared version of libgcc was built when the compiler was configured, these options have no effect.

There are several situations in which an application should use the shared libgcc instead of the static version. The most common of these is when the application wishes to throw and catch exceptions across different shared libraries. In that case, each of the libraries as well as the application itself should use the shared libgcc.

Therefore, the G++ driver automatically adds -shared-libgcc whenever you build a shared library or a main executable, because C++ programs typically use exceptions, so this is the right thing to do.

If, instead, you use the GCC driver to create shared libraries, you may find that they are not always linked with the shared libgcc. If GCC finds, at its configuration time, that you have a non-GNU linker or a GNU linker that does not support option --eh-frame-hdr, it links the shared version of libgcc into shared libraries by default. Otherwise, it takes advantage of the linker and optimizes away the linking with the shared version of libgcc, linking with the static version of libgcc by default. This allows exceptions to propagate through such shared libraries, without incurring relocation costs at library load time.

However, if a library or main executable is supposed to throw or catch exceptions, you must link it using the G++ driver, or using the option -shared-libgcc, such that it is linked with the shared libgcc.

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.
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.
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.
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.
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.
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.
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.
Pass option as an option to the linker. You can use this to supply system-specific linker options that GCC does not recognize.

If you want to pass an option that takes a separate argument, you must use -Xlinker twice, once for the option and once for the argument. For example, to pass -assert definitions, you must write -Xlinker -assert -Xlinker definitions. It does not work to write -Xlinker "-assert definitions", because this passes the entire string as a single argument, which is not what the linker expects.

When using the GNU linker, it is usually more convenient to pass arguments to linker options using the option=value syntax than as separate arguments. For example, you can specify -Xlinker -Map=output.map rather than -Xlinker -Map -Xlinker output.map. Other linkers may not support this syntax for command-line options.

Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas. You can use this syntax to pass an argument to the option. For example, -Wl,-Map,output.map passes -Map output.map to the linker. When using the GNU linker, you can also get the same effect with -Wl,-Map=output.map.
Pretend the symbol symbol is undefined, to force linking of library modules to define it. You can use -u multiple times with different symbols to force loading of additional library modules.
-z is passed directly on to the linker along with the keyword keyword. See the section in the documentation of your linker for permitted values and their meanings.

These options specify directories to search for header files, for libraries and for parts of the compiler:

Add the directory dir to the list of directories to be searched for header files during preprocessing. If dir begins with = or $SYSROOT, then the = or $SYSROOT is replaced by the sysroot prefix; see --sysroot and -isysroot.

Directories specified with -iquote apply only to the quote form of the directive, "#include "file"". Directories specified with -I, -isystem, or -idirafter apply to lookup for both the "#include "file"" and "#include <file>" directives.

You can specify any number or combination of these options on the command line to search for header files in several directories. The lookup order is as follows:

1.
For the quote form of the include directive, the directory of the current file is searched first.
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. However, you should not use this option to add directories that contain vendor-supplied system header files; use -isystem for that.

The -isystem and -idirafter options also mark the directory as a system directory, so that it gets the same special treatment that is applied to the standard system directories.

If a standard system include directory, or a directory specified with -isystem, is also specified with -I, the -I option is ignored. The directory is still searched but as a system directory at its normal position in the system include chain. This is to ensure that GCC's procedure to fix buggy system headers and the ordering for the "#include_next" directive are not inadvertently changed. If you really need to change the search order for system directories, use the -nostdinc and/or -isystem options.

Split the include path. This option has been deprecated. Please use -iquote instead for -I directories before the -I- and remove the -I- option.

Any directories specified with -I options before -I- are searched only for headers requested with "#include "file""; they are not searched for "#include <file>". If additional directories are specified with -I options after the -I-, those directories are searched for all #include directives.

In addition, -I- inhibits the use of the directory of the current file directory as the first search directory for "#include "file"". There is no way to override this effect of -I-.

Specify prefix as the prefix for subsequent -iwithprefix options. If the prefix represents a directory, you should include the final /.
Append dir to the prefix specified previously with -iprefix, and add the resulting directory to the include search path. -iwithprefixbefore puts it in the same place -I would; -iwithprefix puts it where -idirafter would.
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 information.
Use dir as a subdirectory of the directory containing target-specific C++ headers.
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.
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.)
Set the directory to search for plugins that are passed by -fplugin=name instead of -fplugin=path/name.so. This option is not meant to be used by the user, but only passed by the driver.
Add directory dir to the list of directories to be searched for -l.
This option specifies where to find the executables, libraries, include files, and data files of the compiler itself.

The compiler driver program runs one or more of the subprograms cpp, cc1, as and ld. It tries prefix as a prefix for each program it tries to run, both with and without machine/version/ for the corresponding target machine and compiler version.

For each subprogram to be run, the compiler driver first tries the -B prefix, if any. If that name is not found, or if -B is not specified, the driver tries two standard prefixes, /usr/lib/gcc/ and /usr/local/lib/gcc/. If neither of those results in a file name that is found, the unmodified program name is searched for using the directories specified in your PATH environment variable.

The compiler checks to see if the path provided by -B refers to a directory, and if necessary it adds a directory separator character at the end of the path.

-B prefixes that effectively specify directory names also apply to libraries in the linker, because the compiler translates these options into -L options for the linker. They also apply to include files in the preprocessor, because the compiler translates these options into -isystem options for the preprocessor. In this case, the compiler appends include to the prefix.

The runtime support file libgcc.a can also be searched for using the -B prefix, if needed. If it is not found there, the two standard prefixes above are tried, and that is all. The file is left out of the link if it is not found by those means.

Another way to specify a prefix much like the -B prefix is to use the environment variable GCC_EXEC_PREFIX.

As a special kludge, if the path provided by -B is [dir/]stageN/, where N is a number in the range 0 to 9, then it is replaced by [dir/]include. This is to help with boot-strapping the compiler.

Do not expand any symbolic links, resolve references to /../ or /./, or make the path absolute when generating a relative prefix.
Use dir as the logical root directory for headers and libraries. For example, if the compiler normally searches for headers in /usr/include and libraries in /usr/lib, it instead searches dir/usr/include and dir/usr/lib.

If you use both this option and the -isysroot option, then the --sysroot option applies to libraries, but the -isysroot option applies to header files.

The GNU linker (beginning with version 2.16) has the necessary support for this option. If your linker does not support this option, the header file aspect of --sysroot still works, but the library aspect does not.

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.

These machine-independent options control the interface conventions used in code generation.

Most of them have both positive and negative forms; the negative form of -ffoo is -fno-foo. In the table below, only one of the forms is listed---the one that is not the default. You can figure out the other form by either removing no- or adding it.

This option controls stack space reuse for user declared local/auto variables and compiler generated temporaries. reuse_level can be all, named_vars, or none. all enables stack reuse for all local variables and temporaries, named_vars enables the reuse only for user defined local variables with names, and none disables stack reuse completely. The default value is all. The option is needed when the program extends the lifetime of a scoped local variable or a compiler generated temporary beyond the end point defined by the language. When a lifetime of a variable ends, and if the variable lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped local variables whose live range does not overlap with it. Legacy code extending local lifetime is likely to break with the stack reuse optimization.

For example,

int *p;
{
  int local1;

  p = &local1;
  local1 = 10;
  ....
}
{
   int local2;
   local2 = 20;
   ...
}

if (*p == 10)  // out of scope use of local1
  {

  }

Another example:

struct A
{
    A(int k) : i(k), j(k) { }
    int i;
    int j;
};

A *ap;

void foo(const A& ar)
{
   ap = &ar;
}

void bar()
{
   foo(A(10)); // temp object's lifetime ends when foo returns

   {
     A a(20);
     ....
   }
   ap->i+= 10;  // ap references out of scope temp whose space
                // is reused with a. What is the value of ap->i?
}

The lifetime of a compiler generated temporary is well defined by the C++ standard. When a lifetime of a temporary ends, and if the temporary lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped local variables whose live range does not overlap with it. However some of the legacy code relies on the behavior of older compilers in which temporaries' stack space is not reused, the aggressive stack reuse can lead to runtime errors. This option is used to control the temporary stack reuse optimization.

This option generates traps for signed overflow on addition, subtraction, multiplication operations. The options -ftrapv and -fwrapv override each other, so using -ftrapv -fwrapv on the command-line results in -fwrapv being effective. Note that only active options override, so using -ftrapv -fwrapv -fno-wrapv on the command-line results in -ftrapv being effective.
This option instructs the compiler to assume that signed arithmetic overflow of addition, subtraction and multiplication wraps around using twos-complement representation. This flag enables some optimizations and disables others. The options -ftrapv and -fwrapv override each other, so using -ftrapv -fwrapv on the command-line results in -fwrapv being effective. Note that only active options override, so using -ftrapv -fwrapv -fno-wrapv on the command-line results in -ftrapv being effective.
This option 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.
This option implies -fno-wrapv -fno-wrapv-pointer and when negated implies -fwrapv -fwrapv-pointer.
Enable exception handling. Generates extra code needed to propagate exceptions. For some targets, this implies GCC generates frame unwind information for all functions, which can produce significant data size overhead, although it does not affect execution. If you do not specify this option, GCC enables it by default for languages like C++ that normally require exception handling, and disables it for languages like C that do not normally require it. However, you may need to enable this option when compiling C code that needs to interoperate properly with exception handlers written in C++. You may also wish to disable this option if you are compiling older C++ programs that don't use exception handling.
Generate code that allows trapping instructions to throw exceptions. Note that this requires platform-specific runtime support that does not exist everywhere. Moreover, it only allows trapping instructions to throw exceptions, i.e. memory references or floating-point instructions. It does not allow exceptions to be thrown from arbitrary signal handlers such as "SIGALRM". This enables -fexceptions.
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.
Similar to -fexceptions, except that it just generates any needed static data, but does not affect the generated code in any other way. You normally do not need to enable this option; instead, a language processor that needs this handling enables it on your behalf.
Generate unwind table in DWARF format, if supported by target machine. The table is exact at each instruction boundary, so it can be used for stack unwinding from asynchronous events (such as debugger or garbage collector).
On systems with recent GNU assembler and C library, the C++ compiler uses the "STB_GNU_UNIQUE" binding to make sure that definitions of template static data members and static local variables in inline functions are unique even in the presence of "RTLD_LOCAL"; this is necessary to avoid problems with a library used by two different "RTLD_LOCAL" plugins depending on a definition in one of them and therefore disagreeing with the other one about the binding of the symbol. But this causes "dlclose" to be ignored for affected DSOs; if your program relies on reinitialization of a DSO via "dlclose" and "dlopen", you can use -fno-gnu-unique.
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.

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.

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.

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. This option has no effect for an enumeration type with a fixed underlying type.

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.

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.

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.

Ignore the "#ident" 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.
Put extra commentary information in the generated assembly code to make it more readable. This option is generally only of use to those who actually need to read the generated assembly code (perhaps while debugging the compiler itself).

-fno-verbose-asm, the default, causes the extra information to be omitted and is useful when comparing two assembler files.

The added comments include:

  • information on the compiler version and command-line options,
  • the source code lines associated with the assembly instructions, in the form FILENAME:LINENUMBER:CONTENT OF LINE,
  • hints on which high-level expressions correspond to the various assembly instruction operands.

For example, given this C source file:

int test (int n)
{
  int i;
  int total = 0;

  for (i = 0; i < n; i++)
    total += i * i;

  return total;
}

compiling to (x86_64) assembly via -S and emitting the result direct to stdout via -o -

gcc -S test.c -fverbose-asm -Os -o -

gives output similar to this:

        .file   "test.c"
# GNU C11 (GCC) version 7.0.0 20160809 (experimental) (x86_64-pc-linux-gnu)
  [...snip...]
# options passed:
  [...snip...]

        .text
        .globl  test
        .type   test, @function
test:
.LFB0:
        .cfi_startproc
# test.c:4:   int total = 0;
        xorl    %eax, %eax      # <retval>
# test.c:6:   for (i = 0; i < n; i++)
        xorl    %edx, %edx      # i
.L2:
# test.c:6:   for (i = 0; i < n; i++)
        cmpl    %edi, %edx      # n, i
        jge     .L5     #,
# test.c:7:     total += i * i;
        movl    %edx, %ecx      # i, tmp92
        imull   %edx, %ecx      # i, tmp92
# test.c:6:   for (i = 0; i < n; i++)
        incl    %edx    # i
# test.c:7:     total += i * i;
        addl    %ecx, %eax      # tmp92, <retval>
        jmp     .L2     #
.L5:
# test.c:10: }
        ret
        .cfi_endproc
.LFE0:
        .size   test, .-test
        .ident  "GCC: (GNU) 7.0.0 20160809 (experimental)"
        .section        .note.GNU-stack,"",@progbits

The comments are intended for humans rather than machines and hence the precise format of the comments is subject to change.

This switch causes the command line used to invoke the compiler to be recorded into the object file that is being created. This switch is only implemented on some targets and the exact format of the recording is target and binary file format dependent, but it usually takes the form of a section containing ASCII text. This switch is related to the -fverbose-asm switch, but that switch only records information in the assembler output file as comments, so it never reaches the object file. See also -grecord-gcc-switches for another way of storing compiler options into the object file.
Generate position-independent code (PIC) suitable for use in a shared library, if 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). 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.

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.

These options are similar to -fpic and -fPIC, but the generated position-independent code can be only linked into executables. Usually these options are used to compile code that will be linked using the -pie GCC option.

-fpie and -fPIE both define the macros "__pie__" and "__PIE__". The macros have the value 1 for -fpie and 2 for -fPIE.

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.

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.
Do not use bit tests for switch statements even where it would be more efficient than other code generation strategies.
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.

Treat the register named reg as an allocable register that is clobbered by function calls. It may be allocated for temporaries or variables that do not live across a call. Functions compiled this way do not save and restore the register reg.

It is an error to use this flag with the frame pointer or stack pointer. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results.

This flag does not have a negative form, because it specifies a three-way choice.

Treat the register named reg as an allocable register saved by functions. It may be allocated even for temporaries or variables that live across a call. Functions compiled this way save and restore the register reg if they use it.

It is an error to use this flag with the frame pointer or stack pointer. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results.

A different sort of disaster results from the use of this flag for a register in which function values may be returned.

This flag does not have a negative form, because it specifies a three-way choice.

Without a value specified, pack all structure members together without holes. When a value is specified (which must be a small power of two), pack structure members according to this value, representing the maximum alignment (that is, objects with default alignment requirements larger than this are output potentially unaligned at the next fitting location.

Warning: the -fpack-struct switch causes GCC to generate code that is not binary compatible with code generated without that switch. Additionally, it makes the code suboptimal. Use it to conform to a non-default application binary interface.

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.

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.

For targets that normally need trampolines for nested functions, always generate them instead of using descriptors. Otherwise, for targets that do not need them, like for example HP-PA or IA-64, do nothing.

A trampoline is a small piece of code that is created at run time on the stack when the address of a nested function is taken, and is used to call the nested function indirectly. Therefore, it requires the stack to be made executable in order for the program to work properly.

-fno-trampolines is enabled by default on a language by language basis to let the compiler avoid generating them, if it computes that this is safe, and replace them with descriptors. Descriptors are made up of data only, but the generated code must be prepared to deal with them. As of this writing, -fno-trampolines is enabled by default only for Ada.

Moreover, code compiled with -ftrampolines and code compiled with -fno-trampolines are not binary compatible if nested functions are present. This option must therefore be used on a program-wide basis and be manipulated with extreme care.

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.

By default, trampolines are generated on stack. However, certain platforms (such as the Apple M1) do not permit an executable stack. Compiling with -ftrampoline-impl=heap generate calls to "__gcc_nested_func_ptr_created" and "__gcc_nested_func_ptr_deleted" in order to allocate and deallocate trampoline space on the executable heap. These functions are implemented in libgcc, and will only be provided on specific targets: x86_64 Darwin, x86_64 and aarch64 Linux. PLEASE NOTE: Heap trampolines are not guaranteed to be correctly deallocated if you "setjmp", instantiate nested functions, and then "longjmp" back to a state prior to having allocated those nested functions.
Set the default ELF image symbol visibility to the specified option---all symbols are marked with this unless overridden within the code. Using this feature can very substantially improve linking and load times of shared object libraries, produce more optimized code, provide near-perfect API export and prevent symbol clashes. It is strongly recommended that you use this in any shared objects you distribute.

Despite the nomenclature, default always means public; i.e., available to be linked against from outside the shared object. protected and internal are pretty useless in real-world usage so the only other commonly used option is hidden. The default if -fvisibility isn't specified is default, i.e., make every symbol public.

A good explanation of the benefits offered by ensuring ELF symbols have the correct visibility is given by "How To Write Shared Libraries" by Ulrich Drepper