Using The GNU Compiler Collection: Richard M. Stallman and The GCC Developer Community
Using The GNU Compiler Collection: Richard M. Stallman and The GCC Developer Community
(GCC)
Short Contents
1 Programming Languages Supported by GCC . . . . . . . . . . . . . . . 1
2 Language Standards Supported by GCC . . . . . . . . . . . . . . . . . . . 3
3 GCC Command Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4 C Implementation-Defined Behavior . . . . . . . . . . . . . . . . . . . . . 559
5 C++ Implementation-Defined Behavior . . . . . . . . . . . . . . . . . . 569
6 Extensions to the C Language Family . . . . . . . . . . . . . . . . . . . 571
7 Extensions to the C++ Language . . . . . . . . . . . . . . . . . . . . . 1003
8 GNU Objective-C Features . . . . . . . . . . . . . . . . . . . . . . . . . . . 1017
9 Binary Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1033
10 gcov—a Test Coverage Program . . . . . . . . . . . . . . . . . . . . . . . 1037
11 gcov-tool—an Offline Gcda Profile Processing Tool . . . . . . 1057
12 gcov-dump—an Offline Gcda and Gcno Profile Dump Tool . 1061
13 lto-dump—Tool for dumping LTO object files. . . . . . . . . . . . 1063
14 Known Causes of Trouble with GCC . . . . . . . . . . . . . . . . . . . 1065
15 Reporting Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1081
16 How To Get Help with GCC . . . . . . . . . . . . . . . . . . . . . . . . . . 1083
17 Contributing to GCC Development . . . . . . . . . . . . . . . . . . . . 1085
Funding Free Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1087
The GNU Project and GNU/Linux . . . . . . . . . . . . . . . . . . . . . . . . 1089
GNU General Public License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1091
GNU Free Documentation License . . . . . . . . . . . . . . . . . . . . . . . . . 1103
Contributors to GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1111
A Indices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1129
iii
Table of Contents
2.1 C Language
The original ANSI C standard (X3.159-1989) was ratified in 1989 and published in 1990.
This standard was ratified as an ISO standard (ISO/IEC 9899:1990) later in 1990. There
were no technical differences between these publications, although the sections of the ANSI
standard were renumbered and became clauses in the ISO standard. The ANSI standard,
but not the ISO standard, also came with a Rationale document. This standard, in both its
forms, is commonly known as C89, or occasionally as C90, from the dates of ratification. To
select this standard in GCC, use one of the options -ansi, -std=c90 or -std=iso9899:1990;
to obtain all the diagnostics required by the standard, you should also specify -pedantic
(or -pedantic-errors if you want them to be errors rather than warnings). See Section 3.4
[Options Controlling C Dialect], page 43.
Errors in the 1990 ISO C standard were corrected in two Technical Corrigenda published
in 1994 and 1996. GCC does not support the uncorrected version.
An amendment to the 1990 standard was published in 1995. This amendment added
digraphs and __STDC_VERSION__ to the language, but otherwise concerned the library. This
amendment is commonly known as AMD1; the amended standard is sometimes known as
C94 or C95. To select this standard in GCC, use the option -std=iso9899:199409 (with,
as for other standard versions, -pedantic to receive all required diagnostics).
A new edition of the ISO C standard was published in 1999 as ISO/IEC 9899:1999, and
is commonly known as C99. (While in development, drafts of this standard version were
referred to as C9X.) GCC has substantially complete support for this standard version; see
https://gcc.gnu.org/c99status.html for details. To select this standard, use -std=c99
or -std=iso9899:1999.
Errors in the 1999 ISO C standard were corrected in three Technical Corrigenda published
in 2001, 2004 and 2007. GCC does not support the uncorrected version.
A fourth version of the C standard, known as C11, was published in 2011 as ISO/IEC
9899:2011. (While in development, drafts of this standard version were referred to as
C1X.) GCC has substantially complete support for this standard, enabled with -std=c11 or
-std=iso9899:2011. A version with corrections integrated was prepared in 2017 and pub-
lished in 2018 as ISO/IEC 9899:2018; it is known as C17 and is supported with -std=c17 or
-std=iso9899:2017; the corrections are also applied with -std=c11, and the only difference
between the options is the value of __STDC_VERSION__.
A further version of the C standard, known as C23, is under development and expected to
be published in 2024 as ISO/IEC 9899:2024. (While in development, drafts of this standard
version were referred to as C2X.) Experimental and incomplete support for this is enabled
with -std=c23 or -std=iso9899:2024.
By default, GCC provides some extensions to the C language that, on rare occasions con-
flict with the C standard. See Chapter 6 [Extensions to the C Language Family], page 571.
4 Using the GNU Compiler Collection (GCC)
Some features that are part of the C99 standard are accepted as extensions in C90 mode,
and some features that are part of the C11 standard are accepted as extensions in C90
and C99 modes. Use of the -std options listed above disables these extensions where they
conflict with the C standard version selected. You may also select an extended version of
the C language explicitly with -std=gnu90 (for C90 with GNU extensions), -std=gnu99
(for C99 with GNU extensions) or -std=gnu11 (for C11 with GNU extensions).
The default, if no C language dialect options are given, is -std=gnu17.
The ISO C standard defines (in clause 4) two classes of conforming implementation. A
conforming hosted implementation supports the whole standard including all the library
facilities; a conforming freestanding implementation is only required to provide certain
library facilities: those in <float.h>, <limits.h>, <stdarg.h>, and <stddef.h>; since
AMD1, also those in <iso646.h>; since C99, also those in <stdbool.h> and <stdint.h>;
and since C11, also those in <stdalign.h> and <stdnoreturn.h>. In addition, complex
types, added in C99, are not required for freestanding implementations.
The standard also defines two environments for programs, a freestanding environment,
required of all implementations and which may not have library facilities beyond those
required of freestanding implementations, where the handling of program startup and ter-
mination are implementation-defined; and a hosted environment, which is not required,
in which all the library facilities are provided and startup is through a function int main
(void) or int main (int, char *[]). An OS kernel is an example of a program running
in a freestanding environment; a program using the facilities of an operating system is an
example of a program running in a hosted environment.
GCC aims towards being usable as a conforming freestanding implementation, or as the
compiler for a conforming hosted implementation. By default, it acts as the compiler for a
hosted implementation, defining __STDC_HOSTED__ as 1 and presuming that when the names
of ISO C functions are used, they have the semantics defined in the standard. To make it act
as a conforming freestanding implementation for a freestanding environment, use the option
-ffreestanding; it then defines __STDC_HOSTED__ to 0 and does not make assumptions
about the meanings of function names from the standard library, with exceptions noted
below. To build an OS kernel, you may well still need to make your own arrangements for
linking and startup. See Section 3.4 [Options Controlling C Dialect], page 43.
GCC does not provide the library facilities required only of hosted implementations, nor
yet all the facilities required by C99 of freestanding implementations on all platforms. To
use the facilities of a hosted environment, you need to find them elsewhere (for example, in
the GNU C library). See Section 14.5 [Standard Libraries], page 1070.
Most of the compiler support routines used by GCC are present in libgcc, but there are
a few exceptions. GCC requires the freestanding environment provide memcpy, memmove,
memset and memcmp. Contrary to the standards covering memcpy GCC expects the case
of an exact overlap of source and destination to work and not invoke undefined behavior.
Finally, if __builtin_trap is used, and the target does not implement the trap pattern,
then GCC emits a call to abort.
For references to Technical Corrigenda, Rationale documents and information concerning
the history of C that is available online, see https://gcc.gnu.org/readings.html
Chapter 2: Language Standards Supported by GCC 5
2.4 Go Language
As of the GCC 4.7.1 release, GCC supports the Go 1 language standard, described at
https://go.dev/doc/go1.
2.5 D language
GCC supports the D 2.0 programming language. The D language itself is currently de-
fined by its reference implementation and supporting language specification, described at
https://dlang.org/spec/spec.html.
Chapter 2: Language Standards Supported by GCC 7
Overall Options
See Section 3.2 [Options Controlling the Kind of Output], page 32.
-c -S -E -o file
-dumpbase dumpbase -dumpbase-ext auxdropsuf
-dumpdir dumppfx -x language
-v -### --help[=class[,...]] --target-help --version
-pass-exit-codes -pipe -specs=file -wrapper
@file -ffile-prefix-map=old=new -fcanon-prefix-map
-fplugin=file -fplugin-arg-name=arg
-fdump-ada-spec[-slim] -fada-spec-parent=unit -fdump-go-spec=file
C Language Options
See Section 3.4 [Options Controlling C Dialect], page 43.
-ansi -std=standard -aux-info filename
-fno-asm
-fno-builtin -fno-builtin-function -fcond-mismatch
-ffreestanding -fgimple -fgnu-tm -fgnu89-inline -fhosted
-flax-vector-conversions -fms-extensions
-foffload=arg -foffload-options=arg
-fopenacc -fopenacc-dim=geom
-fopenmp -fopenmp-simd -fopenmp-target-simd-clone[=device-type]
-fpermitted-flt-eval-methods=standard
-fplan9-extensions -fsigned-bitfields -funsigned-bitfields
-fsigned-char -funsigned-char -fstrict-flex-arrays[=n]
-fsso-struct=endianness
C++ Language Options
See Section 3.5 [Options Controlling C++ Dialect], page 52.
-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
Chapter 3: GCC Command Options 11
-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
-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]
Warning Options
See Section 3.8 [Options to Request or Suppress Warnings], page 93.
-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
Chapter 3: GCC Command Options 13
-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
-femit-struct-debug-baseonly -femit-struct-debug-reduced
-femit-struct-debug-detailed[=spec-list]
-fno-eliminate-unused-debug-symbols -femit-class-debug-always
-fno-merge-debug-strings -fno-dwarf2-cfi-asm
-fvar-tracking -fvar-tracking-assignments
Optimization Options
See Section 3.11 [Options that Control Optimization], page 181.
-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
Chapter 3: GCC Command Options 17
-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]
Preprocessor Options
See Section 3.13 [Options Controlling the Preprocessor], page 278.
-Aquestion=answer
-A-question[=answer]
-C -CC -Dmacro[=defn]
-dD -dI -dM -dN -dU
-fdebug-cpp -fdirectives-only -fdollars-in-identifiers
-fexec-charset=charset -fextended-identifiers
-finput-charset=charset -flarge-source-files
-fmacro-prefix-map=old=new -fmax-include-depth=depth
-fno-canonical-system-headers -fpch-deps -fpch-preprocess
-fpreprocessed -ftabstop=width -ftrack-macro-expansion
-fwide-exec-charset=charset -fworking-directory
-H -imacros file -include file
-M -MD -MF -MG -MM -MMD -MP -MQ -MT -Mno-modules
-no-integrated-cpp -P -pthread -remap
-traditional -traditional-cpp -trigraphs
-Umacro -undef
-Wp,option -Xpreprocessor option
Assembler Options
See Section 3.14 [Passing Options to the Assembler], page 286.
-Wa,option -Xassembler option
Linker Options
See Section 3.15 [Options for Linking], page 286.
object-file-name -fuse-ld=linker -llibrary
-nostartfiles -nodefaultlibs -nolibc -nostdlib -nostdlib++
-e entry --entry=entry
-pie -pthread -r -rdynamic
-s -static -static-pie -static-libgcc -static-libstdc++
-static-libasan -static-libtsan -static-liblsan -static-libubsan
-shared -shared-libgcc -symbolic
-T script -Wl,option -Xlinker option
-u symbol -z keyword
Directory Options
See Section 3.16 [Options for Directory Search], page 292.
Chapter 3: GCC Command Options 19
Developer Options
See Section 3.18 [GCC Developer Options], page 305.
-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
20 Using the GNU Compiler Collection (GCC)
-fira-verbose=n
-flto-report -flto-report-wpa -fmem-report-wpa
-fmem-report -fpre-ipa-mem-report -fpost-ipa-mem-report
-fopt-info -fopt-info-options[=file]
-fmultiflags -fprofile-report
-frandom-seed=string -fsched-verbose=n
-fsel-sched-verbose -fsel-sched-dump-cfg -fsel-sched-pipelining-verbose
-fstats -fstack-usage -ftime-report -ftime-report-details
-fvar-tracking-assignments-toggle -gtoggle
-print-file-name=library -print-libgcc-file-name
-print-multi-directory -print-multi-lib -print-multi-os-directory
-print-prog-name=program -print-search-dirs -Q
-print-sysroot -print-sysroot-headers-suffix
-save-temps -save-temps=cwd -save-temps=obj -time[=file]
Machine-Dependent Options
See Section 3.19 [Machine-Dependent Options], page 323.
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
Chapter 3: GCC Command Options 21
-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
Chapter 3: GCC Command Options 23
-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
26 Using the GNU Compiler Collection (GCC)
-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=
Chapter 3: GCC Command Options 27
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
28 Using the GNU Compiler Collection (GCC)
-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
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
Chapter 3: GCC Command Options 29
-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
30 Using the GNU Compiler Collection (GCC)
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
32 Using the GNU Compiler Collection (GCC)
-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.
-x none Turn off any specification of a language, so that subsequent files are handled
according to their file name suffixes (as they are if -x has not been used at all).
If you only want some of the stages of compilation, you can use -x (or filename suffixes)
to tell gcc where to start, and one of the options -c, -S, or -E to say where gcc is to stop.
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.
Chapter 3: GCC Command Options 35
-S Stop after the stage of compilation proper; do not assemble. The output is in
the form of an assembler code file for each non-assembler input file specified.
By default, the assembler file name for a source file is made by replacing the
suffix ‘.c’, ‘.i’, etc., with ‘.s’.
Input files that don’t require compilation are ignored.
-E Stop after the preprocessing stage; do not run the compiler proper. The output
is in the form of preprocessed source code, which is sent to the standard output.
Input files that don’t require preprocessing are ignored.
-o file Place the primary output in file file. This applies to whatever sort of output is
being produced, whether it be an executable file, an object file, an assembler
file or preprocessed C code.
If -o is not specified, the default is to put an executable file in a.out, the
object file for source.suffix in source.o, its assembler file in source.s, a
precompiled header file in source.suffix.gch, and all preprocessed C source
on standard output.
Though -o names only the primary output, it also affects the naming of aux-
iliary 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, other-
wise, 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.*.
36 Using the GNU Compiler Collection (GCC)
The location and the names of auxiliary and dump outputs can be adjusted
by the options -dumpbase, -dumpbase-ext, -dumpdir, -save-temps=cwd, and
-save-temps=obj.
-dumpbase dumpbase
This option sets the base name for auxiliary and dump output files. It does
not affect the name of the primary output file. Intermediate outputs, when
preserved, are not regarded as primary outputs, but as auxiliary outputs:
gcc -save-temps -S foo.c
saves the (no longer) temporary preprocessed file in foo.i, and then compiles
to the (implied) output file foo.s, whereas:
gcc -save-temps -dumpbase save-foo -c foo.c
preprocesses to in save-foo.i, compiles to save-foo.s (now an intermediate,
thus auxiliary output), and then assembles to the (implied) output file foo.o.
Absent this option, dump and aux files take their names from the input file,
or from the (non-linker) output file, if one is explicitly specified: dump output
files (e.g. those requested by -fdump-* options) with the input name suffix,
and aux output files (those requested by other non-dump options, e.g. -save-
temps, -gsplit-dwarf, -fcallgraph-info) without it.
Similar suffix differentiation of dump and aux outputs can be attained for
explicitly-given -dumpbase basename.suf by also specifying -dumpbase-ext
.suf.
If dumpbase is explicitly specified with any directory component, any dumppfx
specification (e.g. -dumpdir or -save-temps=*) is ignored, and instead of ap-
pending 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 aux-
iliary 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 base-
name in the naming of auxiliary and dump outputs during compilation, com-
puting 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.
Chapter 3: GCC Command Options 37
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 recompi-
lation during linking will use dir/foobar. as the prefix for dumps and auxiliary
files.
-dumpbase-ext auxdropsuf
When forming the name of an auxiliary (but not a dump) output file, drop trail-
ing 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 pre-
fix, creating auxiliary outputs named main-foo.* and main-bar.* and dump
outputs named main-foo.c.* and main-bar.c.*.
-dumpdir dumppfx
When forming the name of an auxiliary or dump output file, use dumppfx as a
prefix:
gcc -dumpdir pfx- -c foo.c ...
creates foo.o as the primary output, and auxiliary outputs named pfx-foo.*,
combining the given dumppfx with the default dumpbase derived from the
default primary output, derived in turn from the input name. Dump outputs
also take the input name suffix: pfx-foo.c.*.
If dumppfx is to be used as a directory name, it must end with a directory
separator:
gcc -dumpdir dir/ -c foo.c -o obj/bar.o ...
creates obj/bar.o as the primary output, and auxiliary outputs named
dir/bar.*, combining the given dumppfx with the default dumpbase derived
from the primary output name. Dump outputs also take the input name
suffix: dir/bar.c.*.
It defaults to the location of the output file, unless the output file is a special
file like /dev/null. Options -save-temps=cwd and -save-temps=obj override
this default, just like an explicit -dumpdir option. In case multiple such options
are given, the last one prevails:
gcc -dumpdir pfx- -c foo.c -save-temps=obj ...
38 Using the GNU Compiler Collection (GCC)
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 recompila-
tion, 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 re-
placing the compiler-added dash, if any, as a -dumpdir option to lto-wrapper;
being involved in linking, this program does not normally get any -dumpbase
and -dumpbase-ext, and it ignores them.
When running sub-compilers, lto-wrapper appends LTO stage names to the
received dumppfx, ensures it contains a directory component so that it overrides
any -dumpdir, and passes that as -dumpbase to sub-compilers.
-v Print (on standard error output) the commands executed to run the stages of
compilation. Also print the version number of the compiler driver program and
of the preprocessor and the compiler proper.
-### Like -v except the commands are not executed and arguments are quoted unless
they contain only alphanumeric characters or ./-_. This is useful for shell
scripts to capture the driver-generated command lines.
--help Print (on the standard output) a description of the command-line options un-
derstood by gcc. If the -v option is also specified then --help is also passed on
to the various processes invoked by gcc, so that they can display the command-
line options they accept. If the -Wextra option has also been specified (prior
to the --help option), then command-line options that have no documentation
associated with them are also displayed.
--target-help
Print (on the standard output) a description of target-specific command-line
options for each tool. For some targets extra target-specific information may
also be printed.
--help={class|[^]qualifier}[,...]
Print (on the standard output) a description of the command-line options un-
derstood by the compiler that fit into all specified classes and qualifiers. These
are the supported classes:
‘optimizers’
Display all of the optimization options supported by the compiler.
‘warnings’
Display all of the options controlling warning messages produced
by the compiler.
‘target’ Display target-specific options. Unlike the --target-help option
however, target-specific options of the linker and assembler are not
displayed. This is because those tools do not currently support the
extended --help= syntax.
‘params’ Display the values recognized by the --param option.
40 Using the GNU Compiler Collection (GCC)
language Display the options supported for language, where language is the
name of one of the languages supported in this version of GCC. If
an option is supported by all languages, one needs to select ‘common’
class.
‘common’ Display the options that are common to all languages.
These are the supported qualifiers:
‘undocumented’
Display only those options that are undocumented.
‘joined’ Display options taking an argument that appears after an equal sign
in the same continuous piece of text, such as: ‘--help=target’.
‘separate’
Display options taking an argument that appears as a separate word
following the original option, such as: ‘-o output-file’.
Thus for example to display all the undocumented target-specific switches sup-
ported 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
Chapter 3: GCC Command Options 41
Alternatively you can discover which binary optimizations are enabled by -O3
by using:
gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts
gcc -c -Q -O2 --help=optimizers > /tmp/O2-opts
diff /tmp/O2-opts /tmp/O3-opts | grep enabled
--version
Display the version number and copyrights of the invoked GCC.
-pass-exit-codes
Normally the gcc program exits with the code of 1 if any phase of the compiler
returns a non-success return code. If you specify -pass-exit-codes, the gcc
program instead returns with the numerically highest error produced by any
phase returning an error indication. The C, C++, and Fortran front ends return
4 if an internal compiler error is encountered.
-pipe Use pipes rather than temporary files for communication between the various
stages of compilation. This fails to work on some systems where the assembler
is unable to read from a pipe; but the GNU assembler has no trouble.
-specs=file
Process file after the compiler reads in the standard specs file, in order to
override the defaults which the gcc driver program uses when determining what
switches to pass to cc1, cc1plus, as, ld, etc. More than one -specs=file can
be specified on the command line, and they are processed in order, from left to
right. See Section 3.20 [Spec Files], page 539, for information about the format
of the file.
-wrapper Invoke all subcommands under a wrapper program. The name of the wrapper
program and its parameters are passed as a comma separated list.
gcc -c t.c -wrapper gdb,--args
This invokes all subprograms of gcc under ‘gdb --args’, thus the invocation of
cc1 is ‘gdb --args cc1 ...’.
-ffile-prefix-map=old=new
When compiling files residing in directory old, record any references to them in
the result of the compilation as if the files resided in directory new instead. Spec-
ifying this option is equivalent to specifying all the individual -f*-prefix-map
options. This can be used to make reproducible builds that are location inde-
pendent. 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.
-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.
42 Using the GNU Compiler Collection (GCC)
-fplugin=name.so
Load the plugin code in file name.so, assumed to be a shared object to be
dlopen’d by the compiler. The base name of the shared object file is used
to identify the plugin for the purposes of argument parsing (See -fplugin-
arg-name-key=value below). Each plugin should define the callback functions
specified in the Plugins API.
-fplugin-arg-name-key=value
Define an argument called key with a value of value for the plugin called name.
-fdump-ada-spec[-slim]
For C and C++ source and include files, generate corresponding Ada specs. See
Section “Generating Ada Bindings for C and C++ headers” in GNAT User’s
Guide, which provides detailed documentation on this feature.
-fada-spec-parent=unit
In conjunction with -fdump-ada-spec[-slim] above, generate Ada specs as
child units of parent unit.
-fdump-go-spec=file
For input files in any language, generate corresponding Go declarations in file.
This generates Go const, type, var, and func declarations which may be
a useful way to start writing a Go interface to code written in some other
language.
@file Read command-line options from file. The options read are inserted in place
of the original @file option. If file does not exist, or cannot be read, then the
option will be treated literally, and not removed.
Options in file are separated by whitespace. A whitespace character may be
included in an option by surrounding the entire option in either single or double
quotes. Any character (including a backslash) may be included by prefixing the
character to be included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
for languages related to C. See Section 3.5 [Options Controlling C++ Dialect], page 52, for
explanations of options that are meaningful only for C++ programs.
‘gnu90’
‘gnu89’ GNU dialect of ISO C90 (including some C99 features).
‘gnu99’
‘gnu9x’ GNU dialect of ISO C99. The name ‘gnu9x’ is deprecated.
‘gnu11’
‘gnu1x’ GNU dialect of ISO C11. The name ‘gnu1x’ is deprecated.
‘gnu17’
‘gnu18’ GNU dialect of ISO C17. This is the default for C code.
‘gnu23’
‘gnu2x’ 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.
‘c++98’
‘c++03’ The 1998 ISO C++ standard plus the 2003 technical corrigendum
and some additional defect reports. Same as -ansi for C++ code.
‘gnu++98’
‘gnu++03’ GNU dialect of -std=c++98.
‘c++11’
‘c++0x’ The 2011 ISO C++ standard plus amendments. The name ‘c++0x’
is deprecated.
‘gnu++11’
‘gnu++0x’ GNU dialect of -std=c++11. The name ‘gnu++0x’ is deprecated.
‘c++14’
‘c++1y’ The 2014 ISO C++ standard plus amendments. The name ‘c++1y’
is deprecated.
‘gnu++14’
‘gnu++1y’ GNU dialect of -std=c++14. The name ‘gnu++1y’ is deprecated.
‘c++17’
‘c++1z’ The 2017 ISO C++ standard plus amendments. The name ‘c++1z’
is deprecated.
‘gnu++17’
‘gnu++1z’ GNU dialect of -std=c++17. This is the default for C++ code. The
name ‘gnu++1z’ is deprecated.
‘c++20’
‘c++2a’ The 2020 ISO C++ standard plus amendments. Support is experi-
mental, and could change in incompatible ways in future releases.
The name ‘c++2a’ is deprecated.
‘gnu++20’
‘gnu++2a’ GNU dialect of -std=c++20. Support is experimental, and could
change in incompatible ways in future releases. The name ‘gnu++2a’
is deprecated.
46 Using the GNU Compiler Collection (GCC)
‘c++2b’
‘c++23’ The next revision of the ISO C++ standard, planned for 2023. Sup-
port is highly experimental, and will almost certainly change in
incompatible ways in future releases.
‘gnu++2b’
‘gnu++23’ GNU dialect of -std=c++2b. Support is highly experimental, and
will almost certainly change in incompatible ways in future releases.
‘c++2c’
‘c++26’ The next revision of the ISO C++ standard, planned for 2026. Sup-
port is highly experimental, and will almost certainly change in
incompatible ways in future releases.
‘gnu++2c’
‘gnu++26’ GNU dialect of -std=c++2c. Support is highly experimental, and
will almost certainly change in incompatible ways in future releases.
-aux-info filename
Output to the given filename prototyped declarations for all functions declared
and/or defined in a translation unit, including those in header files. This option
is silently ignored in any language other than C.
Besides declarations, the file indicates, in comments, the origin of each declara-
tion (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 decla-
rations is also provided, inside comments, after the declaration.
-fno-asm Do not recognize asm, inline or typeof as a keyword, so that code can use
these words as identifiers. You can use the keywords __asm__, __inline__ and
__typeof__ instead. In C, -ansi implies -fno-asm.
In C++, inline is a standard keyword and is not affected by this switch. You
may want to use the -fno-gnu-keywords flag instead, which disables typeof
but not asm and inline. In C99 mode (-std=c99 or -std=gnu99), this switch
only affects the asm and typeof keywords, since inline is a standard keyword
in ISO C99. In C23 mode (-std=c23 or -std=gnu23), this switch only affects
the asm keyword, since typeof is a standard keyword in ISO C23.
-fno-builtin
-fno-builtin-function
Don’t recognize built-in functions that do not begin with ‘__builtin_’ as prefix.
See Section 6.61 [Other built-in functions provided by GCC], page 787, for
details of the functions affected, including those which are not built-in functions
when -ansi or -std options for strict ISO C conformance are used because they
do not have an ISO standard meaning.
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.
Chapter 3: GCC Command Options 47
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))
-fcond-mismatch
Allow conditional expressions with mismatched types in the second and third
arguments. The value of such an expression is void. This option is not supported
for C++.
-ffreestanding
Assert that compilation targets a freestanding environment. This implies -fno-
builtin. A freestanding environment is one in which the standard library may
not exist, and program startup may not necessarily be at main. The most
obvious example is an OS kernel. This is equivalent to -fno-hosted.
See Chapter 2 [Language Standards Supported by GCC], page 3, for details of
freestanding and hosted environments.
-fgimple
Enable parsing of function definitions marked with __GIMPLE. This is an ex-
perimental feature that allows unit testing of GIMPLE passes.
-fgnu-tm When the option -fgnu-tm is specified, the compiler generates code for the
Linux variant of Intel’s current Transactional Memory ABI specification doc-
ument (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, See Section
“The GNU Transactional Memory Library” in GNU Transactional Memory
Library.
Note that the transactional memory feature is not supported with non-call
exceptions (-fnon-call-exceptions).
-fgnu89-inline
The option -fgnu89-inline tells GCC to use the traditional GNU semantics
for inline functions when in C99 mode. See Section 6.45 [An Inline Func-
48 Using the GNU Compiler Collection (GCC)
tion is As Fast As a Macro], page 706. Using this option is roughly equivalent
to adding the gnu_inline function attribute to all inline functions (see Sec-
tion 6.33 [Function Attributes], page 599).
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. See
Section “Common Predefined Macros” in The C Preprocessor.
-fhosted
Assert that compilation targets a hosted environment. This implies -fbuiltin.
A hosted environment is one in which the entire standard library is available,
and in which main has a return type of int. Examples are nearly everything
except a kernel. This is equivalent to -fno-freestanding.
-flax-vector-conversions
Allow implicit conversions between vectors with differing numbers of elements
and/or incompatible element types. This option should not be used for new
code.
-fms-extensions
Accept some non-standard constructs used in Microsoft header files.
In C++ code, this allows member names in structures to be similar to previous
types declarations.
typedef int UOW;
struct ABC {
UOW UOW;
};
Some cases of unnamed fields in structures and unions are only accepted
with this option. See Section 6.65 [Unnamed struct/union fields within
structs/unions], page 999, for details.
Note that this option is off for all targets except for x86 targets using ms-abi.
-foffload=disable
-foffload=default
-foffload=target-list
Specify for which OpenMP and OpenACC offload targets code should be gen-
erated. The default behavior, equivalent to -foffload=default, is to generate
code for all supported offload targets. The -foffload=disable form generates
code only for the host fallback, while -foffload=target-list generates code
only for the specified comma-separated list of offload targets.
Offload targets are specified in GCC’s internal target-triplet format. You can
run the compiler with -v to show the list of configured offload targets under
OFFLOAD_TARGET_NAMES.
-foffload-options=options
-foffload-options=target-triplet-list=options
With -foffload-options=options, GCC passes the specified options to the
compilers for all enabled offloading targets. You can specify options that apply
Chapter 3: GCC Command Options 49
-fopenacc
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.
-fopenacc-dim=geom
Specify default compute dimensions for parallel offload regions that do not
explicitly specify. The geom value is a triple of ’:’-separated sizes, in order
’gang’, ’worker’ and, ’vector’. A size can be omitted, to use a target-specific
default value.
-fopenmp Enable handling of OpenMP directives ‘#pragma omp’, ‘[[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.
-fopenmp-simd
Enable handling of OpenMP’s simd, declare simd, declare reduction,
assume, ordered, scan and loop directive, and of combined or composite direc-
tives 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.
-fopenmp-target-simd-clone
-fopenmp-target-simd-clone=device-type
In addition to generating SIMD clones for functions marked with the declare
simd directive, GCC also generates clones for functions marked with the
OpenMP declare target directive that are suitable for vectorization when
this option is in effect. The device-type may be one of none, host, nohost,
and any, which correspond to keywords for the device_type clause of
the declare target directive; clones are generated for the intersection
50 Using the GNU Compiler Collection (GCC)
-fsigned-bitfields
-funsigned-bitfields
-fno-signed-bitfields
-fno-unsigned-bitfields
These options control whether a bit-field is signed or unsigned, when the dec-
laration 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.
-fsigned-char
Let the type char be signed, like signed char.
Note that this is equivalent to -fno-unsigned-char, which is the negative form
of -funsigned-char. Likewise, the option -fno-signed-char is equivalent to
-funsigned-char.
-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.
-fstrict-flex-arrays (C and C++ only)
-fstrict-flex-arrays=level (C and C++ only)
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 mem-
bers.
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 at-
tribute (see Section 6.34 [Variable Attributes], page 669).
You can control this behavior for a specific trailing array field of a structure
by using the variable attribute strict_flex_array attribute (see Section 6.34
[Variable Attributes], page 669).
The -fstrict_flex_arrays option interacts with the -Wstrict-flex-arrays
option. See Section 3.8 [Warning Options], page 93, for more information.
52 Using the GNU Compiler Collection (GCC)
-fsso-struct=endianness
Set the default scalar storage order of structures and unions to the specified en-
dianness. The accepted values are ‘big-endian’, ‘little-endian’ and ‘native’
for the native endianness of the target (the default). This option is not sup-
ported 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.
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... ex-
pressions 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 regres-
sion.
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.
-fabi-compat-version=n
On targets that support strong aliases, G++ works around mangling changes by
creating an alias with the correct mangled name when defining a symbol with
an incorrect mangled name. This switch specifies which ABI version to use for
the alias.
With -fabi-version=0 (the default), this defaults to 13 (GCC 8.2 compatibil-
ity). If another ABI version is explicitly selected, this defaults to 0. For com-
patibility 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 compati-
bility aliases. If this option is provided along with -Wabi (without the version),
the version from this option is used for the warning.
-fno-access-control
Turn off all access checking. This switch is mainly useful for working around
bugs in the access control code.
-faligned-new
Enable support for C++17 new of types that require more alignment than
void* ::operator new(std::size_t) provides. A numeric argument such as
-faligned-new=32 can be used to specify how much alignment (in bytes) is
54 Using the GNU Compiler Collection (GCC)
provided by that function, but few users will need to override the default of
alignof(std::max_align_t).
This flag is enabled by default for -std=c++17.
-fchar8_t
-fno-char8_t
Enable support for char8_t as adopted for C++20. This includes the addition
of a new char8_t fundamental type, changes to the types of UTF-8 string and
character literals, new signatures for user-defined literals, associated standard
library updates, and new __cpp_char8_t and __cpp_lib_char8_t feature test
macros.
This option enables functions to be overloaded for ordinary and UTF-8 strings:
int f(const char *); // #1
int f(const char8_t *); // #2
int v1 = f("text"); // Calls #1
int v2 = f(u8"text"); // Calls #2
The change to the types of UTF-8 string and character literals introduces in-
compatibilities 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 spec-
ified.
const char *cp = u8"xx";// error: invalid conversion from
// `const char8_t*' to `const char*'
int f(const char*);
auto v = f(u8"xx"); // error: invalid conversion from
// `const char8_t*' to `const char*'
std::string s{u8"xx"}; // error: no matching function for call to
// `std::basic_string<char>::basic_string()'
using namespace std::literals;
s = u8"xx"s; // error: conversion from
// `basic_string<char8_t>' to non-scalar
// type `basic_string<char>' requested
-fcheck-new
Check that the pointer returned by operator new is non-null before attempting
to modify the storage allocated. This check is normally unnecessary because
the C++ standard specifies that operator new only returns 0 if it is declared
throw(), in which case the compiler always checks the return value even without
this option. In all other cases, when operator new has a non-empty exception
specification, memory exhaustion is signalled by throwing std::bad_alloc.
See also ‘new (nothrow)’.
Chapter 3: GCC Command Options 55
-fconcepts
-fconcepts-ts
Enable support for the C++ Concepts feature for constraining template ar-
guments. 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.
-fconstexpr-depth=n
Set the maximum nested evaluation depth for C++11 constexpr functions to
n. A limit is needed to detect endless recursion during constant expression
evaluation. The minimum specified by the standard is 512.
-fconstexpr-cache-depth=n
Set the maximum level of nested evaluation depth for C++11 constexpr func-
tions that will be cached to n. This is a heuristic that trades off compilation
speed (when the cache avoids repeated calculations) against memory consump-
tion (when the cache grows very large from highly recursive evaluations). The
default is 8. Very few users are likely to want to adjust it, but if your code does
heavy constexpr calculations you might want to experiment to find which value
works best for you.
-fconstexpr-fp-except
Annex F of the C standard specifies that IEC559 floating point exceptions
encountered at compile time should not stop compilation. C++ compilers have
historically not followed this guidance, instead treating floating point division
by zero as non-constant even though it has a well defined value. This flag tells
the compiler to give Annex F priority over other rules saying that a particular
operation is undefined.
constexpr float inf = 1./0.; // OK with -fconstexpr-fp-except
-fconstexpr-loop-limit=n
Set the maximum number of iterations for a loop in C++14 constexpr functions
to n. A limit is needed to detect infinite loops during constant expression
evaluation. The default is 262144 (1<<18).
-fconstexpr-ops-limit=n
Set the maximum number of operations during a single constexpr evaluation.
Even when number of iterations of a single loop is limited with the above limit,
if there are several nested loops and each of them has many iterations but
still smaller than the above limit, or if in a body of some loop or even outside
of a loop too many expressions need to be evaluated, the resulting constexpr
evaluation might take too long. The default is 33554432 (1<<25).
-fcontracts
Enable experimental support for the C++ Contracts feature, as briefly added to
and then removed from the C++20 working paper (N4820). The implementation
56 Using the GNU Compiler Collection (GCC)
also includes proposed enhancements from papers P1290, P1332, and P1429.
This functionality is intended mostly for those interested in experimentation
towards refining the feature to get it into shape for a future C++ standard.
On violation of a checked contract, the violation handler is called. Users can
replace the violation handler by defining
void
handle_contract_violation (const std::experimental::contract_violation&);
There are different sets of additional flags that can be used together to specify
which contracts will be checked and how, for N4820 contracts, P1332 contracts,
or P1429 contracts; these sets cannot be used together.
-fcontract-mode=[on|off]
Control whether any contracts have any semantics at all. Defaults
to on.
-fcontract-assumption-mode=[on|off]
[N4820] Control whether contracts with level ‘axiom’ should have
the assume semantic. Defaults to on.
-fcontract-build-level=[off|default|audit]
[N4820] Specify which level of contracts to generate checks for. De-
faults to ‘default’.
-fcontract-continuation-mode=[on|off]
[N4820] Control whether to allow the program to continue executing
after a contract violation. That is, do checked contracts have the
‘maybe’ semantic described below rather than the ‘never’ semantic.
Defaults to off.
-fcontract-role=<name>:<default>,<audit>,<axiom>
[P1332] Specify the concrete semantics for each contract level of a
particular contract role.
-fcontract-semantic=[default|audit|axiom]:<semantic>
[P1429] Specify the concrete semantic for a particular contract level.
-fcontract-strict-declarations=[on|off]
Control whether to reject adding contracts to a function after its
first declaration. Defaults to off.
The possible concrete semantics 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.
Chapter 3: GCC Command Options 57
-fcoroutines
Enable support for the C++ coroutines extension (experimental).
-fdiagnostics-all-candidates
Permit the C++ front end to note all candidates during overload resolution
failure, including when a deleted function is selected.
-fno-elide-constructors
The C++ standard allows an implementation to omit creating a temporary that
is only used to initialize another object of the same type. Specifying this option
disables that optimization, and forces G++ to call the copy constructor in all
cases. This option also causes G++ to call trivial member functions which
otherwise would be expanded inline.
In C++17, the compiler is required to omit these temporaries, but this option
still affects trivial member functions.
-fno-enforce-eh-specs
Don’t generate code to check for violation of exception specifications at run
time. This option violates the C++ standard, but may be useful for reducing
code size in production builds, much like defining NDEBUG. This does not give
user code permission to throw exceptions in violation of the exception specifi-
cations; the compiler still optimizes based on the specifications, so throwing an
unexpected exception results in undefined behavior at run time.
-fextern-tls-init
-fno-extern-tls-init
The C++11 and OpenMP standards allow thread_local and threadprivate
variables to have dynamic (runtime) initialization. To support this, any use of
such a variable goes through a wrapper function that performs any necessary
initialization. When the use and definition of the variable are in the same
translation unit, this overhead can be optimized away, but when the use is in a
different translation unit there is significant overhead even if the variable doesn’t
actually need dynamic initialization. If the programmer can be sure that no
use of the variable in a non-defining TU needs to trigger dynamic initialization
(either because the variable is statically initialized, or a use of the variable in
the defining TU will be executed before any uses in another TU), they can avoid
this overhead with the -fno-extern-tls-init option.
On targets that support symbol aliases, the default is -fextern-tls-init. On
targets that do not support symbol aliases, the default is -fno-extern-tls-
init.
-ffold-simple-inlines
-fno-fold-simple-inlines
Permit the C++ frontend to fold calls to std::move, std::forward,
std::addressof and std::as_const. In contrast to inlining, this means no
debug information will be generated for such calls. Since these functions are
rarely interesting to debug, this flag is enabled by default unless -fno-inline
is active.
58 Using the GNU Compiler Collection (GCC)
-fno-gnu-keywords
Do not recognize typeof as a keyword, so that code can use this word as an
identifier. You can use the keyword __typeof__ instead. This option is implied
by the strict ISO C++ dialects: -ansi, -std=c++98, -std=c++11, etc.
-fno-immediate-escalation
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; }
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.
-fimplicit-constexpr
Make inline functions implicitly constexpr, if they satisfy the requirements for a
constexpr function. This option can be used in C++14 mode or later. This can
result in initialization changing from dynamic to static and other optimizations.
-fno-implicit-templates
Never emit code for non-inline templates that are instantiated implicitly (i.e.
by use); only emit code for explicit instantiations. If you use this option, you
must take care to structure your code to include all the necessary explicit in-
stantiations to avoid getting undefined symbols at link time. See Section 7.5
[Template Instantiation], page 1006, for more information.
-fno-implicit-inline-templates
Don’t emit code for implicit instantiations of inline templates, either. The
default is to handle inlines differently so that compiles with and without opti-
mization need the same set of explicit instantiations.
-fno-implement-inlines
To save space, do not emit out-of-line copies of inline functions controlled by
#pragma implementation. This causes linker errors if these functions are not
inlined everywhere they are called.
Chapter 3: GCC Command Options 59
-fmodules-ts
-fno-modules-ts
Enable support for C++20 modules (see Section 3.23 [C++ Modules], page 553).
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.
-fmodule-header
-fmodule-header=user
-fmodule-header=system
Compile a header file to create an importable header unit.
-fmodule-implicit-inline
Member functions defined in their class definitions are not implicitly inline for
modular code. This is different to traditional C++ behavior, for good reasons.
However, it may result in a difficulty during code porting. This option makes
such function definitions implicitly inline. It does however generate an ABI
incompatibility, so you must use it everywhere or nowhere. (Such definitions
outside of a named module remain implicitly inline, regardless.)
-fno-module-lazy
Disable lazy module importing and module mapper creation.
-fmodule-mapper=[hostname]:port[?ident]
-fmodule-mapper=|program[?ident] args...
-fmodule-mapper==socket[?ident]
-fmodule-mapper=<>[inout][?ident]
-fmodule-mapper=<in>out[?ident]
-fmodule-mapper=file[?ident]
An oracle to query for module name to filename mappings. If unspecified the
CXX_MODULE_MAPPER environment variable is used, and if that is unset, an in-
process default is provided.
-fmodule-only
Only emit the Compiled Module Interface, inhibiting any object file.
-fms-extensions
Disable Wpedantic warnings about constructs used in MFC, such as implicit
int and getting a pointer to member function via non-standard syntax.
-fnew-inheriting-ctors
Enable the P0136 adjustment to the semantics of C++11 constructor inheri-
tance. 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.
-fnew-ttp-matching
Enable the P0522 resolution to Core issue 150, template template parameters
and default arguments: this allows a template with default template arguments
as an argument for a template template parameter with fewer template param-
eters. This flag is enabled by default for -std=c++17.
60 Using the GNU Compiler Collection (GCC)
-fno-nonansi-builtins
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.
-fnothrow-opt
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 excep-
tion specification. If the function has local variables of types with non-trivial
destructors, the exception specification actually makes the function smaller be-
cause 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 spec-
ification results in a call to terminate rather than unexpected.
-fno-operator-names
Do not treat the operator name keywords and, bitand, bitor, compl, not, or
and xor as synonyms as keywords.
-fno-optional-diags
Disable diagnostics that the standard says a compiler does not need to issue.
Currently, the only such diagnostic issued by G++ is the one for a name having
multiple meanings within a class.
-fno-pretty-templates
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.
-fno-rtti
Disable generation of information about every class with virtual functions
for use by the C++ run-time type identification features (dynamic_cast and
typeid). If you don’t use those parts of the language, you can save some space
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.
-fsized-deallocation
Enable the built-in global declarations
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;
Chapter 3: GCC Command Options 61
-fstrict-enums
Allow the compiler to optimize using the assumption that a value of enumerated
type can only be one of the values of the enumeration (as defined in the C++
standard; basically, a value that can be represented in the minimum number
of bits needed to represent all the enumerators). This assumption may not be
valid if the program uses a cast to convert an arbitrary integer value to the
enumerated type. This option has no effect for an enumeration type with a
fixed underlying type.
-fstrong-eval-order
Evaluate member access, array subscripting, and shift expressions in left-to-
right order, and evaluate assignment in right-to-left order, as adopted for C++17.
Enabled by default with -std=c++17. -fstrong-eval-order=some enables just
the ordering of member access and shift expressions, and is the default without
-std=c++17.
-ftemplate-backtrace-limit=n
Set the maximum number of template instantiation notes for a single warning
or error to n. The default value is 10.
-ftemplate-depth=n
Set the maximum instantiation depth for template classes to n. A limit on
the template instantiation depth is needed to detect endless recursions during
template class instantiation. ANSI/ISO C++ conforming programs must not
rely on a maximum depth greater than 17 (changed to 1024 in C++11). The
default value is 900, as the compiler can run out of stack space before hitting
1024 in some situations.
-fno-threadsafe-statics
Do not emit the extra code to use the routines specified in the C++ ABI for
thread-safe initialization of local statics. You can use this option to reduce code
size slightly in code that doesn’t need to be thread-safe.
-fuse-cxa-atexit
Register destructors for objects with static storage duration with the __cxa_
atexit function rather than the atexit function. This option is required for
fully standards-compliant handling of static destructors, but only works if your
C library supports __cxa_atexit.
-fno-use-cxa-get-exception-ptr
Don’t use the __cxa_get_exception_ptr runtime routine. This causes
std::uncaught_exception to be incorrect, but is necessary if the runtime
routine is not available.
62 Using the GNU Compiler Collection (GCC)
-fvisibility-inlines-hidden
This switch declares that the user does not attempt to compare pointers to
inline functions or methods where the addresses of the two functions are taken
in different shared objects.
The effect 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 link-
age might otherwise cross a shared library boundary. See Section 7.5 [Template
Instantiation], page 1006.
-fvisibility-ms-compat
This flag attempts to use visibility settings to make GCC’s C++ linkage model
compatible with that of Microsoft Visual Studio.
The flag makes these changes to GCC’s linkage model:
1. It sets the default visibility to hidden, like -fvisibility=hidden.
2. Types, but not their members, are not hidden by default.
3. The One Definition Rule is relaxed for types without explicit visibility
specifications that are defined in more than one shared object: those dec-
larations are permitted if they are permitted when this option is not used.
In new code it is better to use -fvisibility=hidden and export those classes
that are intended to be externally visible. Unfortunately it is possible for code
to rely, perhaps accidentally, on the Visual Studio behavior.
Among the consequences of these changes are that static data members of
the same type with the same name but defined in different shared objects are
different, so changing one does not change the other; and that pointers to
function members defined in different shared objects may not compare equal.
When this flag is given, it is a violation of the ODR to define types with the
same name differently.
-fno-weak
Do not use weak symbol support, even if it is provided by the linker. By
default, G++ uses weak symbols if they are available. This option exists only
for testing, and should not be used by end-users; it results in inferior code and
has no benefits. This option may be removed in a future release of G++.
Chapter 3: GCC Command Options 63
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 (see
Section 7.7 [C++ Attributes], page 1009).
This warning is enabled by -Wall.
-Wdelete-non-virtual-dtor (C++ and Objective-C++ only)
Warn when delete is used to destroy an instance of a class that has virtual
functions and non-virtual destructor. It is unsafe to delete an instance of a
derived class through a pointer to a base class if the base class does not have a
virtual destructor. This warning is enabled by -Wall.
-Wdeprecated-copy (C++ and Objective-C++ only)
Warn that the implicit declaration of a copy constructor or copy assignment
operator is deprecated if the class has a user-provided copy constructor or copy
assignment operator, in C++11 and up. This warning is enabled by -Wextra.
With -Wdeprecated-copy-dtor, also deprecate if the class has a user-provided
destructor.
-Wno-deprecated-enum-enum-conversion (C++ and Objective-C++ only)
Disable the warning about the case when the usual arithmetic conversions are
applied on operands where one is of enumeration type and the other is of a
different enumeration type. This conversion was deprecated in C++20. For
example:
enum E1 { e };
enum E2 { f };
int k = f - e;
66 Using the GNU Compiler Collection (GCC)
least one set of function arguments in at least one instantiation such that an
invocation of the function or constructor could be an evaluated subexpression
of a core constant expression. C++23 removed this restriction, so it’s possible
to have a function or a function template marked constexpr for which no
invocation satisfies the requirements of a core constant expression.
This warning is enabled as a pedantic warning by default in C++20 and earlier.
In C++23, -Winvalid-constexpr can be turned on, in which case it will be an
ordinary warning. For example:
void f (int& i);
constexpr void
g (int& i)
{
// Warns by default in C++20, in C++23 only with -Winvalid-constexpr.
f(i);
}
-Winvalid-imported-macros
Verify all imported macro definitions are valid at the end of compilation. This
is not enabled by default, as it requires additional processing to determine. It
may be useful when preparing sets of header-units to ensure consistent macros.
-Wno-literal-suffix (C++ and Objective-C++ only)
Do not warn when a string or character literal is followed by a ud-suffix which
does not begin with an underscore. As a conforming extension, GCC treats
such suffixes as separate preprocessing tokens in order to maintain backwards
compatibility with code that uses formatting macros from <inttypes.h>. For
example:
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>
int main() {
int64_t i64 = 123;
printf("My int64: %" PRId64"\n", i64);
}
In this case, PRId64 is treated as a separate preprocessing token.
This option also controls warnings when a user-defined literal operator is de-
clared with a literal suffix identifier that doesn’t begin with an underscore.
Literal suffix identifiers that don’t begin with an underscore are reserved for
future standardization.
These warnings are enabled by default.
-Wno-narrowing (C++ and Objective-C++ only)
For C++11 and later standards, narrowing conversions are diagnosed by default,
as required by the standard. A narrowing conversion from a constant produces
an error, and a narrowing conversion from a non-constant produces a warning,
but -Wno-narrowing suppresses the diagnostic. Note that this does not affect
the meaning of well-formed code; narrowing conversions are still considered
ill-formed in SFINAE contexts.
With -Wnarrowing in C++98, warn when a narrowing conversion prohibited by
C++11 occurs within ‘{ }’, e.g.
68 Using the GNU Compiler Collection (GCC)
struct A {
int i;
int j;
A(): j (0), i (1) { }
};
The compiler rearranges the member initializers for i and j to match the dec-
laration order of the members, emitting a warning to that effect. This warning
is enabled by -Wall.
-Wno-pessimizing-move (C++ and Objective-C++ only)
This warning warns when a call to std::move prevents copy elision. A typical
scenario when copy elision can occur is when returning in a function with a class
return type, when the expression being returned is the name of a non-volatile
automatic object, and is not a function parameter, and has the same type as
the function return type.
struct T {
...
};
T fn()
{
T t;
...
return std::move (t);
}
But in this example, the std::move call prevents copy elision.
This warning is enabled by -Wall.
-Wno-redundant-move (C++ and Objective-C++ only)
This warning warns about redundant calls to std::move; that is, when a move
operation would have been performed even without the std::move call. This
happens because the compiler is forced to treat the object as if it were an rvalue
in certain situations such as returning a local variable, where copy elision isn’t
applicable. Consider:
struct T {
...
};
T fn(T t)
{
...
return std::move (t);
}
Here, the std::move call is redundant. Because G++ implements Core Issue
1579, another example is:
struct T { // convertible to U
...
};
struct U {
...
};
U fn()
{
T t;
...
70 Using the GNU Compiler Collection (GCC)
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.
-Wno-pmf-conversions (C++ and Objective-C++ only)
Disable the diagnostic for converting a bound pointer to member function to a
plain pointer.
-Wsign-promo (C++ and Objective-C++ only)
Warn when overload resolution chooses a promotion from unsigned or enumer-
ated 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.
-Wtemplates (C++ and Objective-C++ only)
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.
-Wmismatched-new-delete (C++ and Objective-C++ only)
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 mis-
matched 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
Chapter 3: GCC Command Options 73
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
-Wno-virtual-move-assign
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.
-Wnamespaces
Warn when a namespace definition is opened. Some coding rules disallow
namespaces, and this may be used to enforce that rule. The warning is in-
active 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.
-Wno-template-id-cdtor (C++ and Objective-C++ only)
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.
-Wno-terminate (C++ and Objective-C++ only)
Disable the warning about a throw-expression that will immediately result in a
call to terminate.
-Wno-vexing-parse (C++ and Objective-C++ only)
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.
-Wno-class-conversion (C++ and Objective-C++ only)
Do not warn when a conversion function converts an object to the same type,
to a base class of that type, or to void; such a conversion function will never be
called.
Chapter 3: GCC Command Options 75
-Wplacement-new=2
At this level, in addition to diagnosing all the same constructs as
at level 1, a diagnostic is also issued for placement new expressions
that construct an object in the last member of 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.
76 Using the GNU Compiler Collection (GCC)
struct B : A { };
struct C : B, A { };
-Wno-inherited-variadic-ctor
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.
-Wno-invalid-offsetof (C++ and Objective-C++ only)
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.
-Wsized-deallocation (C++ and Objective-C++ only)
Warn about a definition of an unsized deallocation function
void operator delete (void *) noexcept;
Chapter 3: GCC Command Options 77
-fconstant-string-class=class-name
Use class-name as the name of the class to instantiate for each literal string
specified with the syntax @"...". The default class name is NXConstantString
if the GNU runtime is being used, and NSConstantString if the NeXT runtime
is being used (see below). 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.
-fgnu-runtime
Generate object code compatible with the standard GNU Objective-C runtime.
This is the default for most types of systems.
-fnext-runtime
Generate output compatible with the NeXT runtime. This is the default for
NeXT-based systems, including Darwin / macOS. The macro __NEXT_RUNTIME_
_ is predefined if (and only if) this option is used.
-fno-nil-receivers
Assume that all Objective-C message dispatches ([receiver message:arg]) in
this translation unit ensure that the receiver is not nil. This allows for more
efficient entry points in the runtime to be used. This option is only available in
conjunction with the NeXT runtime and ABI version 0 or 1.
-fobjc-abi-version=n
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.
-fobjc-call-cxx-cdtors
For each Objective-C class, check if any of its instance variables is a C++ ob-
ject 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.
Chapter 3: GCC Command Options 79
As of this writing, only the NeXT runtime on Mac OS X 10.4 and later has sup-
port for invoking the - (id) .cxx_construct and - (void) .cxx_destruct
methods.
-fobjc-direct-dispatch
Allow fast jumps to the message dispatcher. On Darwin this is accomplished
via the comm page.
-fobjc-exceptions
Enable syntactic support for structured exception handling in Objective-C, sim-
ilar to what is offered by C++. This option is required to use the Objective-C
keywords @try, @throw, @catch, @finally and @synchronized. This option is
available with both the GNU runtime and the NeXT runtime (but not available
in conjunction with the NeXT runtime on Mac OS X 10.2 and earlier).
-fobjc-gc
Enable garbage collection (GC) in Objective-C and Objective-C++ programs.
This option is only available with the NeXT runtime; the GNU runtime has a
different garbage collection implementation that does not require special com-
piler flags.
-fobjc-nilcheck
For the NeXT runtime with version 2 of the ABI, check for a nil receiver in
method invocations before doing the actual method call. This is the default and
can be disabled using -fno-objc-nilcheck. Class methods and super calls are
never checked for nil in this way no matter what this flag is set to. Currently
this flag does nothing when the GNU runtime, or an older version of the NeXT
runtime ABI, is used.
-fobjc-std=objc1
Conform to the language syntax of Objective-C 1.0, the language recognized by
GCC 4.0. This only affects the Objective-C additions to the C/C++ language;
it does not affect conformance to C/C++ standards, which is controlled by
the separate C/C++ dialect option flags. When this option is used with the
Objective-C or Objective-C++ compiler, any Objective-C syntax that is not
recognized by GCC 4.0 is rejected. This is useful if you need to make sure that
your Objective-C code can be compiled with older versions of GCC.
-freplace-objc-classes
Emit a special marker instructing ld(1) not to statically link in the resulting
object file, and allow dyld(1) to load it in at run time instead. This is used
in conjunction with the Fix-and-Continue debugging mode, where the object
file in question may be recompiled and dynamically reloaded in the course of
program execution, without the need to restart the program itself. Currently,
Fix-and-Continue functionality is only available in conjunction with the NeXT
runtime on Mac OS X 10.3 and later.
-fzero-link
When compiling for the NeXT runtime, the compiler ordinarily replaces calls to
objc_getClass("...") (when the name of the class is known at compile time)
80 Using the GNU Compiler Collection (GCC)
with static class references that get initialized at load time, which improves run-
time performance. Specifying the -fzero-link flag suppresses this behavior
and causes calls to objc_getClass("...") to be retained. This is useful in
Zero-Link debugging mode, since it allows for individual class implementations
to be modified during program execution. The GNU runtime currently always
retains calls to objc_get_class("...") regardless of command-line options.
-fno-local-ivars
By default instance variables in Objective-C can be accessed as if they were local
variables from within the methods of the class they’re declared in. This can
lead to shadowing between instance variables and other variables declared either
locally inside a class method or globally with the same name. Specifying the
-fno-local-ivars flag disables this behavior thus avoiding variable shadowing
issues.
-fivar-visibility=[public|protected|private|package]
Set the default instance variable visibility to the specified option so that instance
variables declared outside the scope of any access modifier directives default to
the specified visibility.
-gen-decls
Dump interface declarations for all classes seen in the source file to a file named
sourcename.decl.
-Wassign-intercept (Objective-C and Objective-C++ only)
Warn whenever an Objective-C assignment is being intercepted by the garbage
collector.
-Wno-property-assign-default (Objective-C and Objective-C++ only)
Do not warn if a property for an Objective-C object has no assign semantics
specified.
-Wno-protocol (Objective-C and Objective-C++ only)
If a class is declared to implement a protocol, a warning is issued for every
method in the protocol that is not implemented by the class. The default
behavior is to issue a warning for every method not explicitly implemented in
the class, even if a method implementation is inherited from the superclass. If
you use the -Wno-protocol option, then methods inherited from the superclass
are considered to be implemented, and no warning is issued for them.
-Wobjc-root-class (Objective-C and Objective-C++ only)
Warn if a class interface lacks a superclass. Most classes will inherit from
NSObject (or Object) for example. When declaring classes intended to be
root classes, the warning can be suppressed by marking their interfaces with
__attribute__((objc_root_class)).
-Wselector (Objective-C and Objective-C++ only)
Warn if multiple methods of different types for the same selector are found
during compilation. The check is performed on the list of methods in the
final stage of compilation. Additionally, a check is performed for each selector
appearing in a @selector(...) expression, and a corresponding method for
Chapter 3: GCC Command Options 81
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.
-Wstrict-selector-match (Objective-C and Objective-C++ only)
Warn if multiple methods with differing argument and/or return types are found
for a given selector when attempting to send a message using this selector to
a receiver of type id or Class. When this flag is off (which is the default
behavior), the compiler omits such warnings if any differences found are confined
to types that share the same size and alignment.
-Wundeclared-selector (Objective-C and Objective-C++ only)
Warn if a @selector(...) expression referring to an undeclared selector is
found. A selector is considered undeclared if no method with that name has
been declared before the @selector(...) expression, either explicitly in an
@interface or @protocol declaration, or implicitly in an @implementation
section. This option always performs its checks as soon as a @selector(...)
expression is found, while -Wselector only performs its checks in the final stage
of compilation. This also enforces the coding style convention that methods and
selectors must be declared before being used.
-print-objc-runtime-info
Generate C header describing the largest structure that is passed by value, if
any.
-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.
-fdiagnostics-show-location=once
Only meaningful in line-wrapping mode. Instructs the diagnostic messages re-
porter 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 con-
tinuation lines. This is the default behavior.
-fdiagnostics-show-location=every-line
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.
-fdiagnostics-color[=WHEN]
-fno-diagnostics-color
Use color in diagnostics. WHEN is ‘never’, ‘always’, or ‘auto’. The default
depends on how the compiler has been configured, it can be any of the above
WHEN options or also ‘never’ if 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) sub-
strings. 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 col-
ors, 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
Chapter 3: GCC Command Options 83
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 indi-
vidual events and lines indicating interprocedural calls and returns.
range1= SGR substring for first additional range.
range2= SGR substring for second additional range.
locus= SGR substring for location information, ‘file:line’ or
‘file:line:column’ etc.
quote= SGR substring for information printed within quotes.
fnname= SGR substring for names of C++ functions.
targs= SGR substring for C++ function template parameter bindings.
fixit-insert=
SGR substring for fix-it hints suggesting text to be inserted or
replaced.
fixit-delete=
SGR substring for fix-it hints suggesting text to be deleted.
diff-filename=
SGR substring for filename headers within generated patches.
diff-hunk=
SGR substring for the starts of hunks within generated patches.
diff-delete=
SGR substring for deleted lines within generated patches.
diff-insert=
SGR substring for inserted lines within generated patches.
type-diff=
SGR substring for highlighting mismatching types within template
arguments in the C++ frontend.
-fdiagnostics-urls[=WHEN]
Use escape sequences to embed URLs in diagnostics. For example, when
-fdiagnostics-show-option emits text showing the command-line option
controlling a diagnostic, embed a URL for documentation of that option.
WHEN is ‘never’, ‘always’, or ‘auto’. ‘auto’ makes GCC use URL escape
sequences only when the standard error is a terminal, and when not executing
84 Using the GNU Compiler Collection (GCC)
-fno-diagnostics-show-option
By default, each diagnostic emitted includes text indicating the command-line
option that directly controls the diagnostic (if such an option is known to the
diagnostic machinery). Specifying the -fno-diagnostics-show-option flag
suppresses that behavior.
-fno-diagnostics-show-caret
By default, each diagnostic emitted includes the original source line and a caret
‘^’ indicating the column. This option suppresses this information. The source
line is truncated to n characters, if the -fmessage-length=n option is given.
When the output is done to the terminal, the width is limited to the width
given by the COLUMNS environment variable or, if not set, to the terminal width.
-fno-diagnostics-show-labels
By default, when printing source code (via -fdiagnostics-show-caret), di-
agnostics 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).
Chapter 3: GCC Command Options 85
-fno-diagnostics-show-cwe
Diagnostic messages can optionally have an associated CWE (https://cwe.
mitre.org/index.html) identifier. GCC itself only provides such metadata
for some of the -fanalyzer diagnostics. GCC plugins may also provide di-
agnostics with such metadata. By default, if this information is present, it
will be printed with the diagnostic. This option suppresses the printing of this
metadata.
-fno-diagnostics-show-rules
Diagnostic messages can optionally have rules associated with them, such as
from a coding standard, or a specification. GCC itself does not do this for
any of its diagnostics, but plugins may do so. By default, if this information
is present, it will be printed with the diagnostic. This option suppresses the
printing of this metadata.
-fno-diagnostics-show-line-numbers
By default, when printing source code (via -fdiagnostics-show-caret), a
left margin is printed, showing line numbers. This option suppresses this left
margin.
-fdiagnostics-minimum-margin-width=width
This option controls the minimum width of the left margin printed by
-fdiagnostics-show-line-numbers. It defaults to 6.
-fdiagnostics-parseable-fixits
Emit fix-it hints in a machine-parseable format, suitable for consumption by
IDEs. For each fix-it, a line will be printed after the relevant diagnostic, starting
with the string “fix-it:”. For example:
fix-it:"test.c":{45:3-45:21}:"gtk_widget_show_all"
The location is expressed as a half-open range, expressed as a count of bytes,
starting at byte 1 for the initial column. In the above example, bytes 3 through
20 of line 45 of “test.c” are to be replaced with the given string:
00000000011111111112222222222
12345678901234567890123456789
gtk_widget_showall (dlg);
^^^^^^^^^^^^^^^^^^
gtk_widget_show_all
The filename and replacement string escape backslash as “\\", tab as “\t”,
newline as “\n”, double quotes as “\"”, non-printable characters as octal (e.g.
vertical tab as “\013”).
An empty replacement string indicates that the given range is to be removed.
An empty range (e.g. “45:3-45:3”) indicates that the string is to be inserted at
the given position.
-fdiagnostics-generate-patch
Print fix-it hints to stderr in unified diff format, after any diagnostics are
printed. For example:
--- test.c
+++ test.c
@ -42,5 +42,5 @
86 Using the GNU Compiler Collection (GCC)
The diff may or may not be colorized, following the same rules as for diagnostics
(see -fdiagnostics-color).
-fdiagnostics-show-template-tree
In the C++ frontend, when printing diagnostics showing mismatching template
types, such as:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
the -fdiagnostics-show-template-tree flag enables printing a tree-like
structure showing the common and differing parts of the types, such as:
map<
[...],
vector<
[double != float]>>
The parts that differ are highlighted with color (“double” and “float” in this
case).
-fno-elide-type
By default when the C++ frontend prints diagnostics showing mismatching tem-
plate types, common parts of the types are printed as “[...]” to simplify the
error message. For example:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
Specifying the -fno-elide-type flag suppresses that behavior. This flag also
affects the output of the -fdiagnostics-show-template-tree flag.
-fdiagnostics-path-format=KIND
Specify how to print paths of control-flow events for diagnostics that have such
a path associated with them.
KIND is ‘none’, ‘separate-events’, or ‘inline-events’, the default.
‘none’ means to not print diagnostic paths.
‘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 p
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
Chapter 3: GCC Command Options 87
|
| 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);
88 Using the GNU Compiler Collection (GCC)
| | ^~~~~~~~~~~~~~~~~~~~
| | |
| | (7) calling 'free_boxed_int'
|
(etc)
-fdiagnostics-show-path-depths
This option provides additional information when printing control-flow paths
associated with a diagnostic.
If this is option is provided then the stack depth will be printed for each run
of events within -fdiagnostics-path-format=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 debug-
ging diagnostics that report interprocedural control flow.
-fno-show-column
Do not print column numbers in diagnostics. This may be necessary if diag-
nostics are being scanned by a program that does not understand the column
numbers, such as dejagnu.
-fdiagnostics-column-unit=UNIT
Select the units for the column number. This affects traditional diagnostics
(in the absence of -fno-show-column), as well as JSON format diagnostics if
requested.
The default UNIT, ‘display’, 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.
-fdiagnostics-column-origin=ORIGIN
Select the origin for column numbers, i.e. the column number assigned to the
first column. The default value of 1 corresponds to traditional GCC behavior
and to the GNU style guide. Some utilities may perform better with an origin
of 0; any non-negative value may be specified.
-fdiagnostics-escape-format=FORMAT
When GCC prints pertinent source lines for a diagnostic it normally attempts
to print the source bytes directly. However, some diagnostics relate to encoding
issues in the source file, such as malformed UTF-8, or issues with Unicode
normalization. These diagnostics are flagged so that GCC will escape bytes
that are not printable ASCII when printing their pertinent source lines.
This option controls how such bytes should be escaped.
The default FORMAT, ‘unicode’ displays Unicode characters that are not
printable ASCII in the form ‘<U+XXXX>’, and bytes that do not correspond
Chapter 3: GCC Command Options 89
-fdiagnostics-text-art-charset=CHARSET
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’.
-fdiagnostics-format=FORMAT
Select a different format for printing diagnostics. FORMAT is ‘text’,
‘sarif-stderr’, ‘sarif-file’, ‘json’, ‘json-stderr’, or ‘json-file’.
The default is ‘text’.
The ‘sarif-stderr’ and ‘sarif-file’ formats both emit diagnostics in SARIF
Version 2.1.0 format, either to stderr, or to a file named source.sarif, respec-
tively.
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;
90 Using the GNU Compiler Collection (GCC)
| ^
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-Wmislead
"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:
Chapter 3: GCC Command Options 91
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.
Chapter 3: GCC Command Options 93
The following language-independent options do not enable specific warnings but control
the kinds of diagnostics produced by GCC.
-fsyntax-only
Check the code for syntax errors, but don’t do anything beyond that.
-fmax-errors=n
Limits the maximum number of error messages to n, at which point GCC bails
out rather than attempting to continue processing the source code. If n is 0
(the default), there is no limit on the number of error messages produced. If
-Wfatal-errors is also specified, then -Wfatal-errors takes precedence over
this option.
-w Inhibit all warning messages.
-Werror Make all warnings into errors.
-Werror= 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.
-Wfatal-errors
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 Section 3.5 [C++ Dialect Options], page 52,
and Section 3.6 [Objective-C and Objective-C++ Dialect Options], page 77. Additional
warnings can be produced by enabling the static analyzer; See Section 3.9 [Static Analyzer
Options], page 157.
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 (see Section 6.64.12
[Diagnostic Pragmas], page 995) 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
Chapter 3: GCC Command Options 95
-Wpedantic
-pedantic
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 warn-
ings are also disabled in the expression that follows __extension__. However,
only system header files should use these escape routes; application programs
should avoid them. See Section 6.49 [Alternate Keywords], page 766.
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.)
-pedantic-errors
Give an error whenever the base standard (see -Wpedantic) requires a diagnos-
tic, 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 accord-
ing 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
96 Using the GNU Compiler Collection (GCC)
-fpermissive
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:
-Wno-format-extra-args
If -Wformat is specified, do not warn about excess arguments to a printf
or scanf format function. The C standard specifies that such arguments are
ignored.
Where the unused arguments lie between used arguments that are specified
with ‘$’ operand number specifications, normally warnings are still given, since
the implementation could not know what type to pass to va_arg to skip the
unused arguments. However, in the case of scanf formats, this option sup-
presses the warning if the unused arguments are all pointers, since the Single
Unix Specification says that such unused arguments are allowed.
-Wformat-overflow
-Wformat-overflow=level
Warn about calls to formatted input/output functions such as sprintf and
vsprintf that might overflow the destination buffer. When the exact number
of bytes written by a format directive cannot be determined at compile-time
it is estimated based on heuristics that depend on the level argument and
on optimization. While enabling optimization will in most cases improve the
accuracy of the warning, it may also result in false positives.
-Wformat-overflow
-Wformat-overflow=1
Level 1 of -Wformat-overflow enabled by -Wformat employs a
conservative approach that warns only about calls that most likely
overflow the buffer. At this level, numeric arguments to format di-
rectives 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 pre-
cision 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);
}
-Wformat-overflow=2
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
104 Using the GNU Compiler Collection (GCC)
-Wno-format-zero-length
If -Wformat is specified, do not warn about zero-length formats. The C standard
specifies that zero-length formats are allowed.
-Wformat-nonliteral
If -Wformat is specified, also warn if the format string is not a string literal and
so cannot be checked, unless the format function takes its format arguments as
a va_list.
-Wformat-security
If -Wformat is specified, also warn about uses of format functions that repre-
sent 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 cur-
rently a subset of what -Wformat-nonliteral warns about, but in future warn-
ings may be added to -Wformat-security that are not included in -Wformat-
nonliteral.)
-Wformat-signedness
If -Wformat is specified, also warn if the format string requires an unsigned
argument and the argument is signed and vice versa.
Chapter 3: GCC Command Options 105
-Wformat-truncation
-Wformat-truncation=level
Warn about calls to formatted input/output functions such as snprintf and
vsnprintf that might result in output truncation. When the exact number
of bytes written by a format directive cannot be determined at compile-time
it is estimated based on heuristics that depend on the level argument and
on optimization. While enabling optimization will in most cases improve the
accuracy of the warning, it may also result in false positives. Except as noted
otherwise, the option uses the same logic -Wformat-overflow.
-Wformat-truncation
-Wformat-truncation=1
Level 1 of -Wformat-truncation enabled by -Wformat employs
a conservative approach that warns only about calls to bounded
functions whose return value is unused and that will most likely
result in output truncation.
-Wformat-truncation=2
Level 2 warns also about calls to bounded functions whose return
value is used and that might result in truncation given an argument
of sufficient length or magnitude.
-Wformat-y2k
If -Wformat is specified, also warn about strftime formats that may yield only
a two-digit year.
-Wnonnull
Warn about passing a null pointer for arguments marked as requiring a non-null
value by the nonnull function attribute.
-Wnonnull is included in -Wall and -Wformat. It can be disabled with the
-Wno-nonnull option.
-Wnonnull-compare
Warn when comparing an argument marked with the nonnull function at-
tribute against null inside the function.
-Wnonnull-compare is included in -Wall. It can be disabled with the -Wno-
nonnull-compare option.
-Wnull-dereference
Warn if the compiler detects paths that trigger erroneous or undefined behavior
due to dereferencing a null pointer. This option is only active when -fdelete-
null-pointer-checks is active, which is enabled by optimizations in most
targets. The precision of the warnings depends on the optimization options
used.
-Wnrvo (C++ and Objective-C++ only)
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.
106 Using the GNU Compiler Collection (GCC)
std::vector<int> f()
{
std::vector<int> v1, v2;
// ...
if (cond) return v1;
else return v2; // warning: not eliding copy
}
-Winfinite-recursion
Warn about infinitely recursive calls. The warning is effective at all optimization
levels but requires optimization in order to detect infinite recursion in calls
between two or more functions. -Winfinite-recursion is included in -Wall.
Compare with -Wanalyzer-infinite-recursion which provides a similar di-
agnostic, but is implemented in a different way (as part of -fanalyzer).
-Winit-self (C, C++, Objective-C and Objective-C++ only)
Warn about uninitialized variables that are initialized with themselves. Note
this option can only be used with the -Wuninitialized option.
For example, GCC warns about i being uninitialized in the following snippet
only when -Winit-self has been specified:
int f()
{
int i = i;
return i;
}
This warning is enabled by -Wall in C++.
-Wno-implicit-int (C and Objective-C only)
This option controls warnings when a declaration 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.
-Wno-implicit-function-declaration (C and Objective-C only)
This option controls warnings when a function is used before being declared.
This warning is enabled by default, 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.
-Wimplicit (C and Objective-C only)
Same as -Wimplicit-int and -Wimplicit-function-declaration. This
warning is enabled by -Wall.
-Whardened
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.
Chapter 3: GCC Command Options 107
This warning is enabled by default and has effect only when -fhardened is
enabled.
-Wimplicit-fallthrough
-Wimplicit-fallthrough is the same as -Wimplicit-fallthrough=3 and
-Wno-implicit-fallthrough is the same as -Wimplicit-fallthrough=0.
-Wimplicit-fallthrough=n
Warn when a switch case falls through. For example:
switch (cond)
{
case 1:
a = 1;
break;
case 2:
a = 2;
case 3:
a = 3;
break;
}
This warning does not 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
108 Using the GNU Compiler Collection (GCC)
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 com-
ments 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.
-Wno-if-not-aligned (C, C++, Objective-C and Objective-C++ only)
Control if warnings triggered by the warn_if_not_aligned attribute should be
issued. These warnings are enabled by default.
-Wignored-qualifiers (C and C++ only)
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
Chapter 3: GCC Command Options 109
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.
-Wno-ignored-attributes (C and C++ only)
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.
-Wmain 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.
-Wmisleading-indentation (C and C++ only)
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 state-
ment with the same indentation.
In the following example, the call to “bar” is misleadingly indented as if it were
guarded by the “if” conditional.
if (some_condition ())
foo ();
bar (); /* Gotcha: this is not guarded by the "if". */
In the case of mixed tabs and spaces, the warning uses the -ftabstop= option
to determine if the statements line up (defaulting to 8).
The warning is not issued for code involving multiline preprocessor logic such
as the following example.
if (flagA)
foo (0);
#if SOME_CONDITION_THAT_DOES_NOT_HOLD
if (flagB)
#endif
foo (1);
The warning is not issued after a #line directive, since this typically indicates
autogenerated code, and no assumptions can be made about the layout of the
file that the directive references.
This warning is enabled by -Wall in C and C++.
-Wmissing-attributes
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 require-
ments than those of their targets. This typically represents a potential opti-
mization opportunity. By contrast, the -Wattribute-alias=2 option controls
110 Using the GNU Compiler Collection (GCC)
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. (see Section 6.33
[Function Attributes], page 599).
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
(see Section 6.33.1 [Common Function Attributes], page 600), variables
(see Section 6.34.1 [Common Variable Attributes], page 669), or types (see
Section 6.35.1 [Common Type Attributes], page 684).
-Wmissing-attributes is enabled by -Wall.
For example, since the declaration of the primary function template below
makes use of both attribute malloc and alloc_size the declaration of the
explicit specialization of the template is diagnosed because it is missing one of
the attributes.
template <class T>
T* __attribute__ ((malloc, alloc_size (1)))
allocate (size_t);
template <>
void* __attribute__ ((malloc)) // missing alloc_size
allocate<void> (size_t);
-Wmissing-braces
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.
-Wmissing-include-dirs (C, C++, Objective-C, Objective-C++ and Fortran only)
Warn if a user-supplied include directory does not exist. This option is dis-
abled by default for C, C++, Objective-C and Objective-C++. For Fortran, it is
partially enabled by default by warning for -I and -J, only.
-Wno-missing-profile
This option controls warnings if feedback profiles are missing when using the
-fprofile-use option. 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
Chapter 3: GCC Command Options 111
all these cases, warnings are issued to inform you that a profile generation step is
due. Ignoring the warning can result in poorly optimized code. -Wno-missing-
profile can be used to disable the warning, but this is not recommended and
should be done only when non-existent profile data is justified.
-Wmismatched-dealloc
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*);
void f (void)
{
void *p = myalloc (32);
// ...use p...
free (p); // warning: not a matching deallocator for myalloc
mydealloc (p); // ok
}
In C++, the related option -Wmismatched-new-delete diagnoses mismatches
involving either operator new or operator delete.
Option -Wmismatched-dealloc is included in -Wall.
-Wmultistatement-macros
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++.
-Wparentheses
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.
112 Using the GNU Compiler Collection (GCC)
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 unde-
fined. 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 discus-
sions of the problem, including proposed formal definitions, may be found on
the GCC readings page, at https://gcc.gnu.org/readings.html.
This warning is enabled by -Wall for C and C++.
-Wno-return-local-addr
Do not warn about returning a pointer (or in C++, a reference) to a variable
that goes out of scope after the function returns.
-Wreturn-mismatch
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.
-Wreturn-type
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 execu-
tion 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.
114 Using the GNU Compiler Collection (GCC)
Unlike in C, in C++, flowing off the end of a non-void function other than main
results in undefined behavior even when the value of the function is not used.
This warning is enabled by default in C++ and by -Wall otherwise.
-Wno-shift-count-negative
Controls warnings if a shift count is negative. This warning is enabled by
default.
-Wno-shift-count-overflow
Controls warnings if a shift count is greater than or equal to the bit width of
the type. This warning is enabled by default.
-Wshift-negative-value
Warn if left shifting a negative value. This warning is enabled by -Wextra in
C99 (and newer) and C++11 to C++17 modes.
-Wno-shift-overflow
-Wshift-overflow=n
These options control warnings about left shift overflows.
-Wshift-overflow=1
This is the warning level of -Wshift-overflow and is enabled by
default in C99 and C++11 modes (and newer). This warning level
does not warn about left-shifting 1 into the sign bit. (However, in
C, such an overflow is still rejected in contexts where an integer
constant expression is required.) No warning is emitted in C++20
mode (and newer), as signed left shifts always wrap.
-Wshift-overflow=2
This warning level also warns about left-shifting 1 into the sign bit,
unless C++14 mode (or newer) is active.
-Wswitch Warn whenever a switch statement has an index of enumerated type and lacks
a case for one or more of the named codes of that enumeration. (The presence
of a default label prevents this warning.) case labels outside the enumeration
range also provoke warnings when this option is used (even if there is a default
label). This warning is enabled by -Wall.
-Wswitch-default
Warn whenever a switch statement does not have a default case.
-Wswitch-enum
Warn whenever a switch statement has an index of enumerated type and lacks
a case for one or more of the named codes of that enumeration. case labels
outside the enumeration range also provoke warnings when this option is used.
The only difference between -Wswitch and this option is that this option gives
a warning about an omitted enumeration code even if there is a default label.
-Wno-switch-bool
Do not warn when a switch statement has an index of boolean type and the
case values are outside the range of a boolean type. It is possible to suppress
Chapter 3: GCC Command Options 115
this warning by casting the controlling expression to a type other than bool.
For example:
switch ((int) (a == 4))
{
...
}
This warning is enabled by default for C and C++ programs.
-Wno-switch-outside-range
This option controls warnings when a switch case has a value that is outside
of its respective type range. This warning is enabled by default for C and C++
programs.
-Wno-switch-unreachable
Do not warn when a switch statement contains statements between the con-
trolling expression and the first case label, which will never be executed. For
example:
switch (cond)
{
i = 15;
...
case 5:
...
}
-Wswitch-unreachable does not warn if the statement between the controlling
expression and the first case label is just a declaration:
switch (cond)
{
int i;
...
case 5:
i = 5;
...
}
This warning is enabled by default for C and C++ programs.
-Wsync-nand (C and C++ only)
Warn when __sync_fetch_and_nand and __sync_nand_and_fetch built-in
functions are used. These functions changed semantics in GCC 4.4.
-Wtrivial-auto-var-init
Warn when -ftrivial-auto-var-init cannot initialize the automatic vari-
able. A common situation is an automatic variable that is declared between
the controlling expression and the first case label of a switch statement.
-Wunused-but-set-parameter
Warn whenever a function parameter is assigned to, but otherwise unused (aside
from its declaration).
To suppress this warning use the unused attribute (see Section 6.34 [Variable
Attributes], page 669).
This warning is also enabled by -Wunused together with -Wextra.
116 Using the GNU Compiler Collection (GCC)
-Wunused-but-set-variable
Warn whenever a local variable is assigned to, but otherwise unused (aside from
its declaration). This warning is enabled by -Wall.
To suppress this warning use the unused attribute (see Section 6.34 [Variable
Attributes], page 669).
This warning is also enabled by -Wunused, which is enabled by -Wall.
-Wunused-function
Warn whenever a static function is declared but not defined or a non-inline
static function is unused. This warning is enabled by -Wall.
-Wunused-label
Warn whenever a label is declared but not used. This warning is enabled by
-Wall.
To suppress this warning use the unused attribute (see Section 6.34 [Variable
Attributes], page 669).
-Wunused-local-typedefs (C, Objective-C, C++ and Objective-C++ only)
Warn when a typedef locally defined in a function is not used. This warning is
enabled by -Wall.
-Wunused-parameter
Warn whenever a function parameter is unused aside from its declaration. This
option is not enabled by -Wunused unless -Wextra is also specified.
To suppress this warning use the unused attribute (see Section 6.34 [Variable
Attributes], page 669).
-Wno-unused-result
Do not warn if a caller of a function marked with attribute warn_unused_
result (see Section 6.33 [Function Attributes], page 599) does not use its return
value. The default is -Wunused-result.
-Wunused-variable
Warn whenever a local or static variable is unused aside from its declaration.
This option implies -Wunused-const-variable=1 for C, but not for C++. This
warning is enabled by -Wall.
To suppress this warning use the unused attribute (see Section 6.34 [Variable
Attributes], page 669).
-Wunused-const-variable
-Wunused-const-variable=n
Warn whenever a constant static variable is unused aside from its declaration.
To suppress this warning use the unused attribute (see Section 6.34 [Variable
Attributes], page 669).
-Wunused-const-variable=1
Warn about unused static const variables defined in the main com-
pilation unit, but not about static const variables declared in any
header included.
Chapter 3: GCC Command Options 117
-Wuse-after-free=3
At level 3, the warning also diagnoses uses of indeterminate pointers
in equality expressions. All uses of indeterminate pointers are un-
defined 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);
-Wuninitialized
Warn if an object with automatic or allocated storage duration is used without
having been initialized. In C++, also warn if a non-static reference or non-static
const member appears in a class without constructors.
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.)
Chapter 3: GCC Command Options 119
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) { }
};
-Wno-invalid-memory-model
This option controls warnings for invocations of Section 6.57 [ atomic Builtins],
page 776, Section 6.56 [ sync Builtins], page 774, and the C11 atomic generic
functions with a memory consistency argument that is either invalid for the
operation or outside the range of values of the memory_order enumeration. For
example, since the __atomic_store and __atomic_store_n built-ins are only
defined for the relaxed, release, and sequentially consistent memory orders the
following code is diagnosed:
void store (int *i)
{
__atomic_store_n (i, 0, memory_order_consume);
}
-Winvalid-memory-model is enabled by default.
-Wmaybe-uninitialized
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 ob-
ject 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 argu-
ment isn’t used to access the object and avoids the warning (see Section 6.33.1
[Common Function Attributes], page 600).
These warnings are only possible in optimizing compilation, because otherwise
GCC does not keep track of the state of variables.
120 Using the GNU Compiler Collection (GCC)
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. See Section 6.33 [Function Attributes],
page 599.
This warning is enabled by -Wall or -Wextra.
-Wunknown-pragmas
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.
-Wno-pragmas
Do not warn about misuses of pragmas, such as incorrect parameters, invalid
syntax, or conflicts between pragmas. See also -Wunknown-pragmas.
-Wno-prio-ctor-dtor
Do not warn if a priority from 0 to 100 is used for 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.
-Wstrict-aliasing
This option is only active when -fstrict-aliasing is active. It warns about
code that might break the strict aliasing rules that the compiler is using for
optimization. The warning does not catch all cases, but does attempt to catch
Chapter 3: GCC Command Options 121
-Wstrict-aliasing=n
This option is only active when -fstrict-aliasing is active. It warns about
code that might break the strict aliasing rules that the compiler is using for
optimization. Higher levels correspond to higher accuracy (fewer false pos-
itives). 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.
-Wstrict-overflow
-Wstrict-overflow=n
This option is only active when signed overflow is undefined. It warns about
cases where the compiler optimizes based on the assumption that signed over-
flow 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 unde-
fined signed overflow when estimating how many iterations a loop requires, in
particular when determining whether a loop will be executed at all.
-Wstrict-overflow=1
Warn about cases that are both questionable and easy to avoid.
For example the compiler simplifies x + 1 > x to 1. This level of
-Wstrict-overflow is enabled by -Wall; higher levels are not,
and must be explicitly requested.
122 Using the GNU Compiler Collection (GCC)
-Wstrict-overflow=2
Also warn about other cases where a comparison is simplified to a
constant. For example: abs (x) >= 0. This can only be simplified
when signed integer overflow is undefined, because abs (INT_MIN)
overflows to INT_MIN, which is less than zero. -Wstrict-overflow
(with no level) is the same as -Wstrict-overflow=2.
-Wstrict-overflow=3
Also warn about other cases where a comparison is simplified. For
example: x + 1 > 1 is simplified to x > 0.
-Wstrict-overflow=4
Also warn about other simplifications not covered by the above
cases. For example: (x * 10) / 5 is simplified to x * 2.
-Wstrict-overflow=5
Also warn about cases where the compiler reduces the magnitude
of a constant involved in a comparison. For example: x + 2 > y is
simplified to x + 1 >= y. This is reported only at the highest warn-
ing level because this simplification applies to many comparisons,
so this warning level gives a very large number of false positives.
-Wstring-compare
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.
-Wno-stringop-overflow
-Wstringop-overflow
-Wstringop-overflow=type
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. See Section 6.60 [Object Size Checking], page 785.
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
Chapter 3: GCC Command Options 123
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;
}
-Wstringop-overflow
-Wstringop-overflow=1
The -Wstringop-overflow=1 option uses type-zero Object Size
Checking to determine the sizes of destination objects. At this
setting the option does not warn for writes past the end of subob-
jects 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.
-Wstringop-overflow=2
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.
-Wstringop-overflow=3
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.
124 Using the GNU Compiler Collection (GCC)
-Wstringop-overflow=4
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.
-Wno-stringop-overread
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.
-Wno-stringop-truncation
Do not warn for calls to bounded string manipulation functions such as strncat,
strncpy, and stpncpy that may either truncate the copied string or leave the
destination unchanged.
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
Chapter 3: GCC Command Options 125
-Warray-bounds
-Warray-bounds=n
Warn about out of bounds subscripts or offsets into arrays. This warning is
enabled by -Wall. It is more effective when -ftree-vrp is active (the default for
-O2 and above) but a subset of instances are issued even without optimization.
By default, the trailing array of a structure will be treated as a flexible array
member by -Warray-bounds or -Warray-bounds=n if it is declared as either
a flexible array member per C99 standard onwards (‘[]’), a GCC zero-length
array extension (‘[0]’), or an one-element array (‘[1]’). As a result, out of
bounds subscripts or offsets into zero-length arrays or one-element arrays are
not warned by default.
You can add the option -fstrict-flex-arrays or -fstrict-flex-
arrays=level to control how this option treat trailing array of a structure as
a flexible array member:
when level<=1, no change to the default behavior.
when level=2, additional warnings will be issued for out of bounds subscripts
or offsets into one-element arrays;
when level=3, in addition to level=2, additional warnings will be issued for out
of bounds subscripts or offsets into zero-length arrays.
-Warray-bounds=1
This is the default warning level of -Warray-bounds and is enabled
by -Wall; higher levels are not, and must be explicitly requested.
-Warray-bounds=2
This warning level also warns about the intermediate results of
pointer arithmetic that may yield out of bounds values. This warn-
ing level may give a larger number of false positives and is deacti-
vated by default.
Chapter 3: GCC Command Options 129
-Warray-compare
Warn about equality and relational comparisons between two operands of array
type. This comparison was deprecated in C++20. For example:
int arr1[5];
int arr2[5];
bool same = arr1 == arr2;
-Warray-parameter
-Warray-parameter=n
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 in-
consistency 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)
-Wattribute-alias=n
-Wno-attribute-alias
Warn about declarations using the alias and similar attributes whose target is
incompatible with the type of the alias. See Section 6.33 [Declaring Attributes
of Functions], page 599.
-Wattribute-alias=1
The default warning level of the -Wattribute-alias option diag-
noses incompatibilities between the type of the alias declaration and
that of its target. Such incompatibilities are typically indicative of
bugs.
-Wattribute-alias=2
At this level -Wattribute-alias also diagnoses cases where the
attributes of the alias declaration are more restrictive than the at-
tributes applied to its target. These mismatches can potentially
result in incorrect code generation. In other cases they may be be-
nign and could be resolved simply by adding the missing attribute
to the target. For comparison, see the -Wmissing-attributes op-
tion, 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 de-
fault. You can disable these warnings with either -Wno-attribute-alias or
-Wattribute-alias=0.
-Wbidi-chars=[none|unpaired|any|ucn]
Warn about possibly misleading UTF-8 bidirectional control characters in com-
ments, 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.
-Wbool-compare
Warn about boolean expression compared with an integer value different from
true/false. For instance, the following comparison is always false:
int n = 5;
Chapter 3: GCC Command Options 131
...
if ((n > 1) == 2) { ... }
This warning is enabled by -Wall.
-Wbool-operation
Warn about suspicious operations on expressions of a boolean type. For in-
stance, bitwise negation of a boolean is very likely a bug in the program. For
C, this warning also warns about incrementing or decrementing a boolean,
which rarely makes sense. (In C++, decrementing a boolean is always invalid.
Incrementing a boolean is invalid in C++17, and deprecated otherwise.)
This warning is enabled by -Wall.
-Wduplicated-branches
Warn when an if-else has identical branches. This warning detects cases like
if (p != NULL)
return 0;
else
return 0;
It doesn’t warn when both branches contain just a null statement. This warning
also warn for conditional operators:
int i = x ? *p : *p;
-Wduplicated-cond
Warn about duplicated conditions in an if-else-if chain. For instance, warn for
the following code:
if (p->q != NULL) { ... }
else if (p->q != NULL) { ... }
-Wframe-address
Warn when the ‘__builtin_frame_address’ or ‘__builtin_return_address’
is called with an argument greater than 0. Such calls may return indeterminate
values or crash the program. The warning is included in -Wall.
-Wno-discarded-qualifiers (C and Objective-C only)
Do not warn if type qualifiers on pointers are being discarded. Typically, the
compiler warns if a const char * variable is passed to a function that takes a
char * parameter. This option can be used to suppress such a warning.
-Wno-discarded-array-qualifiers (C and Objective-C only)
Do not warn if type qualifiers on arrays which are pointer targets are being
discarded. Typically, the compiler warns if a const int (*)[] variable is passed
to a function that takes a int (*)[] parameter. This option can be used to
suppress such a warning.
-Wno-incompatible-pointer-types (C and Objective-C only)
Do not warn when there is a conversion between pointers that have incompatible
types. This warning is for cases not covered by -Wno-pointer-sign, which
warns for pointer argument passing or assignment with different signedness.
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
132 Using the GNU Compiler Collection (GCC)
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.
-Wtrampolines
Warn about trampolines generated for pointers to nested functions. A tram-
poline 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 re-
quires 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.
-Wfloat-equal
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.
-Wtraditional (C and Objective-C only)
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 tra-
ditional implementations do not recognize #elif, so this option suggests
avoiding it altogether.
• A function-like macro that appears without arguments.
• The unary plus operator.
134 Using the GNU Compiler Collection (GCC)
• 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 com-
patibility macros, PARAMS and VPARAMS. This warning is also bypassed for
nested functions because that feature is already a GCC extension and thus
not relevant to traditional C compatibility.
-Wtraditional-conversion (C and Objective-C only)
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.
-Wdeclaration-after-statement (C and Objective-C only)
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
Chapter 3: GCC Command Options 135
GCC. It is not supported by ISO C90. See Section 6.32 [Mixed Labels and
Declarations], page 599.
This warning is upgraded to an error by -pedantic-errors.
-Wshadow 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.
-Wno-shadow-ivar (Objective-C only)
Do not warn whenever a local variable shadows an instance variable in an
Objective-C method.
-Wshadow=global
Warn for any shadowing. Same as -Wshadow.
-Wshadow=local
Warn when a local variable shadows another local variable or parameter.
-Wshadow=compatible-local
Warn when a local variable shadows another local variable or parameter whose
type is compatible with that of the shadowing variable. In C++, type compatibil-
ity 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 incom-
patible type, it is most likely intentional, not a bug or typo, as shown in the
following example:
for (SomeIterator i = SomeObj.begin(); i != SomeObj.end(); ++i)
{
for (int i = 0; i < N; ++i)
{
...
}
...
}
Since the two variable i in the example above have incompatible types, enabling
only -Wshadow=compatible-local does not emit a warning. Because their
types are incompatible, if a programmer accidentally uses one in place of the
other, type checking is expected to catch that and emit an error or warning.
Use of this flag instead of -Wshadow=local can possibly reduce the number of
warnings triggered by intentional shadowing. Note that this also means that
shadowing const char *i by char *i does not emit a warning.
This warning is also enabled by -Wshadow=local.
-Wlarger-than=byte-size
Warn whenever an object is defined whose size exceeds byte-size. -Wlarger-
than=‘PTRDIFF_MAX’ is enabled by default. Warnings controlled by the option
136 Using the GNU Compiler Collection (GCC)
triggers warnings when the argument in a call to such a function has an unsigned
type. This warning can be suppressed with an explicit type cast and it is also
enabled by -Wextra.
-Wcomment
-Wcomments
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.
-Wtrigraphs
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’.
-Wundef Warn if an undefined identifier is evaluated in an #if directive. Such identifiers
are replaced with zero.
-Wexpansion-to-defined
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.
-Wunused-macros
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
-Wno-endif-labels
Do not warn whenever an #else or an #endif are followed by text. This
sometimes happens in older programs with code of the form
#if FOO
...
#else FOO
...
#endif FOO
The second and third FOO should be in comments. This warning is on by default.
Chapter 3: GCC Command Options 139
-Wcast-align
Warn whenever a pointer is cast such that the required alignment of the target
is increased. For example, warn if a char * is cast to an int * on machines
where integers can only be accessed at two- or four-byte boundaries.
-Wcast-align=strict
Warn whenever a pointer is cast such that the required alignment of the target
is increased. For example, warn if a char * is cast to an int * regardless of the
target machine.
Chapter 3: GCC Command Options 141
-Wcast-function-type
Warn when a function pointer is cast to an incompatible function pointer. In
a cast involving function types with a variable argument list only the types of
initial arguments that are provided are considered. Any parameter of pointer-
type matches any other pointer-type. Any benign differences in integral types
are ignored, like int vs. long on ILP32 targets. Likewise type qualifiers are
ignored. The function type void (*) (void) is special and matches everything,
which can be used to suppress this warning. In a cast involving pointer to
member types this warning warns whenever the type cast is changing the pointer
to member type. This warning is enabled by -Wextra.
-Wwrite-strings
When compiling C, give string constants the type const char[length] so that
copying the address of one into a non-const char * pointer produces a warning.
These warnings help you find at compile time code that can try to write into
a string constant, but only if you have been very careful about using const in
declarations and prototypes. Otherwise, it is just a nuisance. This is why we
did not make -Wall request these warnings.
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.
-Wclobbered
Warn for variables that might be changed by longjmp or vfork. This warning
is also enabled by -Wextra.
-Wno-complain-wrong-lang
By default, language front ends complain when a command-line option is
valid, but not applicable to that front end. This may be disabled with
-Wno-complain-wrong-lang, which is mostly useful when invoking a single
compiler driver for multiple source files written in different languages, for
example:
$ g++ -fno-rtti a.cc b.f90
The driver g++ invokes the C++ front end to compile a.cc and the Fortran
front end to compile b.f90. The latter front end diagnoses ‘f951: Warning:
command-line option '-fno-rtti' is valid for C++/D/ObjC++ but not
for Fortran’, which may be disabled with -Wno-complain-wrong-lang.
-Wcompare-distinct-pointer-types (C and Objective-C only)
Warn if pointers of distinct types are compared without a cast. This warning
is enabled by default.
-Wconversion
Warn for implicit conversions that may alter a value. This includes conversions
between real and integer, like abs (x) when x is double; conversions between
signed and unsigned, like unsigned ui = -1; and conversions to smaller types,
like sqrtf (M_PI). Do not warn for explicit casts like abs ((int) x) and ui
= (unsigned) -1, or if the value is not changed by the conversion like in abs
142 Using the GNU Compiler Collection (GCC)
(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 conver-
sions; and conversions that never use a type conversion operator: conversions
to void, the same type, a base class or a reference to them. Warnings about
conversions between signed and unsigned integers are disabled by default in
C++ unless -Wsign-conversion is explicitly enabled.
Warnings about conversion from arithmetic on a small type back to that type
are only given with -Warith-conversion.
-Wdangling-else
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 ex-
pected, as illustrated in the above example by indentation the programmer
chose. When there is the potential for this confusion, GCC issues a warn-
ing 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.
-Wdangling-pointer
-Wdangling-pointer=n
Warn about uses of pointers (or C++ references) to objects with automatic
storage duration after their lifetime has ended. This includes local variables
declared in nested blocks, compound literals and other unnamed temporary
objects. In addition, warn about storing the address of such objects in es-
caped pointers. The warning is enabled at all optimization levels but may yield
different results with optimization than without.
-Wdangling-pointer=1
At level 1, the warning diagnoses only unconditional uses of dan-
gling pointers.
Chapter 3: GCC Command Options 143
-Wdangling-pointer=2
At level 2, in addition to unconditional uses the warning also diag-
noses conditional uses of dangling pointers.
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);
}
-Wdate-time
Warn when macros __TIME__, __DATE__ or __TIMESTAMP__ are encountered as
they might prevent bit-wise-identical reproducible compilations.
-Wempty-body
Warn if an empty body occurs in an if, else or do while statement. This
warning is also enabled by -Wextra.
-Wno-endif-labels
Do not warn about stray tokens after #else and #endif.
144 Using the GNU Compiler Collection (GCC)
-Wenum-compare
Warn about a comparison between values of different enumerated types. In
C++ enumerated type mismatches in conditional expressions are also diagnosed
and the warning is enabled by default. In C this warning is enabled by -Wall.
-Wenum-conversion
Warn when a value of enumerated type is implicitly converted to a different
enumerated type. This warning is enabled by -Wextra in C.
-Wenum-int-mismatch (C and Objective-C only)
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.
-Wjump-misses-init (C, Objective-C only)
Warn if a goto statement or a switch statement jumps forward across the
initialization of a variable, or jumps backward to a label after the variable has
been initialized. This only warns about variables that are initialized when they
are declared. This warning is only supported for C and Objective-C; in C++
this sort of branch is an error in any case.
-Wjump-misses-init is included in -Wc++-compat. It can be disabled with the
-Wno-jump-misses-init option.
-Wsign-compare
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.
-Wsign-conversion
Warn for implicit conversions that may change the sign of an integer value, like
assigning a signed integer expression to an unsigned integer variable. An explicit
cast silences the warning. In C, this option is enabled also by -Wconversion.
-Wflex-array-member-not-at-end (C and C++ only)
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; };
-Wfloat-conversion
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.
Chapter 3: GCC Command Options 145
-Wno-scalar-storage-order
Do not warn on suspicious constructs involving reverse scalar storage order.
-Wsizeof-array-div
Warn about divisions of two sizeof operators when the first one is applied to an
array and the divisor does not equal the size of the array element. In such a
case, the computation will not yield the number of elements in the array, which
is likely what the user intended. This warning warns e.g. about
int fn ()
{
int arr[10];
return sizeof (arr) / sizeof (short);
}
This warning is enabled by -Wall.
-Wsizeof-pointer-div
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.
-Wsizeof-pointer-memaccess
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 expres-
sion of the source array. For example, in the following function the call to
strncat specifies the size of the source string as the bound. That is almost
certainly a mistake and so the call is diagnosed.
void make_file (const char *name)
{
char path[PATH_MAX];
strncpy (path, name, sizeof path - 1);
strncat (path, ".text", sizeof ".text");
...
}
The -Wsizeof-pointer-memaccess option is enabled by -Wall.
-Wno-sizeof-array-argument
Do not warn when the sizeof operator is applied to a parameter that is declared
as an array in a function definition. This warning is enabled by default for C
and C++ programs.
-Wmemset-elt-size
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.
146 Using the GNU Compiler Collection (GCC)
-Wmemset-transposed-args
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.
-Waddress
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.
-Wno-address-of-packed-member
Do not warn when the address of packed member of struct or union is taken,
which usually results in an unaligned pointer value. This is enabled by default.
-Wlogical-op
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) { ... }
Chapter 3: GCC Command Options 147
-Wlogical-not-parentheses
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.
-Waggregate-return
Warn if any functions that return structures or unions are defined or called. (In
languages where you can return an array, this also elicits a warning.)
-Wno-aggressive-loop-optimizations
Warn if in a loop with constant number of iterations the compiler detects un-
defined behavior in some statement during one or more of the iterations.
-Wno-attributes
Do not warn if an unexpected __attribute__ is used, such as unrecognized
attributes, function attributes applied to variables, etc. This does not stop
errors for incorrect use of supported attributes.
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 us-
ing -Wno-attributes=vendor:: which prevents warning about both of these
declarations:
[[vendor::safe]] void f();
[[vendor::unsafe]] void f2();
Note that -Wno-attributes= does not imply -Wno-attributes.
-Wno-builtin-declaration-mismatch
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.
148 Using the GNU Compiler Collection (GCC)
-Wno-builtin-macro-redefined
Do not warn if certain built-in macros are redefined. This suppresses warn-
ings for redefinition of __TIMESTAMP__, __TIME__, __DATE__, __FILE__, and
__BASE_FILE__.
-Wstrict-prototypes (C and Objective-C only)
Warn if a function is declared or defined without specifying the argument types.
(An old-style function definition is permitted without a warning if preceded by
a declaration that specifies the argument types.)
-Wold-style-declaration (C and Objective-C only)
Warn for obsolescent usages, according to the C Standard, in a declaration. For
example, warn if storage-class specifiers like static are not the first things in
a declaration. This warning is also enabled by -Wextra.
-Wold-style-definition (C and Objective-C only)
Warn if an old-style function definition is used. A warning is given even if there
is a previous prototype. A definition using ‘()’ is not considered an old-style
definition in C23 mode, because it is equivalent to ‘(void)’ in that case, but is
considered an old-style definition for older standards.
-Wmissing-parameter-type (C and Objective-C only)
A function parameter is declared without a type specifier in K&R-style func-
tions:
void foo(bar) { }
This warning is also enabled by -Wextra.
-Wno-declaration-missing-parameter-type (C and Objective-C only)
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.
-Wmissing-prototypes (C and Objective-C only)
Warn if a global function is defined without a previous prototype declaration.
This warning is issued even if the definition itself provides a prototype. Use
this option to detect global functions that do not have a matching prototype
declaration in a header file. This option is not valid for C++ because all func-
tion 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++.
Chapter 3: GCC Command Options 149
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;
and GCC warns if your code is not in NFKC if you use -Wnormalized=nfkc.
This warning is comparable to warning about every identifier that contains the
letter O because it might be confused with the digit 0, and so is not the default,
but may be useful as a local coding convention if the programming environment
cannot be fixed to display these characters distinctly.
-Wno-attribute-warning
Do not warn about usage of functions (see Section 6.33 [Function Attributes],
page 599) declared with warning attribute. By default, this warning is en-
abled. -Wno-attribute-warning can be used to disable the warning or -Wno-
error=attribute-warning can be used to disable the error when compiled
with -Werror flag.
-Wno-deprecated
Do not warn about usage of deprecated features. See Section 7.11 [Deprecated
Features], page 1015.
-Wno-deprecated-declarations
Do not warn about uses of functions (see Section 6.33 [Function Attributes],
page 599), variables (see Section 6.34 [Variable Attributes], page 669), and types
(see Section 6.35 [Type Attributes], page 684) marked as deprecated by using
the deprecated attribute.
-Wno-overflow
Do not warn about compile-time overflow in constant expressions.
-Wno-odr Warn about One Definition Rule violations during link-time optimization. En-
abled by default.
-Wopenacc-parallelism
Warn about potentially suboptimal choices related to OpenACC parallelism.
-Wno-openmp
Warn about suspicious OpenMP code.
-Wopenmp-simd
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.
-Woverride-init (C and Objective-C only)
Warn if an initialized field without side effects is overridden when using desig-
nated initializers (see Section 6.29 [Designated Initializers], page 596).
This warning is included in -Wextra. To get other -Wextra warnings without
this one, use -Wextra -Wno-override-init.
-Wno-override-init-side-effects (C and Objective-C only)
Do not warn if an initialized field with side effects is overridden when using
designated initializers (see Section 6.29 [Designated Initializers], page 596). This
warning is enabled by default.
-Wpacked Warn if a structure is given the packed attribute, but the packed attribute has no
effect on the layout or size of the structure. Such structures may be mis-aligned
152 Using the GNU Compiler Collection (GCC)
for little benefit. For instance, in this code, the variable f.x in struct bar is
misaligned even though struct bar does not itself have the packed attribute:
struct foo {
int x;
char a, b, c, d;
} __attribute__((packed));
struct bar {
char z;
struct foo f;
};
-Wnopacked-bitfield-compat
The 4.1, 4.2 and 4.3 series of GCC ignore the packed attribute on bit-fields of
type char. This was fixed in GCC 4.4 but the change can lead to differences
in the structure layout. GCC informs you when the offset of such a field has
changed in GCC 4.4. For example there is no longer a 4-bit padding between
field a and b in this structure:
struct foo
{
char a:4;
char b:8;
} __attribute__ ((packed));
This warning is enabled by default. Use -Wno-packed-bitfield-compat to
disable this warning.
-Wpacked-not-aligned (C, C++, Objective-C and Objective-C++ only)
Warn if a structure field with explicitly specified alignment in a packed struct
or union is misaligned. For example, a warning will be issued on struct S, like,
warning: alignment 1 of 'struct S' is less than 8, in this code:
struct __attribute__ ((aligned (8))) S8 { char a[8]; };
struct __attribute__ ((packed)) S {
struct S8 s8;
};
This warning is enabled by -Wall.
-Wpadded Warn if padding is included in a structure, either to align an element of the
structure or to align the whole structure. Sometimes when this happens it is
possible to rearrange the fields of the structure to reduce the padding and so
make the structure smaller.
-Wredundant-decls
Warn if anything is declared more than once in the same scope, even in cases
where multiple declaration is valid and changes nothing.
-Wrestrict
Warn when an object referenced by a restrict-qualified parameter (or, in
C++, a __restrict-qualified parameter) is aliased by another argument, or
when copies between such objects overlap. For example, the call to the strcpy
function below attempts to truncate the string by replacing its initial characters
with the last four. However, because the call writes the terminating NUL into
a[4], the copies overlap and the call is diagnosed.
void foo (void)
Chapter 3: GCC Command Options 153
{
char a[] = "abcd1234";
strcpy (a, a + 4);
...
}
The -Wrestrict option detects some instances of simple overlap even without
optimization but works best at -O2 and above. It is included in -Wall.
-Wnested-externs (C and Objective-C only)
Warn if an extern declaration is encountered within a function.
-Winline Warn if a function that is declared as inline cannot be inlined. Even with this
option, the compiler does not warn about failures to inline functions declared
in system headers.
The compiler uses a variety of heuristics to determine whether or not to inline a
function. For example, the compiler takes into account the size of the function
being inlined and the amount of inlining that has already been done in the cur-
rent function. Therefore, seemingly insignificant changes in the source program
can cause the warnings produced by -Winline to appear or disappear.
-Winterference-size
Warn about use of C++17 std::hardware_destructive_interference_size
without specifying its value with --param destructive-interference-size.
Also warn about questionable values for that option.
This variable is intended to be used for controlling class layout, to avoid false
sharing in concurrent code:
struct independent_fields {
alignas(std::hardware_destructive_interference_size)
std::atomic<int> one;
alignas(std::hardware_destructive_interference_size)
std::atomic<int> two;
};
Here ‘one’ and ‘two’ are intended to be far enough apart that stores to one
won’t require accesses to the other to reload the cache line.
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 out-
side a single build of your project, you can turn off the warning with -Wno-
interference-size.
-Wint-in-bool-context
Warn for suspicious use of integer values where boolean values are expected,
such as conditional expressions (?:) using non-boolean integer constants in
154 Using the GNU Compiler Collection (GCC)
-Wvla-larger-than=byte-size
If this option is used, the compiler warns for declarations of variable-length
arrays whose size is either unbounded, or bounded by an argument that allows
the array size to exceed byte-size bytes. This is similar to how -Walloca-
larger-than=byte-size works, but with variable-length arrays.
Note that GCC may optimize small variable-length arrays of a known value
into plain arrays, so this warning may not get triggered for such arrays.
-Wvla-larger-than=‘PTRDIFF_MAX’ is enabled by default but is typically only
effective when -ftree-vrp is active (default for -O2 and above).
See also -Walloca-larger-than=byte-size.
-Wno-vla-larger-than
Disable -Wvla-larger-than= warnings. The option is equivalent to -Wvla-
larger-than=‘SIZE_MAX’ or larger.
-Wvla-parameter
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 pro-
vided 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);
...
}
-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
158 Using the GNU Compiler Collection (GCC)
-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.
-Wanalyzer-symbol-too-complex
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.
-Wanalyzer-too-complex
If -fanalyzer is enabled, the analyzer uses various heuristics to attempt to
explore the control flow and data flow in the program, but these can be defeated
by sufficiently complicated code.
By default, the analysis silently stops if the code is too complicated for the
analyzer to fully explore and it reaches an internal limit. The -Wanalyzer-
too-complex option warns if this occurs.
-Wno-analyzer-allocation-size
This warning requires -fanalyzer, which enables it; to disable it, use -Wno-
analyzer-allocation-size.
This diagnostic warns for paths through the code in which a pointer to a buffer
is assigned to point at a buffer with a size that is not a multiple of sizeof
(*pointer).
See CWE-131: Incorrect Calculation of Buffer Size (https://cwe.mitre.org/
data/definitions/131.html).
-Wno-analyzer-deref-before-check
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-
deref-before-check to disable it.
This diagnostic warns for paths through the code in which a pointer is checked
for NULL *after* it has already been dereferenced, 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.
Chapter 3: GCC Command Options 159
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 ref-
erenced 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.
-Wno-analyzer-fd-double-close
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).
-Wno-analyzer-fd-leak
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).
-Wno-analyzer-fd-phase-mismatch
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).
-Wno-analyzer-fd-type-mismatch
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.
-Wno-analyzer-fd-use-after-close
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.
Chapter 3: GCC Command Options 161
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.
-Wno-analyzer-fd-use-without-check
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.
-Wno-analyzer-file-leak
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-file-
leak to disable it.
This diagnostic warns for paths through the code in which a <stdio.h> FILE
* stream object is leaked.
See CWE-775: Missing Release of File Descriptor or Handle after Effective
Lifetime (https://cwe.mitre.org/data/definitions/775.html).
-Wno-analyzer-free-of-non-heap
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).
-Wno-analyzer-imprecise-fp-arithmetic
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 arith-
metic is used in locations where precise computation is needed. This diagnostic
only warns on use of floating-point operands inside the calculation of an allo-
cation size at the moment.
-Wno-analyzer-infinite-loop
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
162 Using the GNU Compiler Collection (GCC)
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).
-Wno-analyzer-infinite-recursion
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).
-Wno-analyzer-jump-through-null
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.
Chapter 3: GCC Command Options 163
-Wno-analyzer-malloc-leak
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-
malloc-leak to disable it.
This diagnostic warns for paths through the code in which a pointer allocated
via an allocator is leaked: either malloc, or a function marked with attribute
malloc.
See CWE-401: Missing Release of Memory after Effective Lifetime (https://
cwe.mitre.org/data/definitions/401.html).
-Wno-analyzer-mismatching-deallocation
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-
mismatching-deallocation to disable it.
This diagnostic warns for paths through the code in which the wrong deal-
location 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 allo-
cator/deallocator pairs using attribute malloc.
See CWE-762: Mismatched Memory Management Routines (https://cwe.
mitre.org/data/definitions/762.html).
-Wno-analyzer-out-of-bounds
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 an-
alyzer 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.
-Wno-analyzer-overlapping-buffers
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
164 Using the GNU Compiler Collection (GCC)
• strcpy
for cases where the buffers are known to overlap.
-Wno-analyzer-possible-null-argument
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-
possible-null-argument to disable it.
This diagnostic warns for paths through the code in which a possibly-NULL
value is passed to a function argument marked with __attribute__
((nonnull)) as requiring a non-NULL value.
See CWE-690: Unchecked Return Value to NULL Pointer Dereference
(https://cwe.mitre.org/data/definitions/690.html).
-Wno-analyzer-possible-null-dereference
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-
possible-null-dereference to disable it.
This diagnostic warns for paths through the code in which a possibly-NULL
value is dereferenced.
See CWE-690: Unchecked Return Value to NULL Pointer Dereference
(https://cwe.mitre.org/data/definitions/690.html).
-Wno-analyzer-null-argument
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-null-
argument to disable it.
This diagnostic warns for paths through the code in which a value known
to be NULL is passed to a function argument marked with __attribute__
((nonnull)) as requiring a non-NULL value.
See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/
definitions/476.html).
-Wno-analyzer-null-dereference
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-null-
dereference to disable it.
This diagnostic warns for paths through the code in which a value known to be
NULL is dereferenced.
See CWE-476: NULL Pointer Dereference (https://cwe.mitre.org/data/
definitions/476.html).
-Wno-analyzer-putenv-of-auto-var
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).
-Wno-analyzer-shift-count-negative
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-
shift-count-negative to disable it.
Chapter 3: GCC Command Options 165
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 di-
agnostic 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 neg-
atives are more likely relative to other warnings.
-Wno-analyzer-shift-count-overflow
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-
shift-count-overflow to disable it.
This diagnostic warns for paths through the code in which a shift is attempted
with a count greater than or equal to the precision of the operand’s type.
It is analogous to the -Wshift-count-overflow diagnostic implemented in
the C/C++ front ends, but is implemented based on analyzing interprocedural
paths, rather than merely parsing the syntax tree. However, the analyzer does
not prioritize detection of such paths, so false negatives are more likely relative
to other warnings.
-Wno-analyzer-stale-setjmp-buffer
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-
stale-setjmp-buffer to disable it.
This diagnostic warns for paths through the code in which longjmp is called to
rewind to a jmp_buf relating to a setjmp call in a function that has returned.
When setjmp is called on a jmp_buf to record a rewind location, it records the
stack frame. The stack frame becomes invalid when the function containing the
setjmp call returns. Attempting to rewind to it via longjmp would reference a
stack frame that no longer exists, and likely lead to a crash (or worse).
-Wno-analyzer-tainted-allocation-size
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).
-Wno-analyzer-tainted-assertion
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 typi-
cally indicate abnormal termination of the program, such as for assertion failure
handlers. For example:
assert (some_tainted_value < SOME_LIMIT);
166 Using the GNU Compiler Collection (GCC)
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 re-
moved 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 opti-
mizer 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.
-Wno-analyzer-tainted-array-index
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).
-Wno-analyzer-tainted-divisor
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).
Chapter 3: GCC Command Options 167
-Wno-analyzer-tainted-offset
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).
-Wno-analyzer-tainted-size
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 ac-
cess.
See CWE-129: Improper Validation of Array Index (https://cwe.mitre.org/
data/definitions/129.html).
-Wno-analyzer-undefined-behavior-strtok
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.
-Wno-analyzer-unsafe-call-within-signal-handler
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-
unsafe-call-within-signal-handler to disable it.
This diagnostic warns for paths through the code in which a function known to
be async-signal-unsafe (such as fprintf) is called from a signal handler.
See CWE-479: Signal Handler Use of a Non-reentrant Function (https://cwe.
mitre.org/data/definitions/479.html).
-Wno-analyzer-use-after-free
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-use-
after-free to disable it.
This diagnostic warns for paths through the code in which a pointer is used
after a deallocator is called on it: either free, or a deallocator referenced by
attribute malloc.
See CWE-416: Use After Free (https://cwe.mitre.org/data/definitions/
416.html).
-Wno-analyzer-use-of-pointer-in-stale-stack-frame
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-use-
of-pointer-in-stale-stack-frame to disable it.
168 Using the GNU Compiler Collection (GCC)
This diagnostic warns for paths through the code in which a pointer is derefer-
enced that points to a variable in a stale stack frame.
-Wno-analyzer-va-arg-type-mismatch
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).
-Wno-analyzer-va-list-exhausted
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).
-Wno-analyzer-va-list-leak
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.
-Wno-analyzer-va-list-use-after-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.
-Wno-analyzer-write-to-const
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-
write-to-const to disable it.
This diagnostic warns for paths through the code in which the analyzer detects
an attempt to write through a pointer to a const object. However, the analyzer
does not prioritize detection of such paths, so false negatives are more likely
relative to other warnings.
-Wno-analyzer-write-to-string-literal
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-
write-to-string-literal to disable it.
This diagnostic warns for paths through the code in which the analyzer detects
an attempt to write through a pointer to a string literal. However, the analyzer
Chapter 3: GCC Command Options 169
does not prioritize detection of such paths, so false negatives are more likely
relative to other warnings.
-Wno-analyzer-use-of-uninitialized-value
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,
• __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
• --param analyzer-min-snodes-for-call-summary=value
The following options control the analyzer.
-fanalyzer-call-summaries
Simplify interprocedural analysis by computing the effect of certain calls, rather
than exploring all paths through the function from callsite to each possible
return.
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).
-fanalyzer-checker=name
Restrict the analyzer to run just the named checker, and enable it.
-fanalyzer-debug-text-art-headings
This option is intended for analyzer developers. If enabled, the analyzer will
add extra annotations to any diagrams it generates.
-fno-analyzer-feasibility
This option is intended for analyzer developers.
By default the analyzer verifies that there is a feasible control flow path for each
diagnostic it emits: that the conditions that hold are not mutually exclusive.
Diagnostics for which no feasible path can be found are rejected. This filtering
can be suppressed with -fno-analyzer-feasibility, for debugging issues in
this code.
-fanalyzer-fine-grained
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 multi-
ple statements within a basic block. With -fanalyzer-fine-grained, each
statement gets its own edge.
-fanalyzer-show-duplicate-count
This option is intended for analyzer developers: if multiple diagnostics have
been detected as being duplicates of each other, it emits a note when report-
ing the best diagnostic, giving the number of additional diagnostics that were
suppressed by the deduplication logic.
-fanalyzer-show-events-in-system-headers
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.
-fno-analyzer-state-merge
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.
172 Using the GNU Compiler Collection (GCC)
-fno-analyzer-state-purge
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.
-fno-analyzer-suppress-followups
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 ex-
plore such paths even after such diagnostics, which may be helpful for debugging
issues in the analyzer, or for microbenchmarks for detecting undefined behavior.
-fanalyzer-transitivity
This option enables transitivity of constraints within the analyzer.
-fno-analyzer-undo-inlining
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 func-
tion 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 be disabled, which may be of help when debugging
issues in the analyzer.
-fanalyzer-verbose-edges
This option is intended for analyzer developers. It enables more verbose, lower-
level detail in the descriptions of control flow within diagnostic paths.
-fanalyzer-verbose-state-changes
This option is intended for analyzer developers. It enables more verbose, lower-
level detail in the descriptions of events relating to state machines within diag-
nostic paths.
Chapter 3: GCC Command Options 173
-fanalyzer-verbosity=level
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.
-fdump-analyzer
Dump internal details about what the analyzer is doing to file.analyzer.txt.
-fdump-analyzer-stderr overrides this option.
-fdump-analyzer-stderr
Dump internal details about what the analyzer is doing to stderr. This option
overrides -fdump-analyzer.
-fdump-analyzer-callgraph
Dump a representation of the call graph suitable for viewing with GraphViz to
file.callgraph.dot.
-fdump-analyzer-exploded-graph
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.
-fdump-analyzer-exploded-nodes
Emit diagnostics showing where nodes in the “exploded graph” are in relation
to the program source.
-fdump-analyzer-exploded-nodes-2
Dump a textual representation of the “exploded graph” to file.eg.txt.
-fdump-analyzer-exploded-nodes-3
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.
-fdump-analyzer-exploded-paths
Dump a textual representation of the “exploded path” for each diagnostic to
file.idx.kind.epath.txt.
174 Using the GNU Compiler Collection (GCC)
-fdump-analyzer-feasibility
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.
-fdump-analyzer-infinite-loop
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.
-fdump-analyzer-json
Dump a compressed JSON representation of analyzer internals to
file.analyzer.json.gz. The precise format is subject to change.
-fdump-analyzer-state-purge
As per -fdump-analyzer-supergraph, dump a representation of the “super-
graph” suitable for viewing with GraphViz, but annotate the graph with in-
formation on what state will be purged at each node. The graph is written to
file.state-purge.dot.
-fdump-analyzer-supergraph
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.
-fdump-analyzer-untracked
Emit custom warnings with internal details intended for analyzer developers.
On most systems that use stabs format, -g enables use of extra debugging
information that only GDB can use; this extra information makes debugging
work better in GDB but probably makes other debuggers crash or refuse to
read the program. If you want to control for certain whether to generate the
extra information, use -gvms (see below).
-ggdb Produce debugging information for use by GDB. This means to use the most
expressive format available (DWARF, stabs, or the native format if neither of
those are supported), including GDB extensions if at all possible.
-gdwarf
-gdwarf-version
Produce debugging information in DWARF format (if that is supported). The
value of version may be either 2, 3, 4 or 5; the default version for most targets
is 5 (with the exception of VxWorks, TPF and Darwin / 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 maxi-
mum benefit. Version 5 requires GDB 8.0 or higher.
GCC no longer supports DWARF Version 1, which is substantially different
than Version 2 and later. For historical reasons, some other DWARF-related
options such as -fno-dwarf2-cfi-asm) retain a reference to DWARF Version
2 in their names, but apply to all currently-supported versions of DWARF.
-gbtf Request BTF debug information. BTF is the default debugging format for the
eBPF target. On other targets, like x86, BTF debug information can be gen-
erated along with DWARF debug information when both of the debug formats
are enabled explicitly via their respective command line options.
-gctf
-gctflevel
Request CTF debug information and use level to specify how much CTF debug
information should be produced. If -gctf is specified without a value for level,
the default level of CTF debug information is 2.
CTF debug information can be generated along with DWARF debug informa-
tion when both of the debug formats are enabled explicitly via their respective
command line options.
Level 0 produces no CTF debug information at all. Thus, -gctf0 negates
-gctf.
Level 1 produces CTF information for tracebacks only. This includes callsite
information, but does not include type information.
Level 2 produces type information for entities (functions, data objects etc.) at
file-scope or global-scope only.
-gvms Produce debugging information in Alpha/VMS debug format (if that is sup-
ported). This is the format used by DEBUG on Alpha/VMS systems.
176 Using the GNU Compiler Collection (GCC)
-gcodeview
Produce debugging information in CodeView debug format (if that is sup-
ported). This is the format used by Microsoft Visual C++ on Windows.
-glevel
-ggdblevel
-gvmslevel
Request debugging information and also use level to specify how much infor-
mation. 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.
-fno-eliminate-unused-debug-symbols
By default, no debug information is produced for symbols that are not actually
used. Use this option if you want debug information for all symbols.
-femit-class-debug-always
Instead of emitting debugging information for a C++ class in only one object file,
emit it in all object files using the class. This option should be used only with
debuggers that are unable to handle the way GCC normally emits debugging
information for classes because using this option increases the size of debugging
information by as much as a factor of two.
-fno-merge-debug-strings
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.
-fdebug-prefix-map=old=new
When compiling files residing in directory old, record debugging information
describing them as i